blob: c45dd3f4f9576c6d4c5bac2f56212c83969de201 [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
Seth Moore5a0320f2023-03-24 12:29:08 -0700593std::shared_ptr<IRemotelyProvisionedComponent> matching_rp_instance(const std::string& km_name) {
David Drysdale4dc01072021-04-01 12:17:35 +0100594 string km_suffix = device_suffix(km_name);
595
596 vector<string> rp_names =
597 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
598 for (const string& rp_name : rp_names) {
599 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
600 // KeyMint instance, assume they match.
601 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
602 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
Seth Moore5a0320f2023-03-24 12:29:08 -0700603 return IRemotelyProvisionedComponent::fromBinder(binder);
David Drysdale4dc01072021-04-01 12:17:35 +0100604 }
605 }
Seth Moore5a0320f2023-03-24 12:29:08 -0700606 return nullptr;
David Drysdale4dc01072021-04-01 12:17:35 +0100607}
608
Selene Huang31ab4042020-04-29 04:22:39 -0700609} // namespace
610
611class NewKeyGenerationTest : public KeyMintAidlTestBase {
612 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700613 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000614 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
Selene Huang31ab4042020-04-29 04:22:39 -0700615 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700616
Selene Huang31ab4042020-04-29 04:22:39 -0700617 // Check that some unexpected tags/values are NOT present.
618 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
619 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000620 }
621
622 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000623 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
David Drysdale7de9feb2021-03-05 14:56:19 +0000624 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
625 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
626
627 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000628 }
629
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000630 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics,
631 const KeyOrigin expectedKeyOrigin) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000632 // TODO(swillden): Distinguish which params should be in which auth list.
633 AuthorizationSet auths;
634 for (auto& entry : keyCharacteristics) {
635 auths.push_back(AuthorizationSet(entry.authorizations));
636 }
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000637 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, expectedKeyOrigin));
David Drysdale7de9feb2021-03-05 14:56:19 +0000638
639 // Verify that App data, ROT and auth timeout are NOT included.
640 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
641 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700642 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
643
David Drysdaled2cc8c22021-04-15 13:29:45 +0100644 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
645 // never adds it.
646 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
647
David Drysdale7de9feb2021-03-05 14:56:19 +0000648 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700649 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000650 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700651 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700652 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000653 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700654 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000655
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000656 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100657 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
658 EXPECT_TRUE(vendor_pl);
659 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000660
661 // Should include boot patchlevel (but there are some test scenarios where this is not
662 // possible).
663 if (check_boot_pl) {
664 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
665 EXPECT_TRUE(boot_pl);
666 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100667
David Drysdale7de9feb2021-03-05 14:56:19 +0000668 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700669 }
670};
671
672/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000673 * NewKeyGenerationTest.Aes
674 *
675 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
676 * have correct characteristics.
677 */
678TEST_P(NewKeyGenerationTest, Aes) {
679 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
680 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
681 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
682 SCOPED_TRACE(testing::Message()
683 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
684 vector<uint8_t> key_blob;
685 vector<KeyCharacteristics> key_characteristics;
686 auto builder = AuthorizationSetBuilder()
687 .AesEncryptionKey(key_size)
688 .BlockMode(block_mode)
689 .Padding(padding_mode)
690 .SetDefaultValidity();
691 if (block_mode == BlockMode::GCM) {
692 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
693 }
694 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
695
696 EXPECT_GT(key_blob.size(), 0U);
697 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100698 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000699
700 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
701
702 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
703 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
704 << "Key size " << key_size << "missing";
705
706 CheckedDeleteKey(&key_blob);
707 }
708 }
709 }
710}
711
712/*
713 * NewKeyGenerationTest.AesInvalidSize
714 *
715 * Verifies that specifying an invalid key size for AES key generation returns
716 * UNSUPPORTED_KEY_SIZE.
717 */
718TEST_P(NewKeyGenerationTest, AesInvalidSize) {
719 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
720 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
721 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
722 SCOPED_TRACE(testing::Message()
723 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
724 vector<uint8_t> key_blob;
725 vector<KeyCharacteristics> key_characteristics;
726 auto builder = AuthorizationSetBuilder()
727 .AesEncryptionKey(key_size)
728 .BlockMode(block_mode)
729 .Padding(padding_mode)
730 .SetDefaultValidity();
731 if (block_mode == BlockMode::GCM) {
732 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
733 }
734 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
735 GenerateKey(builder, &key_blob, &key_characteristics));
736 }
737 }
738 }
739
740 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
741 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100742 SCOPED_TRACE(testing::Message() << "AES-unknown-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000743 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)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100996 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -0700997 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700998 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700999 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1000 .RsaSigningKey(key_size, 65537)
1001 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001002 .Padding(PaddingMode::NONE)
1003 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001004 &key_blob, &key_characteristics));
1005
1006 ASSERT_GT(key_blob.size(), 0U);
1007 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001008 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001009
Shawn Willden7f424372021-01-10 18:06:50 -07001010 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001011
1012 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1013 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1014 << "Key size " << key_size << "missing";
1015 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1016
1017 CheckedDeleteKey(&key_blob);
1018 }
1019}
1020
1021/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001022 * NewKeyGenerationTest.RsaWithMissingValidity
1023 *
1024 * Verifies that keymint returns an error while generating asymmetric key
1025 * without providing NOT_BEFORE and NOT_AFTER parameters.
1026 */
1027TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
Seth Moore7dc1fda2022-12-12 16:56:20 -08001028 if (AidlVersion() < 3) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001029 /*
1030 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1031 * specified for asymmetric key generation. However, this was not
1032 * checked at the time so we can only be strict about checking this for
1033 * implementations of KeyMint version 2 and above.
1034 */
1035 GTEST_SKIP() << "Validity strict since KeyMint v2";
1036 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001037 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1038 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1039 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1040
1041 vector<uint8_t> key_blob;
1042 vector<KeyCharacteristics> key_characteristics;
1043 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1044 GenerateKey(AuthorizationSetBuilder()
1045 .RsaSigningKey(2048, 65537)
1046 .Digest(Digest::NONE)
1047 .Padding(PaddingMode::NONE)
1048 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1049 kUndefinedExpirationDateTime),
1050 &key_blob, &key_characteristics));
1051
1052 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1053 GenerateKey(AuthorizationSetBuilder()
1054 .RsaSigningKey(2048, 65537)
1055 .Digest(Digest::NONE)
1056 .Padding(PaddingMode::NONE)
1057 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1058 &key_blob, &key_characteristics));
1059}
1060
1061/*
Qi Wud22ec842020-11-26 13:27:53 +08001062 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001063 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001064 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1065 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001066 */
1067TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001068 auto challenge = "hello";
1069 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001070
Selene Huang6e46f142021-04-20 19:20:11 -07001071 auto subject = "cert subj 2";
1072 vector<uint8_t> subject_der(make_name_from_str(subject));
1073
1074 uint64_t serial_int = 66;
1075 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1076
Selene Huang4f64c222021-04-13 19:54:36 -07001077 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001078 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001079 vector<uint8_t> key_blob;
1080 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001081 auto builder = AuthorizationSetBuilder()
1082 .RsaSigningKey(key_size, 65537)
1083 .Digest(Digest::NONE)
1084 .Padding(PaddingMode::NONE)
1085 .AttestationChallenge(challenge)
1086 .AttestationApplicationId(app_id)
1087 .Authorization(TAG_NO_AUTH_REQUIRED)
1088 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1089 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1090 .SetDefaultValidity();
1091
1092 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001093 // Strongbox may not support factory provisioned attestation key.
1094 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001095 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1096 result = GenerateKeyWithSelfSignedAttestKey(
1097 AuthorizationSetBuilder()
1098 .RsaKey(key_size, 65537)
1099 .AttestKey()
1100 .SetDefaultValidity(), /* attest key params */
1101 builder, &key_blob, &key_characteristics);
1102 }
subrahmanyaman05642492022-02-05 07:10:56 +00001103 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001104 ASSERT_EQ(ErrorCode::OK, result);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001105 ASSERT_GT(key_blob.size(), 0U);
1106 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001107 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001108
1109 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1110
1111 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1112 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1113 << "Key size " << key_size << "missing";
1114 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1115
David Drysdalea8a888e2022-06-08 12:43:56 +01001116 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001117 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001118 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001119
1120 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1121 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001122 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001123 sw_enforced, hw_enforced, SecLevel(),
1124 cert_chain_[0].encodedCertificate));
1125
1126 CheckedDeleteKey(&key_blob);
1127 }
1128}
1129
1130/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001131 * NewKeyGenerationTest.RsaWithRkpAttestation
David Drysdale4dc01072021-04-01 12:17:35 +01001132 *
Seth Moore7dc1fda2022-12-12 16:56:20 -08001133 * Verifies that keymint can generate all required RSA key sizes using an attestation key
David Drysdale4dc01072021-04-01 12:17:35 +01001134 * that has been generated using an associate IRemotelyProvisionedComponent.
1135 */
Seth Moore7dc1fda2022-12-12 16:56:20 -08001136TEST_P(NewKeyGenerationTest, RsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001137 if (!IsRkpSupportRequired()) {
1138 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001139 }
1140
Seth Moore5a0320f2023-03-24 12:29:08 -07001141 // Check for an IRemotelyProvisionedComponent instance associated with the
1142 // KeyMint instance.
1143 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1144 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1145 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1146 }
1147 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1148 << GetParam();
David Drysdale4dc01072021-04-01 12:17:35 +01001149
1150 // Generate a P-256 keypair to use as an attestation key.
1151 MacedPublicKey macedPubKey;
1152 std::vector<uint8_t> privateKeyBlob;
1153 auto status =
1154 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1155 ASSERT_TRUE(status.isOk());
1156 vector<uint8_t> coseKeyData;
1157 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1158
1159 AttestationKey attestation_key;
1160 attestation_key.keyBlob = std::move(privateKeyBlob);
1161 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1162
1163 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001164 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdale4dc01072021-04-01 12:17:35 +01001165 auto challenge = "hello";
1166 auto app_id = "foo";
1167
1168 vector<uint8_t> key_blob;
1169 vector<KeyCharacteristics> key_characteristics;
1170 ASSERT_EQ(ErrorCode::OK,
1171 GenerateKey(AuthorizationSetBuilder()
1172 .RsaSigningKey(key_size, 65537)
1173 .Digest(Digest::NONE)
1174 .Padding(PaddingMode::NONE)
1175 .AttestationChallenge(challenge)
1176 .AttestationApplicationId(app_id)
1177 .Authorization(TAG_NO_AUTH_REQUIRED)
1178 .SetDefaultValidity(),
1179 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1180
1181 ASSERT_GT(key_blob.size(), 0U);
1182 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001183 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001184
1185 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1186
1187 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1188 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1189 << "Key size " << key_size << "missing";
1190 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1191
1192 // Attestation by itself is not valid (last entry is not self-signed).
1193 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1194
1195 // The signature over the attested key should correspond to the P256 public key.
David Drysdalea8a888e2022-06-08 12:43:56 +01001196 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale4dc01072021-04-01 12:17:35 +01001197 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1198 ASSERT_TRUE(key_cert.get());
1199 EVP_PKEY_Ptr signing_pubkey;
1200 p256_pub_key(coseKeyData, &signing_pubkey);
1201 ASSERT_TRUE(signing_pubkey.get());
1202
1203 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1204 << "Verification of attested certificate failed "
1205 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1206
1207 CheckedDeleteKey(&key_blob);
1208 }
1209}
1210
1211/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001212 * NewKeyGenerationTest.EcdsaWithRkpAttestation
1213 *
1214 * Verifies that keymint can generate all required ECDSA key sizes using an attestation key
1215 * that has been generated using an associate IRemotelyProvisionedComponent.
1216 */
1217TEST_P(NewKeyGenerationTest, EcdsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001218 if (!IsRkpSupportRequired()) {
1219 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001220 }
1221
Seth Moore5a0320f2023-03-24 12:29:08 -07001222 // Check for an IRemotelyProvisionedComponent instance associated with the
1223 // KeyMint instance.
1224 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1225 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1226 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1227 }
1228 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1229 << GetParam();
Seth Moore7dc1fda2022-12-12 16:56:20 -08001230
1231 // Generate a P-256 keypair to use as an attestation key.
1232 MacedPublicKey macedPubKey;
1233 std::vector<uint8_t> privateKeyBlob;
1234 auto status =
1235 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1236 ASSERT_TRUE(status.isOk());
1237 vector<uint8_t> coseKeyData;
1238 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1239
1240 AttestationKey attestation_key;
1241 attestation_key.keyBlob = std::move(privateKeyBlob);
1242 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1243
1244 for (auto curve : ValidCurves()) {
1245 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
1246 auto challenge = "hello";
1247 auto app_id = "foo";
1248
1249 vector<uint8_t> key_blob;
1250 vector<KeyCharacteristics> key_characteristics;
1251 ASSERT_EQ(ErrorCode::OK,
1252 GenerateKey(AuthorizationSetBuilder()
1253 .EcdsaSigningKey(curve)
1254 .Digest(Digest::NONE)
1255 .AttestationChallenge(challenge)
1256 .AttestationApplicationId(app_id)
1257 .Authorization(TAG_NO_AUTH_REQUIRED)
1258 .SetDefaultValidity(),
1259 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1260
1261 ASSERT_GT(key_blob.size(), 0U);
1262 CheckBaseParams(key_characteristics);
1263 CheckCharacteristics(key_blob, key_characteristics);
1264
1265 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1266
1267 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1268 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1269
1270 // Attestation by itself is not valid (last entry is not self-signed).
1271 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1272
1273 // The signature over the attested key should correspond to the P256 public key.
1274 ASSERT_GT(cert_chain_.size(), 0);
1275 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1276 ASSERT_TRUE(key_cert.get());
1277 EVP_PKEY_Ptr signing_pubkey;
1278 p256_pub_key(coseKeyData, &signing_pubkey);
1279 ASSERT_TRUE(signing_pubkey.get());
1280
1281 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1282 << "Verification of attested certificate failed "
1283 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1284
1285 CheckedDeleteKey(&key_blob);
1286 }
1287}
1288
1289/*
Selene Huang4f64c222021-04-13 19:54:36 -07001290 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1291 *
1292 * Verifies that keymint attestation for RSA encryption keys with challenge and
1293 * app id is also successful.
1294 */
1295TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1296 auto key_size = 2048;
1297 auto challenge = "hello";
1298 auto app_id = "foo";
1299
Selene Huang6e46f142021-04-20 19:20:11 -07001300 auto subject = "subj 2";
1301 vector<uint8_t> subject_der(make_name_from_str(subject));
1302
1303 uint64_t serial_int = 111166;
1304 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1305
Selene Huang4f64c222021-04-13 19:54:36 -07001306 vector<uint8_t> key_blob;
1307 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001308 auto builder = AuthorizationSetBuilder()
1309 .RsaEncryptionKey(key_size, 65537)
1310 .Padding(PaddingMode::NONE)
1311 .AttestationChallenge(challenge)
1312 .AttestationApplicationId(app_id)
1313 .Authorization(TAG_NO_AUTH_REQUIRED)
1314 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1315 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1316 .SetDefaultValidity();
1317
1318 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001319 // Strongbox may not support factory provisioned attestation key.
1320 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001321 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1322 result = GenerateKeyWithSelfSignedAttestKey(
1323 AuthorizationSetBuilder()
1324 .RsaKey(key_size, 65537)
1325 .AttestKey()
1326 .SetDefaultValidity(), /* attest key params */
1327 builder, &key_blob, &key_characteristics);
1328 }
subrahmanyaman05642492022-02-05 07:10:56 +00001329 }
1330 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001331
1332 ASSERT_GT(key_blob.size(), 0U);
1333 AuthorizationSet auths;
1334 for (auto& entry : key_characteristics) {
1335 auths.push_back(AuthorizationSet(entry.authorizations));
1336 }
1337
1338 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1339 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1340
1341 // Verify that App data and ROT are NOT included.
1342 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1343 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1344
1345 // Check that some unexpected tags/values are NOT present.
1346 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1347 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1348
1349 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1350
1351 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1352 ASSERT_TRUE(os_ver);
1353 EXPECT_EQ(*os_ver, os_version());
1354
1355 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1356
1357 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1358 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1359 << "Key size " << key_size << "missing";
1360 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1361
David Drysdalea8a888e2022-06-08 12:43:56 +01001362 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001363 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001364 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001365
1366 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1367 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001368 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001369 sw_enforced, hw_enforced, SecLevel(),
1370 cert_chain_[0].encodedCertificate));
1371
1372 CheckedDeleteKey(&key_blob);
1373}
1374
1375/*
1376 * NewKeyGenerationTest.RsaWithSelfSign
1377 *
1378 * Verifies that attesting to RSA key generation is successful, and returns
1379 * self signed certificate if no challenge is provided. And signing etc
1380 * works as expected.
1381 */
1382TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001383 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1384 vector<uint8_t> subject_der(make_name_from_str(subject));
1385
1386 uint64_t serial_int = 0;
1387 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1388
Selene Huang4f64c222021-04-13 19:54:36 -07001389 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001390 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang4f64c222021-04-13 19:54:36 -07001391 vector<uint8_t> key_blob;
1392 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001393 ASSERT_EQ(ErrorCode::OK,
1394 GenerateKey(AuthorizationSetBuilder()
1395 .RsaSigningKey(key_size, 65537)
1396 .Digest(Digest::NONE)
1397 .Padding(PaddingMode::NONE)
1398 .Authorization(TAG_NO_AUTH_REQUIRED)
1399 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1400 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1401 .SetDefaultValidity(),
1402 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001403
1404 ASSERT_GT(key_blob.size(), 0U);
1405 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001406 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001407
1408 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1409
1410 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1411 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1412 << "Key size " << key_size << "missing";
1413 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1414
David Drysdalea8a888e2022-06-08 12:43:56 +01001415 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang6e46f142021-04-20 19:20:11 -07001416 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001417 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001418
1419 CheckedDeleteKey(&key_blob);
1420 }
1421}
1422
1423/*
1424 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1425 *
1426 * Verifies that attesting to RSA checks for missing app ID.
1427 */
1428TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1429 auto challenge = "hello";
1430 vector<uint8_t> key_blob;
1431 vector<KeyCharacteristics> key_characteristics;
1432
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001433 auto builder = AuthorizationSetBuilder()
1434 .RsaSigningKey(2048, 65537)
1435 .Digest(Digest::NONE)
1436 .Padding(PaddingMode::NONE)
1437 .AttestationChallenge(challenge)
1438 .Authorization(TAG_NO_AUTH_REQUIRED)
1439 .SetDefaultValidity();
1440
1441 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001442 // Strongbox may not support factory provisioned attestation key.
1443 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001444 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1445 result = GenerateKeyWithSelfSignedAttestKey(
1446 AuthorizationSetBuilder()
1447 .RsaKey(2048, 65537)
1448 .AttestKey()
1449 .SetDefaultValidity(), /* attest key params */
1450 builder, &key_blob, &key_characteristics);
1451 }
subrahmanyaman05642492022-02-05 07:10:56 +00001452 }
1453 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001454}
1455
1456/*
1457 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1458 *
1459 * Verifies that attesting to RSA ignores app id if challenge is missing.
1460 */
1461TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1462 auto key_size = 2048;
1463 auto app_id = "foo";
1464
Selene Huang6e46f142021-04-20 19:20:11 -07001465 auto subject = "cert subj 2";
1466 vector<uint8_t> subject_der(make_name_from_str(subject));
1467
1468 uint64_t serial_int = 1;
1469 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1470
Selene Huang4f64c222021-04-13 19:54:36 -07001471 vector<uint8_t> key_blob;
1472 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001473 ASSERT_EQ(ErrorCode::OK,
1474 GenerateKey(AuthorizationSetBuilder()
1475 .RsaSigningKey(key_size, 65537)
1476 .Digest(Digest::NONE)
1477 .Padding(PaddingMode::NONE)
1478 .AttestationApplicationId(app_id)
1479 .Authorization(TAG_NO_AUTH_REQUIRED)
1480 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1481 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1482 .SetDefaultValidity(),
1483 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001484
1485 ASSERT_GT(key_blob.size(), 0U);
1486 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001487 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001488
1489 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1490
1491 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1492 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1493 << "Key size " << key_size << "missing";
1494 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1495
David Drysdalea8a888e2022-06-08 12:43:56 +01001496 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001497 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001498 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1499 ASSERT_EQ(cert_chain_.size(), 1);
1500
1501 CheckedDeleteKey(&key_blob);
1502}
1503
1504/*
Qi Wud22ec842020-11-26 13:27:53 +08001505 * NewKeyGenerationTest.LimitedUsageRsa
1506 *
1507 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1508 * resulting keys have correct characteristics.
1509 */
1510TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1511 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001512 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wud22ec842020-11-26 13:27:53 +08001513 vector<uint8_t> key_blob;
1514 vector<KeyCharacteristics> key_characteristics;
1515 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1516 .RsaSigningKey(key_size, 65537)
1517 .Digest(Digest::NONE)
1518 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001519 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1520 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001521 &key_blob, &key_characteristics));
1522
1523 ASSERT_GT(key_blob.size(), 0U);
1524 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001525 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001526
1527 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1528
1529 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1530 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1531 << "Key size " << key_size << "missing";
1532 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1533
1534 // Check the usage count limit tag appears in the authorizations.
1535 AuthorizationSet auths;
1536 for (auto& entry : key_characteristics) {
1537 auths.push_back(AuthorizationSet(entry.authorizations));
1538 }
1539 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1540 << "key usage count limit " << 1U << " missing";
1541
1542 CheckedDeleteKey(&key_blob);
1543 }
1544}
1545
1546/*
Qi Wubeefae42021-01-28 23:16:37 +08001547 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1548 *
1549 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1550 * resulting keys have correct characteristics and attestation.
1551 */
1552TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001553 auto challenge = "hello";
1554 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001555
Selene Huang6e46f142021-04-20 19:20:11 -07001556 auto subject = "cert subj 2";
1557 vector<uint8_t> subject_der(make_name_from_str(subject));
1558
1559 uint64_t serial_int = 66;
1560 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1561
Selene Huang4f64c222021-04-13 19:54:36 -07001562 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001563 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wubeefae42021-01-28 23:16:37 +08001564 vector<uint8_t> key_blob;
1565 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001566 auto builder = AuthorizationSetBuilder()
1567 .RsaSigningKey(key_size, 65537)
1568 .Digest(Digest::NONE)
1569 .Padding(PaddingMode::NONE)
1570 .AttestationChallenge(challenge)
1571 .AttestationApplicationId(app_id)
1572 .Authorization(TAG_NO_AUTH_REQUIRED)
1573 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1574 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1575 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1576 .SetDefaultValidity();
1577
1578 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001579 // Strongbox may not support factory provisioned attestation key.
1580 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001581 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1582 result = GenerateKeyWithSelfSignedAttestKey(
1583 AuthorizationSetBuilder()
1584 .RsaKey(key_size, 65537)
1585 .AttestKey()
1586 .SetDefaultValidity(), /* attest key params */
1587 builder, &key_blob, &key_characteristics);
1588 }
subrahmanyaman05642492022-02-05 07:10:56 +00001589 }
1590 ASSERT_EQ(ErrorCode::OK, result);
Qi Wubeefae42021-01-28 23:16:37 +08001591
1592 ASSERT_GT(key_blob.size(), 0U);
1593 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001594 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001595
1596 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1597
1598 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1599 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1600 << "Key size " << key_size << "missing";
1601 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1602
1603 // Check the usage count limit tag appears in the authorizations.
1604 AuthorizationSet auths;
1605 for (auto& entry : key_characteristics) {
1606 auths.push_back(AuthorizationSet(entry.authorizations));
1607 }
1608 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1609 << "key usage count limit " << 1U << " missing";
1610
1611 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001612 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001613 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001614 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001615
1616 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1617 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001618 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001619 sw_enforced, hw_enforced, SecLevel(),
1620 cert_chain_[0].encodedCertificate));
1621
1622 CheckedDeleteKey(&key_blob);
1623 }
1624}
1625
1626/*
Selene Huang31ab4042020-04-29 04:22:39 -07001627 * NewKeyGenerationTest.NoInvalidRsaSizes
1628 *
1629 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1630 */
1631TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1632 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001633 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07001634 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001635 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001636 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1637 GenerateKey(AuthorizationSetBuilder()
1638 .RsaSigningKey(key_size, 65537)
1639 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001640 .Padding(PaddingMode::NONE)
1641 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001642 &key_blob, &key_characteristics));
1643 }
1644}
1645
1646/*
1647 * NewKeyGenerationTest.RsaNoDefaultSize
1648 *
1649 * Verifies that failing to specify a key size for RSA key generation returns
1650 * UNSUPPORTED_KEY_SIZE.
1651 */
1652TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1653 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1654 GenerateKey(AuthorizationSetBuilder()
1655 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1656 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001657 .SigningKey()
1658 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001659}
1660
1661/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001662 * NewKeyGenerationTest.RsaMissingParams
1663 *
1664 * Verifies that omitting optional tags works.
1665 */
1666TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1667 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001668 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdaled2cc8c22021-04-15 13:29:45 +01001669 ASSERT_EQ(ErrorCode::OK,
1670 GenerateKey(
1671 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1672 CheckedDeleteKey();
1673 }
1674}
1675
1676/*
Selene Huang31ab4042020-04-29 04:22:39 -07001677 * NewKeyGenerationTest.Ecdsa
1678 *
David Drysdale42fe1892021-10-14 14:43:46 +01001679 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001680 * have correct characteristics.
1681 */
1682TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001683 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001684 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07001685 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001686 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001687 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001688 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001689 .Digest(Digest::NONE)
1690 .SetDefaultValidity(),
1691 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001692 ASSERT_GT(key_blob.size(), 0U);
1693 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001694 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001695
Shawn Willden7f424372021-01-10 18:06:50 -07001696 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001697
1698 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001699 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001700
1701 CheckedDeleteKey(&key_blob);
1702 }
1703}
1704
1705/*
David Drysdale42fe1892021-10-14 14:43:46 +01001706 * NewKeyGenerationTest.EcdsaCurve25519
1707 *
1708 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1709 * has correct characteristics.
1710 */
1711TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1712 if (!Curve25519Supported()) {
1713 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1714 }
1715
1716 EcCurve curve = EcCurve::CURVE_25519;
1717 vector<uint8_t> key_blob;
1718 vector<KeyCharacteristics> key_characteristics;
1719 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1720 .EcdsaSigningKey(curve)
1721 .Digest(Digest::NONE)
1722 .SetDefaultValidity(),
1723 &key_blob, &key_characteristics);
1724 ASSERT_EQ(result, ErrorCode::OK);
1725 ASSERT_GT(key_blob.size(), 0U);
1726
1727 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1728 ASSERT_GT(cert_chain_.size(), 0);
1729
1730 CheckBaseParams(key_characteristics);
1731 CheckCharacteristics(key_blob, key_characteristics);
1732
1733 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1734
1735 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1736 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1737
1738 CheckedDeleteKey(&key_blob);
1739}
1740
1741/*
1742 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1743 *
1744 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1745 * SIGN and AGREE_KEY.
1746 */
1747TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1748 if (!Curve25519Supported()) {
1749 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1750 }
1751
1752 EcCurve curve = EcCurve::CURVE_25519;
1753 vector<uint8_t> key_blob;
1754 vector<KeyCharacteristics> key_characteristics;
1755 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1756 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1757 .EcdsaSigningKey(curve)
1758 .Digest(Digest::NONE)
1759 .SetDefaultValidity(),
1760 &key_blob, &key_characteristics);
1761 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1762}
1763
1764/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001765 * NewKeyGenerationTest.EcdsaWithMissingValidity
1766 *
1767 * Verifies that keymint returns an error while generating asymmetric key
1768 * without providing NOT_BEFORE and NOT_AFTER parameters.
1769 */
1770TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001771 if (AidlVersion() < 2) {
1772 /*
1773 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1774 * specified for asymmetric key generation. However, this was not
1775 * checked at the time so we can only be strict about checking this for
1776 * implementations of KeyMint version 2 and above.
1777 */
1778 GTEST_SKIP() << "Validity strict since KeyMint v2";
1779 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001780 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1781 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1782 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1783
1784 vector<uint8_t> key_blob;
1785 vector<KeyCharacteristics> key_characteristics;
1786 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1787 GenerateKey(AuthorizationSetBuilder()
1788 .EcdsaSigningKey(EcCurve::P_256)
1789 .Digest(Digest::NONE)
1790 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1791 kUndefinedExpirationDateTime),
1792 &key_blob, &key_characteristics));
1793
1794 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1795 GenerateKey(AuthorizationSetBuilder()
1796 .EcdsaSigningKey(EcCurve::P_256)
1797 .Digest(Digest::NONE)
1798 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1799 &key_blob, &key_characteristics));
1800}
1801
1802/*
Selene Huang4f64c222021-04-13 19:54:36 -07001803 * NewKeyGenerationTest.EcdsaAttestation
1804 *
1805 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1806 * an attestation will be generated.
1807 */
1808TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1809 auto challenge = "hello";
1810 auto app_id = "foo";
1811
Selene Huang6e46f142021-04-20 19:20:11 -07001812 auto subject = "cert subj 2";
1813 vector<uint8_t> subject_der(make_name_from_str(subject));
1814
1815 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1816 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1817
David Drysdaledf09e542021-06-08 15:46:11 +01001818 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001819 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07001820 vector<uint8_t> key_blob;
1821 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001822 auto builder = AuthorizationSetBuilder()
1823 .Authorization(TAG_NO_AUTH_REQUIRED)
1824 .EcdsaSigningKey(curve)
1825 .Digest(Digest::NONE)
1826 .AttestationChallenge(challenge)
1827 .AttestationApplicationId(app_id)
1828 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1829 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1830 .SetDefaultValidity();
1831
1832 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001833 // Strongbox may not support factory provisioned attestation key.
1834 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001835 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1836 result = GenerateKeyWithSelfSignedAttestKey(
1837 AuthorizationSetBuilder()
1838 .EcdsaKey(curve)
1839 .AttestKey()
1840 .SetDefaultValidity(), /* attest key params */
1841 builder, &key_blob, &key_characteristics);
1842 }
subrahmanyaman05642492022-02-05 07:10:56 +00001843 }
1844 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001845 ASSERT_GT(key_blob.size(), 0U);
1846 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001847 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001848
1849 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1850
1851 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001852 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001853
1854 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1855 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001856 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001857
1858 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1859 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001860 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001861 sw_enforced, hw_enforced, SecLevel(),
1862 cert_chain_[0].encodedCertificate));
1863
1864 CheckedDeleteKey(&key_blob);
1865 }
1866}
1867
1868/*
David Drysdale42fe1892021-10-14 14:43:46 +01001869 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1870 *
1871 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1872 * an attestation will be generated.
1873 */
1874TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1875 if (!Curve25519Supported()) {
1876 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1877 }
1878
1879 EcCurve curve = EcCurve::CURVE_25519;
1880 auto challenge = "hello";
1881 auto app_id = "foo";
1882
1883 auto subject = "cert subj 2";
1884 vector<uint8_t> subject_der(make_name_from_str(subject));
1885
1886 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1887 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1888
1889 vector<uint8_t> key_blob;
1890 vector<KeyCharacteristics> key_characteristics;
1891 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1892 .Authorization(TAG_NO_AUTH_REQUIRED)
1893 .EcdsaSigningKey(curve)
1894 .Digest(Digest::NONE)
1895 .AttestationChallenge(challenge)
1896 .AttestationApplicationId(app_id)
1897 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1898 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1899 .SetDefaultValidity(),
1900 &key_blob, &key_characteristics);
1901 ASSERT_EQ(ErrorCode::OK, result);
1902 ASSERT_GT(key_blob.size(), 0U);
1903 CheckBaseParams(key_characteristics);
1904 CheckCharacteristics(key_blob, key_characteristics);
1905
1906 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1907
1908 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1909 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1910
1911 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1912 ASSERT_GT(cert_chain_.size(), 0);
1913 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1914
1915 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1916 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1917 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1918 sw_enforced, hw_enforced, SecLevel(),
1919 cert_chain_[0].encodedCertificate));
1920
1921 CheckedDeleteKey(&key_blob);
1922}
1923
1924/*
David Drysdale37af4b32021-05-14 16:46:59 +01001925 * NewKeyGenerationTest.EcdsaAttestationTags
1926 *
1927 * Verifies that creation of an attested ECDSA key includes various tags in the
1928 * attestation extension.
1929 */
1930TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1931 auto challenge = "hello";
1932 auto app_id = "foo";
1933 auto subject = "cert subj 2";
1934 vector<uint8_t> subject_der(make_name_from_str(subject));
1935 uint64_t serial_int = 0x1010;
1936 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1937 const AuthorizationSetBuilder base_builder =
1938 AuthorizationSetBuilder()
1939 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001940 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001941 .Digest(Digest::NONE)
1942 .AttestationChallenge(challenge)
1943 .AttestationApplicationId(app_id)
1944 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1945 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1946 .SetDefaultValidity();
1947
1948 // Various tags that map to fields in the attestation extension ASN.1 schema.
1949 auto extra_tags = AuthorizationSetBuilder()
1950 .Authorization(TAG_ROLLBACK_RESISTANCE)
1951 .Authorization(TAG_EARLY_BOOT_ONLY)
1952 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1953 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1954 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1955 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1956 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1957 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1958 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1959 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1960 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1961 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001962
David Drysdale37af4b32021-05-14 16:46:59 +01001963 for (const KeyParameter& tag : extra_tags) {
1964 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1965 vector<uint8_t> key_blob;
1966 vector<KeyCharacteristics> key_characteristics;
1967 AuthorizationSetBuilder builder = base_builder;
1968 builder.push_back(tag);
1969 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1970 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1971 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1972 continue;
1973 }
Seth Mooreb393b082021-07-12 14:18:28 -07001974 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1975 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001976 continue;
1977 }
subrahmanyaman05642492022-02-05 07:10:56 +00001978 // Strongbox may not support factory provisioned attestation key.
1979 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001980 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1981 result = GenerateKeyWithSelfSignedAttestKey(
1982 AuthorizationSetBuilder()
1983 .EcdsaKey(EcCurve::P_256)
1984 .AttestKey()
1985 .SetDefaultValidity(), /* attest key params */
1986 builder, &key_blob, &key_characteristics);
1987 }
subrahmanyaman05642492022-02-05 07:10:56 +00001988 }
David Drysdale37af4b32021-05-14 16:46:59 +01001989 ASSERT_EQ(result, ErrorCode::OK);
1990 ASSERT_GT(key_blob.size(), 0U);
1991
1992 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1993 ASSERT_GT(cert_chain_.size(), 0);
1994 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1995
1996 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1997 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001998 // Some tags are optional, so don't require them to be in the enforcements.
1999 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01002000 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
2001 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
2002 }
2003
2004 // Verifying the attestation record will check for the specific tag because
2005 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002006 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2007 hw_enforced, SecLevel(),
2008 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002009
2010 CheckedDeleteKey(&key_blob);
2011 }
2012
David Drysdalec53b7d92021-10-11 12:35:58 +01002013 // Collection of invalid attestation ID tags.
2014 auto invalid_tags =
2015 AuthorizationSetBuilder()
2016 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
2017 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
2018 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
2019 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
2020 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
2021 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
2022 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
2023 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01002024 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01002025 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01002026 vector<uint8_t> key_blob;
2027 vector<KeyCharacteristics> key_characteristics;
2028 AuthorizationSetBuilder builder =
2029 AuthorizationSetBuilder()
2030 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002031 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01002032 .Digest(Digest::NONE)
2033 .AttestationChallenge(challenge)
2034 .AttestationApplicationId(app_id)
2035 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2036 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2037 .SetDefaultValidity();
2038 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002039
2040 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
2041 // Strongbox may not support factory provisioned attestation key.
2042 if (SecLevel() == SecurityLevel::STRONGBOX) {
2043 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2044 error = GenerateKeyWithSelfSignedAttestKey(
2045 AuthorizationSetBuilder()
2046 .EcdsaKey(EcCurve::P_256)
2047 .AttestKey()
2048 .SetDefaultValidity(), /* attest key params */
2049 builder, &key_blob, &key_characteristics);
2050 }
2051 }
2052 ASSERT_EQ(error, ErrorCode::CANNOT_ATTEST_IDS);
David Drysdale37af4b32021-05-14 16:46:59 +01002053 }
2054}
2055
2056/*
David Drysdalec53b7d92021-10-11 12:35:58 +01002057 * NewKeyGenerationTest.EcdsaAttestationIdTags
2058 *
2059 * Verifies that creation of an attested ECDSA key includes various ID tags in the
2060 * attestation extension.
2061 */
2062TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
David Drysdale555ba002022-05-03 18:48:57 +01002063 if (is_gsi_image()) {
2064 // GSI sets up a standard set of device identifiers that may not match
2065 // the device identifiers held by the device.
2066 GTEST_SKIP() << "Test not applicable under GSI";
2067 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002068 auto challenge = "hello";
2069 auto app_id = "foo";
2070 auto subject = "cert subj 2";
2071 vector<uint8_t> subject_der(make_name_from_str(subject));
2072 uint64_t serial_int = 0x1010;
2073 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2074 const AuthorizationSetBuilder base_builder =
2075 AuthorizationSetBuilder()
2076 .Authorization(TAG_NO_AUTH_REQUIRED)
2077 .EcdsaSigningKey(EcCurve::P_256)
2078 .Digest(Digest::NONE)
2079 .AttestationChallenge(challenge)
2080 .AttestationApplicationId(app_id)
2081 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2082 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2083 .SetDefaultValidity();
2084
2085 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
2086 auto extra_tags = AuthorizationSetBuilder();
Prashant Patil8d779bf2022-09-28 16:09:29 +01002087 // Use ro.product.brand_for_attestation property for attestation if it is present else fallback
2088 // to ro.product.brand
2089 std::string prop_value =
2090 ::android::base::GetProperty("ro.product.brand_for_attestation", /* default= */ "");
2091 if (!prop_value.empty()) {
2092 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND,
2093 "ro.product.brand_for_attestation");
2094 } else {
2095 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
2096 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002097 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
Prashant Patil8d779bf2022-09-28 16:09:29 +01002098 // Use ro.product.name_for_attestation property for attestation if it is present else fallback
2099 // to ro.product.name
2100 prop_value = ::android::base::GetProperty("ro.product.name_for_attestation", /* default= */ "");
2101 if (!prop_value.empty()) {
2102 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT,
2103 "ro.product.name_for_attestation");
2104 } else {
2105 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
2106 }
Tri Vo799e4352022-11-07 17:23:50 -08002107 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
David Drysdalec53b7d92021-10-11 12:35:58 +01002108 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
Prashant Patil8d779bf2022-09-28 16:09:29 +01002109 // Use ro.product.model_for_attestation property for attestation if it is present else fallback
2110 // to ro.product.model
2111 prop_value =
2112 ::android::base::GetProperty("ro.product.model_for_attestation", /* default= */ "");
2113 if (!prop_value.empty()) {
2114 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL,
2115 "ro.product.model_for_attestation");
2116 } else {
2117 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
2118 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002119
2120 for (const KeyParameter& tag : extra_tags) {
2121 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2122 vector<uint8_t> key_blob;
2123 vector<KeyCharacteristics> key_characteristics;
2124 AuthorizationSetBuilder builder = base_builder;
2125 builder.push_back(tag);
2126 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002127 // Strongbox may not support factory provisioned attestation key.
2128 if (SecLevel() == SecurityLevel::STRONGBOX) {
2129 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2130 }
Prashant Patil88ad1892022-03-15 16:31:02 +00002131 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2132 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01002133 continue;
2134 }
2135 ASSERT_EQ(result, ErrorCode::OK);
2136 ASSERT_GT(key_blob.size(), 0U);
2137
2138 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2139 ASSERT_GT(cert_chain_.size(), 0);
2140 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2141
2142 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2143 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2144
2145 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2146 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2147 // attestation extension should contain them, so make sure the extra tag is added.
2148 hw_enforced.push_back(tag);
2149
2150 // Verifying the attestation record will check for the specific tag because
2151 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002152 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2153 hw_enforced, SecLevel(),
2154 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002155
2156 CheckedDeleteKey(&key_blob);
2157 }
2158}
2159
2160/*
David Drysdale565ccc72021-10-11 12:49:50 +01002161 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2162 *
2163 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2164 */
2165TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2166 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002167 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002168 auto challenge = "hello";
2169 auto subject = "cert subj 2";
2170 vector<uint8_t> subject_der(make_name_from_str(subject));
2171 uint64_t serial_int = 0x1010;
2172 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002173 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002174 AuthorizationSetBuilder()
2175 .Authorization(TAG_NO_AUTH_REQUIRED)
2176 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2177 .EcdsaSigningKey(EcCurve::P_256)
2178 .Digest(Digest::NONE)
2179 .AttestationChallenge(challenge)
2180 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2181 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2182 .AttestationApplicationId(app_id)
2183 .Authorization(TAG_CREATION_DATETIME, datetime)
2184 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002185 if (reset) {
2186 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2187 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002188 auto result = GenerateKey(builder);
2189 if (SecLevel() == SecurityLevel::STRONGBOX) {
2190 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2191 result = GenerateKeyWithSelfSignedAttestKey(
2192 AuthorizationSetBuilder()
2193 .EcdsaKey(EcCurve::P_256)
2194 .AttestKey()
2195 .SetDefaultValidity(), /* attest key params */
2196 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2197 }
2198 }
2199 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002200 ASSERT_GT(key_blob_.size(), 0U);
2201
2202 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2203 ASSERT_GT(cert_chain_.size(), 0);
2204 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2205
2206 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2207 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2208
2209 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002210 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2211 hw_enforced, SecLevel(),
2212 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002213 EXPECT_GT(unique_id->size(), 0);
2214 CheckedDeleteKey();
2215 };
2216
2217 // Generate unique ID
2218 auto app_id = "foo";
2219 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2220 vector<uint8_t> unique_id;
2221 get_unique_id(app_id, cert_date, &unique_id);
2222
2223 // Generating a new key with the same parameters should give the same unique ID.
2224 vector<uint8_t> unique_id2;
2225 get_unique_id(app_id, cert_date, &unique_id2);
2226 EXPECT_EQ(unique_id, unique_id2);
2227
2228 // Generating a new key with a slightly different date should give the same unique ID.
2229 uint64_t rounded_date = cert_date / 2592000000LLU;
2230 uint64_t min_date = rounded_date * 2592000000LLU;
2231 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2232
2233 vector<uint8_t> unique_id3;
2234 get_unique_id(app_id, min_date, &unique_id3);
2235 EXPECT_EQ(unique_id, unique_id3);
2236
2237 vector<uint8_t> unique_id4;
2238 get_unique_id(app_id, max_date, &unique_id4);
2239 EXPECT_EQ(unique_id, unique_id4);
2240
2241 // A different attestation application ID should yield a different unique ID.
2242 auto app_id2 = "different_foo";
2243 vector<uint8_t> unique_id5;
2244 get_unique_id(app_id2, cert_date, &unique_id5);
2245 EXPECT_NE(unique_id, unique_id5);
2246
2247 // A radically different date should yield a different unique ID.
2248 vector<uint8_t> unique_id6;
2249 get_unique_id(app_id, 1611621648000, &unique_id6);
2250 EXPECT_NE(unique_id, unique_id6);
2251
2252 vector<uint8_t> unique_id7;
2253 get_unique_id(app_id, max_date + 1, &unique_id7);
2254 EXPECT_NE(unique_id, unique_id7);
2255
2256 vector<uint8_t> unique_id8;
2257 get_unique_id(app_id, min_date - 1, &unique_id8);
2258 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002259
2260 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2261 vector<uint8_t> unique_id9;
2262 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2263 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002264}
2265
2266/*
David Drysdale37af4b32021-05-14 16:46:59 +01002267 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2268 *
2269 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2270 */
2271TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2272 auto challenge = "hello";
2273 auto attest_app_id = "foo";
2274 auto subject = "cert subj 2";
2275 vector<uint8_t> subject_der(make_name_from_str(subject));
2276 uint64_t serial_int = 0x1010;
2277 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2278
2279 // Earlier versions of the attestation extension schema included a slot:
2280 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2281 // This should never have been included, and should never be filled in.
2282 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2283 // to confirm that this field never makes it into the attestation extension.
2284 vector<uint8_t> key_blob;
2285 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002286 auto builder = AuthorizationSetBuilder()
2287 .Authorization(TAG_NO_AUTH_REQUIRED)
2288 .EcdsaSigningKey(EcCurve::P_256)
2289 .Digest(Digest::NONE)
2290 .AttestationChallenge(challenge)
2291 .AttestationApplicationId(attest_app_id)
2292 .Authorization(TAG_APPLICATION_ID, "client_id")
2293 .Authorization(TAG_APPLICATION_DATA, "appdata")
2294 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2295 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2296 .SetDefaultValidity();
2297
2298 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002299 // Strongbox may not support factory provisioned attestation key.
2300 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002301 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2302 result = GenerateKeyWithSelfSignedAttestKey(
2303 AuthorizationSetBuilder()
2304 .EcdsaKey(EcCurve::P_256)
2305 .AttestKey()
2306 .SetDefaultValidity(), /* attest key params */
2307 builder, &key_blob, &key_characteristics);
2308 }
subrahmanyaman05642492022-02-05 07:10:56 +00002309 }
David Drysdale37af4b32021-05-14 16:46:59 +01002310 ASSERT_EQ(result, ErrorCode::OK);
2311 ASSERT_GT(key_blob.size(), 0U);
2312
2313 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2314 ASSERT_GT(cert_chain_.size(), 0);
2315 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2316
2317 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2318 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002319 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2320 hw_enforced, SecLevel(),
2321 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002322
2323 // Check that the app id is not in the cert.
2324 string app_id = "clientid";
2325 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2326 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2327 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2328 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2329 cert_chain_[0].encodedCertificate.end());
2330
2331 CheckedDeleteKey(&key_blob);
2332}
2333
2334/*
Selene Huang4f64c222021-04-13 19:54:36 -07002335 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2336 *
2337 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2338 * the key will generate a self signed attestation.
2339 */
2340TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002341 auto subject = "cert subj 2";
2342 vector<uint8_t> subject_der(make_name_from_str(subject));
2343
2344 uint64_t serial_int = 0x123456FFF1234;
2345 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2346
David Drysdaledf09e542021-06-08 15:46:11 +01002347 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002348 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002349 vector<uint8_t> key_blob;
2350 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002351 ASSERT_EQ(ErrorCode::OK,
2352 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002353 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002354 .Digest(Digest::NONE)
2355 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2356 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2357 .SetDefaultValidity(),
2358 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002359 ASSERT_GT(key_blob.size(), 0U);
2360 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002361 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002362
2363 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2364
2365 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002366 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002367
2368 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2369 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002370 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002371
2372 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2373 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2374
2375 CheckedDeleteKey(&key_blob);
2376 }
2377}
2378
2379/*
2380 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2381 *
2382 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2383 * app id must also be provided or else it will fail.
2384 */
2385TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2386 auto challenge = "hello";
2387 vector<uint8_t> key_blob;
2388 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002389 auto builder = AuthorizationSetBuilder()
2390 .EcdsaSigningKey(EcCurve::P_256)
2391 .Digest(Digest::NONE)
2392 .AttestationChallenge(challenge)
2393 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002394
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002395 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002396 // Strongbox may not support factory provisioned attestation key.
2397 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002398 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2399 result = GenerateKeyWithSelfSignedAttestKey(
2400 AuthorizationSetBuilder()
2401 .EcdsaKey(EcCurve::P_256)
2402 .AttestKey()
2403 .SetDefaultValidity(), /* attest key params */
2404 builder, &key_blob, &key_characteristics);
2405 }
subrahmanyaman05642492022-02-05 07:10:56 +00002406 }
2407 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002408}
2409
2410/*
2411 * NewKeyGenerationTest.EcdsaIgnoreAppId
2412 *
2413 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2414 * any appid will be ignored, and keymint will generate a self sign certificate.
2415 */
2416TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2417 auto app_id = "foo";
2418
David Drysdaledf09e542021-06-08 15:46:11 +01002419 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002420 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002421 vector<uint8_t> key_blob;
2422 vector<KeyCharacteristics> key_characteristics;
2423 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002424 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002425 .Digest(Digest::NONE)
2426 .AttestationApplicationId(app_id)
2427 .SetDefaultValidity(),
2428 &key_blob, &key_characteristics));
2429
2430 ASSERT_GT(key_blob.size(), 0U);
2431 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002432 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002433
2434 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2435
2436 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002437 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002438
2439 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2440 ASSERT_EQ(cert_chain_.size(), 1);
2441
2442 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2443 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2444
2445 CheckedDeleteKey(&key_blob);
2446 }
2447}
2448
2449/*
2450 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2451 *
2452 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2453 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2454 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2455 * to specify how many following bytes will be used to encode the length.
2456 */
2457TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2458 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002459 std::vector<uint32_t> app_id_lengths{143, 258};
2460
2461 for (uint32_t length : app_id_lengths) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002462 SCOPED_TRACE(testing::Message() << "app_id_len=" << length);
Selene Huang4f64c222021-04-13 19:54:36 -07002463 const string app_id(length, 'a');
2464 vector<uint8_t> key_blob;
2465 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002466 auto builder = AuthorizationSetBuilder()
2467 .Authorization(TAG_NO_AUTH_REQUIRED)
2468 .EcdsaSigningKey(EcCurve::P_256)
2469 .Digest(Digest::NONE)
2470 .AttestationChallenge(challenge)
2471 .AttestationApplicationId(app_id)
2472 .SetDefaultValidity();
2473
2474 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002475 // Strongbox may not support factory provisioned attestation key.
2476 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002477 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2478 result = GenerateKeyWithSelfSignedAttestKey(
2479 AuthorizationSetBuilder()
2480 .EcdsaKey(EcCurve::P_256)
2481 .AttestKey()
2482 .SetDefaultValidity(), /* attest key params */
2483 builder, &key_blob, &key_characteristics);
2484 }
subrahmanyaman05642492022-02-05 07:10:56 +00002485 }
2486 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002487 ASSERT_GT(key_blob.size(), 0U);
2488 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002489 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002490
2491 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2492
2493 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002494 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002495
2496 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2497 ASSERT_GT(cert_chain_.size(), 0);
2498
2499 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2500 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002501 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002502 sw_enforced, hw_enforced, SecLevel(),
2503 cert_chain_[0].encodedCertificate));
2504
2505 CheckedDeleteKey(&key_blob);
2506 }
2507}
2508
2509/*
Qi Wud22ec842020-11-26 13:27:53 +08002510 * NewKeyGenerationTest.LimitedUsageEcdsa
2511 *
2512 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2513 * resulting keys have correct characteristics.
2514 */
2515TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002516 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002517 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Qi Wud22ec842020-11-26 13:27:53 +08002518 vector<uint8_t> key_blob;
2519 vector<KeyCharacteristics> key_characteristics;
2520 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002521 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002522 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002523 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2524 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002525 &key_blob, &key_characteristics));
2526
2527 ASSERT_GT(key_blob.size(), 0U);
2528 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002529 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002530
2531 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2532
2533 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002534 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002535
2536 // Check the usage count limit tag appears in the authorizations.
2537 AuthorizationSet auths;
2538 for (auto& entry : key_characteristics) {
2539 auths.push_back(AuthorizationSet(entry.authorizations));
2540 }
2541 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2542 << "key usage count limit " << 1U << " missing";
2543
2544 CheckedDeleteKey(&key_blob);
2545 }
2546}
2547
2548/*
Selene Huang31ab4042020-04-29 04:22:39 -07002549 * NewKeyGenerationTest.EcdsaDefaultSize
2550 *
David Drysdaledf09e542021-06-08 15:46:11 +01002551 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002552 * UNSUPPORTED_KEY_SIZE.
2553 */
2554TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2555 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2556 GenerateKey(AuthorizationSetBuilder()
2557 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2558 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002559 .Digest(Digest::NONE)
2560 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002561}
2562
2563/*
David Drysdale42fe1892021-10-14 14:43:46 +01002564 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002565 *
David Drysdale42fe1892021-10-14 14:43:46 +01002566 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002567 * UNSUPPORTED_KEY_SIZE.
2568 */
David Drysdale42fe1892021-10-14 14:43:46 +01002569TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002570 for (auto curve : InvalidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002571 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07002572 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002573 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002574 auto result = GenerateKey(AuthorizationSetBuilder()
2575 .EcdsaSigningKey(curve)
2576 .Digest(Digest::NONE)
2577 .SetDefaultValidity(),
2578 &key_blob, &key_characteristics);
2579 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2580 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002581 }
2582
David Drysdaledf09e542021-06-08 15:46:11 +01002583 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2584 GenerateKey(AuthorizationSetBuilder()
2585 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2586 .Authorization(TAG_KEY_SIZE, 190)
2587 .SigningKey()
2588 .Digest(Digest::NONE)
2589 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002590}
2591
2592/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002593 * NewKeyGenerationTest.EcdsaMissingCurve
2594 *
2595 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
2596 */
2597TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2598 if (AidlVersion() < 2) {
2599 /*
2600 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2601 * However, this was not checked at the time so we can only be strict about checking this
2602 * for implementations of KeyMint version 2 and above.
2603 */
2604 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
2605 }
2606 /* If EC_CURVE not provided, generateKey
2607 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2608 */
2609 auto result = GenerateKey(
2610 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2611 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2612 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2613}
2614
2615/*
Selene Huang31ab4042020-04-29 04:22:39 -07002616 * NewKeyGenerationTest.EcdsaMismatchKeySize
2617 *
2618 * Verifies that specifying mismatched key size and curve for EC key generation returns
2619 * INVALID_ARGUMENT.
2620 */
2621TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002622 if (SecLevel() == SecurityLevel::STRONGBOX) {
2623 GTEST_SKIP() << "Test not applicable to StrongBox device";
2624 }
Selene Huang31ab4042020-04-29 04:22:39 -07002625
David Drysdaledf09e542021-06-08 15:46:11 +01002626 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002627 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002628 .Authorization(TAG_KEY_SIZE, 224)
2629 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002630 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002631 .Digest(Digest::NONE)
2632 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002633 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002634}
2635
2636/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002637 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002638 *
2639 * Verifies that keymint does not support any curve designated as unsupported.
2640 */
2641TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2642 Digest digest;
2643 if (SecLevel() == SecurityLevel::STRONGBOX) {
2644 digest = Digest::SHA_2_256;
2645 } else {
2646 digest = Digest::SHA_2_512;
2647 }
2648 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002649 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Janis Danisevskis164bb872021-02-09 11:30:25 -08002650 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2651 .EcdsaSigningKey(curve)
2652 .Digest(digest)
2653 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002654 << "Failed to generate key on curve: " << curve;
2655 CheckedDeleteKey();
2656 }
2657}
2658
2659/*
2660 * NewKeyGenerationTest.Hmac
2661 *
2662 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2663 * characteristics.
2664 */
2665TEST_P(NewKeyGenerationTest, Hmac) {
2666 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002667 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07002668 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002669 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002670 constexpr size_t key_size = 128;
2671 ASSERT_EQ(ErrorCode::OK,
2672 GenerateKey(
2673 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2674 TAG_MIN_MAC_LENGTH, 128),
2675 &key_blob, &key_characteristics));
2676
2677 ASSERT_GT(key_blob.size(), 0U);
2678 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002679 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002680
Shawn Willden7f424372021-01-10 18:06:50 -07002681 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2682 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2683 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2684 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002685
2686 CheckedDeleteKey(&key_blob);
2687 }
2688}
2689
2690/*
Selene Huang4f64c222021-04-13 19:54:36 -07002691 * NewKeyGenerationTest.HmacNoAttestation
2692 *
2693 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2694 * and app id are provided.
2695 */
2696TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2697 auto challenge = "hello";
2698 auto app_id = "foo";
2699
2700 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002701 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang4f64c222021-04-13 19:54:36 -07002702 vector<uint8_t> key_blob;
2703 vector<KeyCharacteristics> key_characteristics;
2704 constexpr size_t key_size = 128;
2705 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2706 .HmacKey(key_size)
2707 .Digest(digest)
2708 .AttestationChallenge(challenge)
2709 .AttestationApplicationId(app_id)
2710 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2711 &key_blob, &key_characteristics));
2712
2713 ASSERT_GT(key_blob.size(), 0U);
2714 ASSERT_EQ(cert_chain_.size(), 0);
2715 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002716 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002717
2718 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2719 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2720 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2721 << "Key size " << key_size << "missing";
2722
2723 CheckedDeleteKey(&key_blob);
2724 }
2725}
2726
2727/*
Qi Wud22ec842020-11-26 13:27:53 +08002728 * NewKeyGenerationTest.LimitedUsageHmac
2729 *
2730 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2731 * resulting keys have correct characteristics.
2732 */
2733TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2734 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002735 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Qi Wud22ec842020-11-26 13:27:53 +08002736 vector<uint8_t> key_blob;
2737 vector<KeyCharacteristics> key_characteristics;
2738 constexpr size_t key_size = 128;
2739 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2740 .HmacKey(key_size)
2741 .Digest(digest)
2742 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2743 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2744 &key_blob, &key_characteristics));
2745
2746 ASSERT_GT(key_blob.size(), 0U);
2747 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002748 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002749
2750 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2751 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2752 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2753 << "Key size " << key_size << "missing";
2754
2755 // Check the usage count limit tag appears in the authorizations.
2756 AuthorizationSet auths;
2757 for (auto& entry : key_characteristics) {
2758 auths.push_back(AuthorizationSet(entry.authorizations));
2759 }
2760 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2761 << "key usage count limit " << 1U << " missing";
2762
2763 CheckedDeleteKey(&key_blob);
2764 }
2765}
2766
2767/*
Selene Huang31ab4042020-04-29 04:22:39 -07002768 * NewKeyGenerationTest.HmacCheckKeySizes
2769 *
2770 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2771 */
2772TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2773 for (size_t key_size = 0; key_size <= 512; ++key_size) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002774 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002775 if (key_size < 64 || key_size % 8 != 0) {
2776 // To keep this test from being very slow, we only test a random fraction of
2777 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2778 // them, we expect to run ~40 of them in each run.
2779 if (key_size % 8 == 0 || random() % 10 == 0) {
2780 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2781 GenerateKey(AuthorizationSetBuilder()
2782 .HmacKey(key_size)
2783 .Digest(Digest::SHA_2_256)
2784 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2785 << "HMAC key size " << key_size << " invalid";
2786 }
2787 } else {
2788 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2789 .HmacKey(key_size)
2790 .Digest(Digest::SHA_2_256)
2791 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2792 << "Failed to generate HMAC key of size " << key_size;
2793 CheckedDeleteKey();
2794 }
2795 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002796 if (SecLevel() == SecurityLevel::STRONGBOX) {
2797 // STRONGBOX devices must not support keys larger than 512 bits.
2798 size_t key_size = 520;
2799 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2800 GenerateKey(AuthorizationSetBuilder()
2801 .HmacKey(key_size)
2802 .Digest(Digest::SHA_2_256)
2803 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2804 << "HMAC key size " << key_size << " unexpectedly valid";
2805 }
Selene Huang31ab4042020-04-29 04:22:39 -07002806}
2807
2808/*
2809 * NewKeyGenerationTest.HmacCheckMinMacLengths
2810 *
2811 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2812 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2813 * specific MAC length that failed, so reproducing a failed run will be easy.
2814 */
2815TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2816 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002817 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
Selene Huang31ab4042020-04-29 04:22:39 -07002818 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2819 // To keep this test from being very long, we only test a random fraction of
2820 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2821 // we expect to run ~17 of them in each run.
2822 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2823 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2824 GenerateKey(AuthorizationSetBuilder()
2825 .HmacKey(128)
2826 .Digest(Digest::SHA_2_256)
2827 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2828 << "HMAC min mac length " << min_mac_length << " invalid.";
2829 }
2830 } else {
2831 EXPECT_EQ(ErrorCode::OK,
2832 GenerateKey(AuthorizationSetBuilder()
2833 .HmacKey(128)
2834 .Digest(Digest::SHA_2_256)
2835 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2836 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2837 CheckedDeleteKey();
2838 }
2839 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002840
2841 // Minimum MAC length must be no more than 512 bits.
2842 size_t min_mac_length = 520;
2843 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2844 GenerateKey(AuthorizationSetBuilder()
2845 .HmacKey(128)
2846 .Digest(Digest::SHA_2_256)
2847 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2848 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002849}
2850
2851/*
2852 * NewKeyGenerationTest.HmacMultipleDigests
2853 *
2854 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2855 */
2856TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002857 if (SecLevel() == SecurityLevel::STRONGBOX) {
2858 GTEST_SKIP() << "Test not applicable to StrongBox device";
2859 }
Selene Huang31ab4042020-04-29 04:22:39 -07002860
2861 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2862 GenerateKey(AuthorizationSetBuilder()
2863 .HmacKey(128)
2864 .Digest(Digest::SHA1)
2865 .Digest(Digest::SHA_2_256)
2866 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2867}
2868
2869/*
2870 * NewKeyGenerationTest.HmacDigestNone
2871 *
2872 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2873 */
2874TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2875 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2876 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2877 128)));
2878
2879 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2880 GenerateKey(AuthorizationSetBuilder()
2881 .HmacKey(128)
2882 .Digest(Digest::NONE)
2883 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2884}
2885
Selene Huang4f64c222021-04-13 19:54:36 -07002886/*
2887 * NewKeyGenerationTest.AesNoAttestation
2888 *
2889 * Verifies that attestation parameters to AES keys are ignored and generateKey
2890 * will succeed.
2891 */
2892TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2893 auto challenge = "hello";
2894 auto app_id = "foo";
2895
2896 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2897 .Authorization(TAG_NO_AUTH_REQUIRED)
2898 .AesEncryptionKey(128)
2899 .EcbMode()
2900 .Padding(PaddingMode::PKCS7)
2901 .AttestationChallenge(challenge)
2902 .AttestationApplicationId(app_id)));
2903
2904 ASSERT_EQ(cert_chain_.size(), 0);
2905}
2906
2907/*
2908 * NewKeyGenerationTest.TripleDesNoAttestation
2909 *
2910 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2911 * will be successful. No attestation should be generated.
2912 */
2913TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2914 auto challenge = "hello";
2915 auto app_id = "foo";
2916
2917 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2918 .TripleDesEncryptionKey(168)
2919 .BlockMode(BlockMode::ECB)
2920 .Authorization(TAG_NO_AUTH_REQUIRED)
2921 .Padding(PaddingMode::NONE)
2922 .AttestationChallenge(challenge)
2923 .AttestationApplicationId(app_id)));
2924 ASSERT_EQ(cert_chain_.size(), 0);
2925}
2926
Selene Huang31ab4042020-04-29 04:22:39 -07002927INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2928
2929typedef KeyMintAidlTestBase SigningOperationsTest;
2930
2931/*
2932 * SigningOperationsTest.RsaSuccess
2933 *
2934 * Verifies that raw RSA signature operations succeed.
2935 */
2936TEST_P(SigningOperationsTest, RsaSuccess) {
2937 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2938 .RsaSigningKey(2048, 65537)
2939 .Digest(Digest::NONE)
2940 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002941 .Authorization(TAG_NO_AUTH_REQUIRED)
2942 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002943 string message = "12345678901234567890123456789012";
2944 string signature = SignMessage(
2945 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002946 LocalVerifyMessage(message, signature,
2947 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2948}
2949
2950/*
2951 * SigningOperationsTest.RsaAllPaddingsAndDigests
2952 *
2953 * Verifies RSA signature/verification for all padding modes and digests.
2954 */
2955TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2956 auto authorizations = AuthorizationSetBuilder()
2957 .Authorization(TAG_NO_AUTH_REQUIRED)
2958 .RsaSigningKey(2048, 65537)
2959 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2960 .Padding(PaddingMode::NONE)
2961 .Padding(PaddingMode::RSA_PSS)
2962 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2963 .SetDefaultValidity();
2964
2965 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2966
2967 string message(128, 'a');
2968 string corrupt_message(message);
2969 ++corrupt_message[corrupt_message.size() / 2];
2970
2971 for (auto padding :
2972 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2973 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002974 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002975 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2976 // Digesting only makes sense with padding.
2977 continue;
2978 }
2979
2980 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2981 // PSS requires digesting.
2982 continue;
2983 }
2984
2985 string signature =
2986 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2987 LocalVerifyMessage(message, signature,
2988 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2989 }
2990 }
Selene Huang31ab4042020-04-29 04:22:39 -07002991}
2992
2993/*
2994 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2995 *
Shawn Willden7f424372021-01-10 18:06:50 -07002996 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002997 */
2998TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2999 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3000 .Authorization(TAG_NO_AUTH_REQUIRED)
3001 .RsaSigningKey(2048, 65537)
3002 .Digest(Digest::NONE)
3003 .Padding(PaddingMode::NONE)
3004 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003005 .Authorization(TAG_APPLICATION_DATA, "appdata")
3006 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003007
3008 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3009
Selene Huang31ab4042020-04-29 04:22:39 -07003010 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3011 Begin(KeyPurpose::SIGN,
3012 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3013 AbortIfNeeded();
3014 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3015 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3016 .Digest(Digest::NONE)
3017 .Padding(PaddingMode::NONE)
3018 .Authorization(TAG_APPLICATION_ID, "clientid")));
3019 AbortIfNeeded();
3020 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3021 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3022 .Digest(Digest::NONE)
3023 .Padding(PaddingMode::NONE)
3024 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3025 AbortIfNeeded();
3026 EXPECT_EQ(ErrorCode::OK,
3027 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3028 .Digest(Digest::NONE)
3029 .Padding(PaddingMode::NONE)
3030 .Authorization(TAG_APPLICATION_DATA, "appdata")
3031 .Authorization(TAG_APPLICATION_ID, "clientid")));
3032 AbortIfNeeded();
3033}
3034
3035/*
3036 * SigningOperationsTest.RsaPssSha256Success
3037 *
3038 * Verifies that RSA-PSS signature operations succeed.
3039 */
3040TEST_P(SigningOperationsTest, RsaPssSha256Success) {
3041 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3042 .RsaSigningKey(2048, 65537)
3043 .Digest(Digest::SHA_2_256)
3044 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003045 .Authorization(TAG_NO_AUTH_REQUIRED)
3046 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003047 // Use large message, which won't work without digesting.
3048 string message(1024, 'a');
3049 string signature = SignMessage(
3050 message,
3051 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
3052}
3053
3054/*
3055 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
3056 *
3057 * Verifies that keymint rejects signature operations that specify a padding mode when the key
3058 * supports only unpadded operations.
3059 */
3060TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
3061 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3062 .RsaSigningKey(2048, 65537)
3063 .Digest(Digest::NONE)
3064 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003065 .Padding(PaddingMode::NONE)
3066 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003067 string message = "12345678901234567890123456789012";
3068 string signature;
3069
3070 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3071 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3072 .Digest(Digest::NONE)
3073 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3074}
3075
3076/*
3077 * SigningOperationsTest.NoUserConfirmation
3078 *
3079 * Verifies that keymint rejects signing operations for keys with
3080 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
3081 * presented.
3082 */
3083TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01003084 if (SecLevel() == SecurityLevel::STRONGBOX) {
3085 GTEST_SKIP() << "Test not applicable to StrongBox device";
3086 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08003087 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3088 .RsaSigningKey(1024, 65537)
3089 .Digest(Digest::NONE)
3090 .Padding(PaddingMode::NONE)
3091 .Authorization(TAG_NO_AUTH_REQUIRED)
3092 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
3093 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003094
3095 const string message = "12345678901234567890123456789012";
3096 EXPECT_EQ(ErrorCode::OK,
3097 Begin(KeyPurpose::SIGN,
3098 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3099 string signature;
3100 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
3101}
3102
3103/*
3104 * SigningOperationsTest.RsaPkcs1Sha256Success
3105 *
3106 * Verifies that digested RSA-PKCS1 signature operations succeed.
3107 */
3108TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
3109 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3110 .RsaSigningKey(2048, 65537)
3111 .Digest(Digest::SHA_2_256)
3112 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003113 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3114 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003115 string message(1024, 'a');
3116 string signature = SignMessage(message, AuthorizationSetBuilder()
3117 .Digest(Digest::SHA_2_256)
3118 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3119}
3120
3121/*
3122 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3123 *
3124 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3125 */
3126TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3127 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3128 .RsaSigningKey(2048, 65537)
3129 .Digest(Digest::NONE)
3130 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003131 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3132 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003133 string message(53, 'a');
3134 string signature = SignMessage(message, AuthorizationSetBuilder()
3135 .Digest(Digest::NONE)
3136 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3137}
3138
3139/*
3140 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3141 *
3142 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3143 * given a too-long message.
3144 */
3145TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3146 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3147 .RsaSigningKey(2048, 65537)
3148 .Digest(Digest::NONE)
3149 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003150 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3151 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003152 string message(257, 'a');
3153
3154 EXPECT_EQ(ErrorCode::OK,
3155 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3156 .Digest(Digest::NONE)
3157 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3158 string signature;
3159 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3160}
3161
3162/*
3163 * SigningOperationsTest.RsaPssSha512TooSmallKey
3164 *
3165 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3166 * used with a key that is too small for the message.
3167 *
3168 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3169 * keymint specification requires that salt_size == digest_size, so the message will be
3170 * digest_size * 2 +
3171 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3172 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3173 * for a 1024-bit key.
3174 */
3175TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003176 if (SecLevel() == SecurityLevel::STRONGBOX) {
3177 GTEST_SKIP() << "Test not applicable to StrongBox device";
3178 }
Selene Huang31ab4042020-04-29 04:22:39 -07003179 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3180 .RsaSigningKey(1024, 65537)
3181 .Digest(Digest::SHA_2_512)
3182 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003183 .Padding(PaddingMode::RSA_PSS)
3184 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003185 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3186 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3187 .Digest(Digest::SHA_2_512)
3188 .Padding(PaddingMode::RSA_PSS)));
3189}
3190
3191/*
3192 * SigningOperationsTest.RsaNoPaddingTooLong
3193 *
3194 * Verifies that raw RSA signature operations fail with the correct error code when
3195 * given a too-long message.
3196 */
3197TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3198 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3199 .RsaSigningKey(2048, 65537)
3200 .Digest(Digest::NONE)
3201 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003202 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3203 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003204 // One byte too long
3205 string message(2048 / 8 + 1, 'a');
3206 ASSERT_EQ(ErrorCode::OK,
3207 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3208 .Digest(Digest::NONE)
3209 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3210 string result;
3211 ErrorCode finish_error_code = Finish(message, &result);
3212 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3213 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3214
3215 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3216 message = string(128 * 1024, 'a');
3217 ASSERT_EQ(ErrorCode::OK,
3218 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3219 .Digest(Digest::NONE)
3220 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3221 finish_error_code = Finish(message, &result);
3222 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3223 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3224}
3225
3226/*
3227 * SigningOperationsTest.RsaAbort
3228 *
3229 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3230 * test, but the behavior should be algorithm and purpose-independent.
3231 */
3232TEST_P(SigningOperationsTest, RsaAbort) {
3233 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3234 .RsaSigningKey(2048, 65537)
3235 .Digest(Digest::NONE)
3236 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003237 .Padding(PaddingMode::NONE)
3238 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003239
3240 ASSERT_EQ(ErrorCode::OK,
3241 Begin(KeyPurpose::SIGN,
3242 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3243 EXPECT_EQ(ErrorCode::OK, Abort());
3244
3245 // Another abort should fail
3246 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3247
3248 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003249 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003250}
3251
3252/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003253 * SigningOperationsTest.RsaNonUniqueParams
3254 *
3255 * Verifies that an operation with multiple padding modes is rejected.
3256 */
3257TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3258 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3259 .RsaSigningKey(2048, 65537)
3260 .Digest(Digest::NONE)
3261 .Digest(Digest::SHA1)
3262 .Authorization(TAG_NO_AUTH_REQUIRED)
3263 .Padding(PaddingMode::NONE)
3264 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3265 .SetDefaultValidity()));
3266
3267 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3268 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3269 .Digest(Digest::NONE)
3270 .Padding(PaddingMode::NONE)
3271 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3272
Tommy Chiuc93c4392021-05-11 18:36:50 +08003273 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3274 .Digest(Digest::NONE)
3275 .Digest(Digest::SHA1)
3276 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3277 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003278
3279 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3280 Begin(KeyPurpose::SIGN,
3281 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3282}
3283
3284/*
Selene Huang31ab4042020-04-29 04:22:39 -07003285 * SigningOperationsTest.RsaUnsupportedPadding
3286 *
3287 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3288 * with a padding mode inappropriate for RSA.
3289 */
3290TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3291 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3292 .RsaSigningKey(2048, 65537)
3293 .Authorization(TAG_NO_AUTH_REQUIRED)
3294 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003295 .Padding(PaddingMode::PKCS7)
3296 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003297 ASSERT_EQ(
3298 ErrorCode::UNSUPPORTED_PADDING_MODE,
3299 Begin(KeyPurpose::SIGN,
3300 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003301 CheckedDeleteKey();
3302
3303 ASSERT_EQ(ErrorCode::OK,
3304 GenerateKey(
3305 AuthorizationSetBuilder()
3306 .RsaSigningKey(2048, 65537)
3307 .Authorization(TAG_NO_AUTH_REQUIRED)
3308 .Digest(Digest::SHA_2_256 /* supported digest */)
3309 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3310 .SetDefaultValidity()));
3311 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3312 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3313 .Digest(Digest::SHA_2_256)
3314 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003315}
3316
3317/*
3318 * SigningOperationsTest.RsaPssNoDigest
3319 *
3320 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3321 */
3322TEST_P(SigningOperationsTest, RsaNoDigest) {
3323 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3324 .RsaSigningKey(2048, 65537)
3325 .Authorization(TAG_NO_AUTH_REQUIRED)
3326 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003327 .Padding(PaddingMode::RSA_PSS)
3328 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003329 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3330 Begin(KeyPurpose::SIGN,
3331 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3332
3333 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3334 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3335}
3336
3337/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003338 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003339 *
3340 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3341 * supported in some cases (as validated in other tests), but a mode must be specified.
3342 */
3343TEST_P(SigningOperationsTest, RsaNoPadding) {
3344 // Padding must be specified
3345 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3346 .RsaKey(2048, 65537)
3347 .Authorization(TAG_NO_AUTH_REQUIRED)
3348 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003349 .Digest(Digest::NONE)
3350 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003351 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3352 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3353}
3354
3355/*
3356 * SigningOperationsTest.RsaShortMessage
3357 *
3358 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3359 */
3360TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3361 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3362 .Authorization(TAG_NO_AUTH_REQUIRED)
3363 .RsaSigningKey(2048, 65537)
3364 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003365 .Padding(PaddingMode::NONE)
3366 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003367
3368 // Barely shorter
3369 string message(2048 / 8 - 1, 'a');
3370 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3371
3372 // Much shorter
3373 message = "a";
3374 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3375}
3376
3377/*
3378 * SigningOperationsTest.RsaSignWithEncryptionKey
3379 *
3380 * Verifies that RSA encryption keys cannot be used to sign.
3381 */
3382TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3383 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3384 .Authorization(TAG_NO_AUTH_REQUIRED)
3385 .RsaEncryptionKey(2048, 65537)
3386 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003387 .Padding(PaddingMode::NONE)
3388 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003389 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3390 Begin(KeyPurpose::SIGN,
3391 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3392}
3393
3394/*
3395 * SigningOperationsTest.RsaSignTooLargeMessage
3396 *
3397 * Verifies that attempting a raw signature of a message which is the same length as the key,
3398 * but numerically larger than the public modulus, fails with the correct error.
3399 */
3400TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3401 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3402 .Authorization(TAG_NO_AUTH_REQUIRED)
3403 .RsaSigningKey(2048, 65537)
3404 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003405 .Padding(PaddingMode::NONE)
3406 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003407
3408 // Largest possible message will always be larger than the public modulus.
3409 string message(2048 / 8, static_cast<char>(0xff));
3410 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3411 .Authorization(TAG_NO_AUTH_REQUIRED)
3412 .Digest(Digest::NONE)
3413 .Padding(PaddingMode::NONE)));
3414 string signature;
3415 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3416}
3417
3418/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003419 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3420 *
David Drysdale42fe1892021-10-14 14:43:46 +01003421 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003422 */
3423TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003424
3425 string message = "1234567890";
3426 string corrupt_message = "2234567890";
3427 for (auto curve : ValidCurves()) {
3428 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003429 // Ed25519 only allows Digest::NONE.
3430 auto digests = (curve == EcCurve::CURVE_25519)
3431 ? std::vector<Digest>(1, Digest::NONE)
3432 : ValidDigests(true /* withNone */, false /* withMD5 */);
3433
David Drysdaledf8f52e2021-05-06 08:10:58 +01003434 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3435 .Authorization(TAG_NO_AUTH_REQUIRED)
3436 .EcdsaSigningKey(curve)
3437 .Digest(digests)
3438 .SetDefaultValidity());
3439 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3440 if (error != ErrorCode::OK) {
3441 continue;
3442 }
3443
3444 for (auto digest : digests) {
3445 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3446 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3447 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3448 }
3449
3450 auto rc = DeleteKey();
3451 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3452 }
3453}
3454
3455/*
Selene Huang31ab4042020-04-29 04:22:39 -07003456 * SigningOperationsTest.EcdsaAllCurves
3457 *
David Drysdale42fe1892021-10-14 14:43:46 +01003458 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003459 */
3460TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3461 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003462 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3463 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003464 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3465 .Authorization(TAG_NO_AUTH_REQUIRED)
3466 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003467 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003468 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003469 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3470 if (error != ErrorCode::OK) continue;
3471
3472 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003473 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003474 CheckedDeleteKey();
3475 }
3476}
3477
3478/*
David Drysdale42fe1892021-10-14 14:43:46 +01003479 * SigningOperationsTest.EcdsaCurve25519
3480 *
3481 * Verifies that ECDSA operations succeed with curve25519.
3482 */
3483TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3484 if (!Curve25519Supported()) {
3485 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3486 }
3487
3488 EcCurve curve = EcCurve::CURVE_25519;
3489 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3490 .Authorization(TAG_NO_AUTH_REQUIRED)
3491 .EcdsaSigningKey(curve)
3492 .Digest(Digest::NONE)
3493 .SetDefaultValidity());
3494 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3495
3496 string message(1024, 'a');
3497 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3498 CheckedDeleteKey();
3499}
3500
3501/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003502 * SigningOperationsTest.EcdsaCurve25519MaxSize
3503 *
3504 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3505 */
3506TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3507 if (!Curve25519Supported()) {
3508 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3509 }
3510
3511 EcCurve curve = EcCurve::CURVE_25519;
3512 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3513 .Authorization(TAG_NO_AUTH_REQUIRED)
3514 .EcdsaSigningKey(curve)
3515 .Digest(Digest::NONE)
3516 .SetDefaultValidity());
3517 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3518
3519 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3520
3521 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3522 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3523 string message(msg_size, 'a');
3524
3525 // Attempt to sign via Begin+Finish.
3526 AuthorizationSet out_params;
3527 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3528 EXPECT_TRUE(out_params.empty());
3529 string signature;
3530 auto result = Finish(message, &signature);
3531 EXPECT_EQ(result, ErrorCode::OK);
3532 LocalVerifyMessage(message, signature, params);
3533
3534 // Attempt to sign via Begin+Update+Finish
3535 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3536 EXPECT_TRUE(out_params.empty());
3537 string output;
3538 result = Update(message, &output);
3539 EXPECT_EQ(result, ErrorCode::OK);
3540 EXPECT_EQ(output.size(), 0);
3541 string signature2;
3542 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3543 LocalVerifyMessage(message, signature2, params);
3544 }
3545
3546 CheckedDeleteKey();
3547}
3548
3549/*
3550 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3551 *
3552 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3553 */
3554TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3555 if (!Curve25519Supported()) {
3556 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3557 }
3558
3559 EcCurve curve = EcCurve::CURVE_25519;
3560 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3561 .Authorization(TAG_NO_AUTH_REQUIRED)
3562 .EcdsaSigningKey(curve)
3563 .Digest(Digest::NONE)
3564 .SetDefaultValidity());
3565 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3566
3567 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3568
3569 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3570 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3571 string message(msg_size, 'a');
3572
3573 // Attempt to sign via Begin+Finish.
3574 AuthorizationSet out_params;
3575 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3576 EXPECT_TRUE(out_params.empty());
3577 string signature;
3578 auto result = Finish(message, &signature);
3579 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3580
3581 // Attempt to sign via Begin+Update (but never get to Finish)
3582 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3583 EXPECT_TRUE(out_params.empty());
3584 string output;
3585 result = Update(message, &output);
3586 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3587 }
3588
3589 CheckedDeleteKey();
3590}
3591
3592/*
Selene Huang31ab4042020-04-29 04:22:39 -07003593 * SigningOperationsTest.EcdsaNoDigestHugeData
3594 *
3595 * Verifies that ECDSA operations support very large messages, even without digesting. This
3596 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3597 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3598 * the framework.
3599 */
3600TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3601 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3602 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003603 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003604 .Digest(Digest::NONE)
3605 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003606 string message(1 * 1024, 'a');
3607 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3608}
3609
3610/*
3611 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3612 *
3613 * Verifies that using an EC key requires the correct app ID/data.
3614 */
3615TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3616 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3617 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003618 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003619 .Digest(Digest::NONE)
3620 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003621 .Authorization(TAG_APPLICATION_DATA, "appdata")
3622 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003623
3624 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3625
Selene Huang31ab4042020-04-29 04:22:39 -07003626 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3627 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3628 AbortIfNeeded();
3629 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3630 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3631 .Digest(Digest::NONE)
3632 .Authorization(TAG_APPLICATION_ID, "clientid")));
3633 AbortIfNeeded();
3634 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3635 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3636 .Digest(Digest::NONE)
3637 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3638 AbortIfNeeded();
3639 EXPECT_EQ(ErrorCode::OK,
3640 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3641 .Digest(Digest::NONE)
3642 .Authorization(TAG_APPLICATION_DATA, "appdata")
3643 .Authorization(TAG_APPLICATION_ID, "clientid")));
3644 AbortIfNeeded();
3645}
3646
3647/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003648 * SigningOperationsTest.EcdsaIncompatibleDigest
3649 *
3650 * Verifies that using an EC key requires compatible digest.
3651 */
3652TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3653 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3654 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003655 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003656 .Digest(Digest::NONE)
3657 .Digest(Digest::SHA1)
3658 .SetDefaultValidity()));
3659 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3660 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3661 AbortIfNeeded();
3662}
3663
3664/*
Selene Huang31ab4042020-04-29 04:22:39 -07003665 * SigningOperationsTest.AesEcbSign
3666 *
3667 * Verifies that attempts to use AES keys to sign fail in the correct way.
3668 */
3669TEST_P(SigningOperationsTest, AesEcbSign) {
3670 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3671 .Authorization(TAG_NO_AUTH_REQUIRED)
3672 .SigningKey()
3673 .AesEncryptionKey(128)
3674 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3675
3676 AuthorizationSet out_params;
3677 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3678 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3679 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3680 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3681}
3682
3683/*
3684 * SigningOperationsTest.HmacAllDigests
3685 *
3686 * Verifies that HMAC works with all digests.
3687 */
3688TEST_P(SigningOperationsTest, HmacAllDigests) {
3689 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003690 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003691 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3692 .Authorization(TAG_NO_AUTH_REQUIRED)
3693 .HmacKey(128)
3694 .Digest(digest)
3695 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3696 << "Failed to create HMAC key with digest " << digest;
3697 string message = "12345678901234567890123456789012";
3698 string signature = MacMessage(message, digest, 160);
3699 EXPECT_EQ(160U / 8U, signature.size())
3700 << "Failed to sign with HMAC key with digest " << digest;
3701 CheckedDeleteKey();
3702 }
3703}
3704
3705/*
3706 * SigningOperationsTest.HmacSha256TooLargeMacLength
3707 *
3708 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3709 * digest size.
3710 */
3711TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3712 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3713 .Authorization(TAG_NO_AUTH_REQUIRED)
3714 .HmacKey(128)
3715 .Digest(Digest::SHA_2_256)
3716 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3717 AuthorizationSet output_params;
3718 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3719 AuthorizationSetBuilder()
3720 .Digest(Digest::SHA_2_256)
3721 .Authorization(TAG_MAC_LENGTH, 264),
3722 &output_params));
3723}
3724
3725/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003726 * SigningOperationsTest.HmacSha256InvalidMacLength
3727 *
3728 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3729 * not a multiple of 8.
3730 */
3731TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3732 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3733 .Authorization(TAG_NO_AUTH_REQUIRED)
3734 .HmacKey(128)
3735 .Digest(Digest::SHA_2_256)
3736 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3737 AuthorizationSet output_params;
3738 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3739 AuthorizationSetBuilder()
3740 .Digest(Digest::SHA_2_256)
3741 .Authorization(TAG_MAC_LENGTH, 161),
3742 &output_params));
3743}
3744
3745/*
Selene Huang31ab4042020-04-29 04:22:39 -07003746 * SigningOperationsTest.HmacSha256TooSmallMacLength
3747 *
3748 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3749 * specified minimum MAC length.
3750 */
3751TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3752 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3753 .Authorization(TAG_NO_AUTH_REQUIRED)
3754 .HmacKey(128)
3755 .Digest(Digest::SHA_2_256)
3756 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3757 AuthorizationSet output_params;
3758 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3759 AuthorizationSetBuilder()
3760 .Digest(Digest::SHA_2_256)
3761 .Authorization(TAG_MAC_LENGTH, 120),
3762 &output_params));
3763}
3764
3765/*
3766 * SigningOperationsTest.HmacRfc4231TestCase3
3767 *
3768 * Validates against the test vectors from RFC 4231 test case 3.
3769 */
3770TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3771 string key(20, 0xaa);
3772 string message(50, 0xdd);
3773 uint8_t sha_224_expected[] = {
3774 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3775 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3776 };
3777 uint8_t sha_256_expected[] = {
3778 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3779 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3780 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3781 };
3782 uint8_t sha_384_expected[] = {
3783 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3784 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3785 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3786 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3787 };
3788 uint8_t sha_512_expected[] = {
3789 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3790 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3791 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3792 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3793 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3794 };
3795
3796 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3797 if (SecLevel() != SecurityLevel::STRONGBOX) {
3798 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3799 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3800 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3801 }
3802}
3803
3804/*
3805 * SigningOperationsTest.HmacRfc4231TestCase5
3806 *
3807 * Validates against the test vectors from RFC 4231 test case 5.
3808 */
3809TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3810 string key(20, 0x0c);
3811 string message = "Test With Truncation";
3812
3813 uint8_t sha_224_expected[] = {
3814 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3815 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3816 };
3817 uint8_t sha_256_expected[] = {
3818 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3819 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3820 };
3821 uint8_t sha_384_expected[] = {
3822 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3823 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3824 };
3825 uint8_t sha_512_expected[] = {
3826 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3827 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3828 };
3829
3830 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3831 if (SecLevel() != SecurityLevel::STRONGBOX) {
3832 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3833 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3834 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3835 }
3836}
3837
3838INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3839
3840typedef KeyMintAidlTestBase VerificationOperationsTest;
3841
3842/*
Selene Huang31ab4042020-04-29 04:22:39 -07003843 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3844 *
3845 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3846 */
3847TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3848 string key_material = "HelloThisIsAKey";
3849
3850 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003851 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003852 EXPECT_EQ(ErrorCode::OK,
3853 ImportKey(AuthorizationSetBuilder()
3854 .Authorization(TAG_NO_AUTH_REQUIRED)
3855 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3856 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3857 .Digest(Digest::SHA_2_256)
3858 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3859 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3860 EXPECT_EQ(ErrorCode::OK,
3861 ImportKey(AuthorizationSetBuilder()
3862 .Authorization(TAG_NO_AUTH_REQUIRED)
3863 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3864 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3865 .Digest(Digest::SHA_2_256)
3866 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3867 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3868
3869 string message = "This is a message.";
3870 string signature = SignMessage(
3871 signing_key, message,
3872 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3873
3874 // Signing key should not work.
3875 AuthorizationSet out_params;
3876 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3877 Begin(KeyPurpose::VERIFY, signing_key,
3878 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3879
3880 // Verification key should work.
3881 VerifyMessage(verification_key, message, signature,
3882 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3883
3884 CheckedDeleteKey(&signing_key);
3885 CheckedDeleteKey(&verification_key);
3886}
3887
Prashant Patildec9fdc2021-12-08 15:25:47 +00003888/*
3889 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3890 *
3891 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3892 */
3893TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3894 string key_material = "HelloThisIsAKey";
3895
3896 vector<uint8_t> signing_key, verification_key;
3897 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3898 EXPECT_EQ(ErrorCode::OK,
3899 ImportKey(AuthorizationSetBuilder()
3900 .Authorization(TAG_NO_AUTH_REQUIRED)
3901 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3902 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3903 .Digest(Digest::SHA_2_256)
3904 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3905 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3906 EXPECT_EQ(ErrorCode::OK,
3907 ImportKey(AuthorizationSetBuilder()
3908 .Authorization(TAG_NO_AUTH_REQUIRED)
3909 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3910 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3911 .Digest(Digest::SHA_2_256)
3912 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3913 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3914
3915 string message = "This is a message.";
3916 string signature = SignMessage(
3917 signing_key, message,
3918 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3919
3920 AuthorizationSet begin_out_params;
3921 ASSERT_EQ(ErrorCode::OK,
3922 Begin(KeyPurpose::VERIFY, verification_key,
3923 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3924
3925 string corruptMessage = "This is b message."; // Corrupted message
3926 string output;
3927 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3928
3929 ASSERT_EQ(ErrorCode::OK,
3930 Begin(KeyPurpose::VERIFY, verification_key,
3931 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3932
3933 signature[0] += 1; // Corrupt a signature
3934 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3935
3936 CheckedDeleteKey(&signing_key);
3937 CheckedDeleteKey(&verification_key);
3938}
3939
Selene Huang31ab4042020-04-29 04:22:39 -07003940INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3941
3942typedef KeyMintAidlTestBase ExportKeyTest;
3943
3944/*
3945 * ExportKeyTest.RsaUnsupportedKeyFormat
3946 *
3947 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3948 */
3949// TODO(seleneh) add ExportKey to GenerateKey
3950// check result
3951
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003952class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003953 public:
3954 template <TagType tag_type, Tag tag, typename ValueT>
3955 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3956 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003957 for (auto& entry : key_characteristics_) {
3958 if (entry.securityLevel == SecLevel()) {
3959 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3960 << "Tag " << tag << " with value " << expected
3961 << " not found at security level" << entry.securityLevel;
3962 } else {
3963 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3964 << "Tag " << tag << " found at security level " << entry.securityLevel;
3965 }
Selene Huang31ab4042020-04-29 04:22:39 -07003966 }
3967 }
3968
3969 void CheckOrigin() {
3970 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003971 // Origin isn't a crypto param, but it always lives with them.
3972 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003973 }
3974};
3975
3976/*
3977 * ImportKeyTest.RsaSuccess
3978 *
3979 * Verifies that importing and using an RSA key pair works correctly.
3980 */
3981TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003982 uint32_t key_size;
3983 string key;
3984
3985 if (SecLevel() == SecurityLevel::STRONGBOX) {
3986 key_size = 2048;
3987 key = rsa_2048_key;
3988 } else {
3989 key_size = 1024;
3990 key = rsa_key;
3991 }
3992
Selene Huang31ab4042020-04-29 04:22:39 -07003993 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3994 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003995 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003996 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003997 .Padding(PaddingMode::RSA_PSS)
3998 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003999 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07004000
4001 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07004002 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07004003 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4004 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4005 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4006 CheckOrigin();
4007
4008 string message(1024 / 8, 'a');
4009 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4010 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004011 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004012}
4013
4014/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004015 * ImportKeyTest.RsaSuccessWithoutParams
4016 *
4017 * Verifies that importing and using an RSA key pair without specifying parameters
4018 * works correctly.
4019 */
4020TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
4021 uint32_t key_size;
4022 string key;
4023
4024 if (SecLevel() == SecurityLevel::STRONGBOX) {
4025 key_size = 2048;
4026 key = rsa_2048_key;
4027 } else {
4028 key_size = 1024;
4029 key = rsa_key;
4030 }
4031
4032 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4033 .Authorization(TAG_NO_AUTH_REQUIRED)
4034 .SigningKey()
4035 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
4036 .Digest(Digest::SHA_2_256)
4037 .Padding(PaddingMode::RSA_PSS)
4038 .SetDefaultValidity(),
4039 KeyFormat::PKCS8, key));
4040
4041 // Key size and public exponent are determined from the imported key material.
4042 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4043 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4044
4045 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4046 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4047 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4048 CheckOrigin();
4049
4050 string message(1024 / 8, 'a');
4051 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4052 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004053 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004054}
4055
4056/*
Selene Huang31ab4042020-04-29 04:22:39 -07004057 * ImportKeyTest.RsaKeySizeMismatch
4058 *
4059 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
4060 * correct way.
4061 */
4062TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
4063 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4064 ImportKey(AuthorizationSetBuilder()
4065 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
4066 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004067 .Padding(PaddingMode::NONE)
4068 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004069 KeyFormat::PKCS8, rsa_key));
4070}
4071
4072/*
4073 * ImportKeyTest.RsaPublicExponentMismatch
4074 *
4075 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
4076 * fails in the correct way.
4077 */
4078TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
4079 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4080 ImportKey(AuthorizationSetBuilder()
4081 .RsaSigningKey(1024, 3 /* Doesn't match key */)
4082 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004083 .Padding(PaddingMode::NONE)
4084 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004085 KeyFormat::PKCS8, rsa_key));
4086}
4087
4088/*
David Drysdalee60248c2021-10-04 12:54:13 +01004089 * ImportKeyTest.RsaAttestMultiPurposeFail
4090 *
4091 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
4092 */
4093TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004094 if (AidlVersion() < 2) {
4095 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4096 // with other key purposes. However, this was not checked at the time
4097 // so we can only be strict about checking this for implementations of KeyMint
4098 // version 2 and above.
4099 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4100 }
David Drysdalee60248c2021-10-04 12:54:13 +01004101 uint32_t key_size = 2048;
4102 string key = rsa_2048_key;
4103
4104 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4105 ImportKey(AuthorizationSetBuilder()
4106 .Authorization(TAG_NO_AUTH_REQUIRED)
4107 .RsaSigningKey(key_size, 65537)
4108 .AttestKey()
4109 .Digest(Digest::SHA_2_256)
4110 .Padding(PaddingMode::RSA_PSS)
4111 .SetDefaultValidity(),
4112 KeyFormat::PKCS8, key));
4113}
4114
4115/*
Selene Huang31ab4042020-04-29 04:22:39 -07004116 * ImportKeyTest.EcdsaSuccess
4117 *
4118 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4119 */
4120TEST_P(ImportKeyTest, EcdsaSuccess) {
4121 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4122 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004123 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004124 .Digest(Digest::SHA_2_256)
4125 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004126 KeyFormat::PKCS8, ec_256_key));
4127
4128 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004129 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4130 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4131
4132 CheckOrigin();
4133
4134 string message(32, 'a');
4135 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4136 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004137 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004138}
4139
4140/*
4141 * ImportKeyTest.EcdsaP256RFC5915Success
4142 *
4143 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4144 * correctly.
4145 */
4146TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4147 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4148 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004149 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004150 .Digest(Digest::SHA_2_256)
4151 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004152 KeyFormat::PKCS8, ec_256_key_rfc5915));
4153
4154 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004155 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4156 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4157
4158 CheckOrigin();
4159
4160 string message(32, 'a');
4161 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4162 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004163 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004164}
4165
4166/*
4167 * ImportKeyTest.EcdsaP256SEC1Success
4168 *
4169 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4170 */
4171TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4172 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4173 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004174 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004175 .Digest(Digest::SHA_2_256)
4176 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004177 KeyFormat::PKCS8, ec_256_key_sec1));
4178
4179 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004180 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4181 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4182
4183 CheckOrigin();
4184
4185 string message(32, 'a');
4186 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4187 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004188 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004189}
4190
4191/*
4192 * ImportKeyTest.Ecdsa521Success
4193 *
4194 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4195 */
4196TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004197 if (SecLevel() == SecurityLevel::STRONGBOX) {
4198 GTEST_SKIP() << "Test not applicable to StrongBox device";
4199 }
Selene Huang31ab4042020-04-29 04:22:39 -07004200 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4201 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004202 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004203 .Digest(Digest::SHA_2_256)
4204 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004205 KeyFormat::PKCS8, ec_521_key));
4206
4207 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004208 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4209 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4210 CheckOrigin();
4211
4212 string message(32, 'a');
4213 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4214 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004215 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004216}
4217
4218/*
Selene Huang31ab4042020-04-29 04:22:39 -07004219 * ImportKeyTest.EcdsaCurveMismatch
4220 *
4221 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4222 * the correct way.
4223 */
4224TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4225 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4226 ImportKey(AuthorizationSetBuilder()
4227 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004228 .Digest(Digest::NONE)
4229 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004230 KeyFormat::PKCS8, ec_256_key));
4231}
4232
4233/*
David Drysdalee60248c2021-10-04 12:54:13 +01004234 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4235 *
4236 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4237 */
4238TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004239 if (AidlVersion() < 2) {
4240 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4241 // with other key purposes. However, this was not checked at the time
4242 // so we can only be strict about checking this for implementations of KeyMint
4243 // version 2 and above.
4244 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4245 }
David Drysdalee60248c2021-10-04 12:54:13 +01004246 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4247 ImportKey(AuthorizationSetBuilder()
4248 .Authorization(TAG_NO_AUTH_REQUIRED)
4249 .EcdsaSigningKey(EcCurve::P_256)
4250 .AttestKey()
4251 .Digest(Digest::SHA_2_256)
4252 .SetDefaultValidity(),
4253 KeyFormat::PKCS8, ec_256_key));
4254}
4255
4256/*
David Drysdale42fe1892021-10-14 14:43:46 +01004257 * ImportKeyTest.Ed25519RawSuccess
4258 *
4259 * Verifies that importing and using a raw Ed25519 private key works correctly.
4260 */
4261TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4262 if (!Curve25519Supported()) {
4263 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4264 }
4265
4266 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4267 .Authorization(TAG_NO_AUTH_REQUIRED)
4268 .EcdsaSigningKey(EcCurve::CURVE_25519)
4269 .Digest(Digest::NONE)
4270 .SetDefaultValidity(),
4271 KeyFormat::RAW, ed25519_key));
4272 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4273 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4274 CheckOrigin();
4275
4276 // The returned cert should hold the correct public key.
4277 ASSERT_GT(cert_chain_.size(), 0);
4278 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4279 ASSERT_NE(kmKeyCert, nullptr);
4280 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4281 ASSERT_NE(kmPubKey.get(), nullptr);
4282 size_t kmPubKeySize = 32;
4283 uint8_t kmPubKeyData[32];
4284 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4285 ASSERT_EQ(kmPubKeySize, 32);
4286 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4287
4288 string message(32, 'a');
4289 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4290 string signature = SignMessage(message, params);
4291 LocalVerifyMessage(message, signature, params);
4292}
4293
4294/*
4295 * ImportKeyTest.Ed25519Pkcs8Success
4296 *
4297 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4298 */
4299TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4300 if (!Curve25519Supported()) {
4301 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4302 }
4303
4304 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4305 .Authorization(TAG_NO_AUTH_REQUIRED)
4306 .EcdsaSigningKey(EcCurve::CURVE_25519)
4307 .Digest(Digest::NONE)
4308 .SetDefaultValidity(),
4309 KeyFormat::PKCS8, ed25519_pkcs8_key));
4310 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4311 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4312 CheckOrigin();
4313
4314 // The returned cert should hold the correct public key.
4315 ASSERT_GT(cert_chain_.size(), 0);
4316 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4317 ASSERT_NE(kmKeyCert, nullptr);
4318 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4319 ASSERT_NE(kmPubKey.get(), nullptr);
4320 size_t kmPubKeySize = 32;
4321 uint8_t kmPubKeyData[32];
4322 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4323 ASSERT_EQ(kmPubKeySize, 32);
4324 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4325
4326 string message(32, 'a');
4327 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4328 string signature = SignMessage(message, params);
4329 LocalVerifyMessage(message, signature, params);
4330}
4331
4332/*
4333 * ImportKeyTest.Ed25519CurveMismatch
4334 *
4335 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4336 * the correct way.
4337 */
4338TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4339 if (!Curve25519Supported()) {
4340 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4341 }
4342
4343 ASSERT_NE(ErrorCode::OK,
4344 ImportKey(AuthorizationSetBuilder()
4345 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4346 .Digest(Digest::NONE)
4347 .SetDefaultValidity(),
4348 KeyFormat::RAW, ed25519_key));
4349}
4350
4351/*
4352 * ImportKeyTest.Ed25519FormatMismatch
4353 *
4354 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4355 */
4356TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4357 if (!Curve25519Supported()) {
4358 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4359 }
4360
4361 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4362 .EcdsaSigningKey(EcCurve::CURVE_25519)
4363 .Digest(Digest::NONE)
4364 .SetDefaultValidity(),
4365 KeyFormat::PKCS8, ed25519_key));
4366 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4367 .EcdsaSigningKey(EcCurve::CURVE_25519)
4368 .Digest(Digest::NONE)
4369 .SetDefaultValidity(),
4370 KeyFormat::RAW, ed25519_pkcs8_key));
4371}
4372
4373/*
4374 * ImportKeyTest.Ed25519PurposeMismatch
4375 *
4376 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4377 */
4378TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4379 if (!Curve25519Supported()) {
4380 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4381 }
4382
4383 // Can't have both SIGN and ATTEST_KEY
4384 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4385 .EcdsaSigningKey(EcCurve::CURVE_25519)
4386 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4387 .Digest(Digest::NONE)
4388 .SetDefaultValidity(),
4389 KeyFormat::RAW, ed25519_key));
4390 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4391 // PKCS#8 format and so includes an OID).
4392 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4393 .EcdsaKey(EcCurve::CURVE_25519)
4394 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4395 .Digest(Digest::NONE)
4396 .SetDefaultValidity(),
4397 KeyFormat::PKCS8, ed25519_pkcs8_key));
4398}
4399
4400/*
4401 * ImportKeyTest.X25519RawSuccess
4402 *
4403 * Verifies that importing and using a raw X25519 private key works correctly.
4404 */
4405TEST_P(ImportKeyTest, X25519RawSuccess) {
4406 if (!Curve25519Supported()) {
4407 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4408 }
4409
4410 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4411 .Authorization(TAG_NO_AUTH_REQUIRED)
4412 .EcdsaKey(EcCurve::CURVE_25519)
4413 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4414 .SetDefaultValidity(),
4415 KeyFormat::RAW, x25519_key));
4416
4417 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4418 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4419 CheckOrigin();
4420}
4421
4422/*
4423 * ImportKeyTest.X25519Pkcs8Success
4424 *
4425 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4426 */
4427TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4428 if (!Curve25519Supported()) {
4429 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4430 }
4431
4432 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4433 .Authorization(TAG_NO_AUTH_REQUIRED)
4434 .EcdsaKey(EcCurve::CURVE_25519)
4435 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4436 .SetDefaultValidity(),
4437 KeyFormat::PKCS8, x25519_pkcs8_key));
4438
4439 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4440 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4441 CheckOrigin();
4442}
4443
4444/*
4445 * ImportKeyTest.X25519CurveMismatch
4446 *
4447 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4448 * the correct way.
4449 */
4450TEST_P(ImportKeyTest, X25519CurveMismatch) {
4451 if (!Curve25519Supported()) {
4452 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4453 }
4454
4455 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4456 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4457 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4458 .SetDefaultValidity(),
4459 KeyFormat::RAW, x25519_key));
4460}
4461
4462/*
4463 * ImportKeyTest.X25519FormatMismatch
4464 *
4465 * Verifies that importing an X25519 key with an invalid format fails.
4466 */
4467TEST_P(ImportKeyTest, X25519FormatMismatch) {
4468 if (!Curve25519Supported()) {
4469 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4470 }
4471
4472 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4473 .EcdsaKey(EcCurve::CURVE_25519)
4474 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4475 .SetDefaultValidity(),
4476 KeyFormat::PKCS8, x25519_key));
4477 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4478 .EcdsaKey(EcCurve::CURVE_25519)
4479 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4480 .SetDefaultValidity(),
4481 KeyFormat::RAW, x25519_pkcs8_key));
4482}
4483
4484/*
4485 * ImportKeyTest.X25519PurposeMismatch
4486 *
4487 * Verifies that importing an X25519 key pair with an invalid format fails.
4488 */
4489TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4490 if (!Curve25519Supported()) {
4491 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4492 }
4493
4494 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4495 .EcdsaKey(EcCurve::CURVE_25519)
4496 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4497 .SetDefaultValidity(),
4498 KeyFormat::PKCS8, x25519_pkcs8_key));
4499 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4500 .EcdsaSigningKey(EcCurve::CURVE_25519)
4501 .SetDefaultValidity(),
4502 KeyFormat::PKCS8, x25519_pkcs8_key));
4503}
4504
4505/*
Selene Huang31ab4042020-04-29 04:22:39 -07004506 * ImportKeyTest.AesSuccess
4507 *
4508 * Verifies that importing and using an AES key works.
4509 */
4510TEST_P(ImportKeyTest, AesSuccess) {
4511 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4512 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4513 .Authorization(TAG_NO_AUTH_REQUIRED)
4514 .AesEncryptionKey(key.size() * 8)
4515 .EcbMode()
4516 .Padding(PaddingMode::PKCS7),
4517 KeyFormat::RAW, key));
4518
4519 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4520 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4521 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4522 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4523 CheckOrigin();
4524
4525 string message = "Hello World!";
4526 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4527 string ciphertext = EncryptMessage(message, params);
4528 string plaintext = DecryptMessage(ciphertext, params);
4529 EXPECT_EQ(message, plaintext);
4530}
4531
4532/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004533 * ImportKeyTest.AesFailure
4534 *
4535 * Verifies that importing an invalid AES key fails.
4536 */
4537TEST_P(ImportKeyTest, AesFailure) {
4538 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4539 uint32_t bitlen = key.size() * 8;
4540 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004541 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004542 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004543 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004544 .Authorization(TAG_NO_AUTH_REQUIRED)
4545 .AesEncryptionKey(key_size)
4546 .EcbMode()
4547 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004548 KeyFormat::RAW, key);
4549 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004550 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4551 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004552 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004553
4554 // Explicit key size matches that of the provided key, but it's not a valid size.
4555 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4556 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4557 ImportKey(AuthorizationSetBuilder()
4558 .Authorization(TAG_NO_AUTH_REQUIRED)
4559 .AesEncryptionKey(long_key.size() * 8)
4560 .EcbMode()
4561 .Padding(PaddingMode::PKCS7),
4562 KeyFormat::RAW, long_key));
4563 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4564 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4565 ImportKey(AuthorizationSetBuilder()
4566 .Authorization(TAG_NO_AUTH_REQUIRED)
4567 .AesEncryptionKey(short_key.size() * 8)
4568 .EcbMode()
4569 .Padding(PaddingMode::PKCS7),
4570 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004571}
4572
4573/*
4574 * ImportKeyTest.TripleDesSuccess
4575 *
4576 * Verifies that importing and using a 3DES key works.
4577 */
4578TEST_P(ImportKeyTest, TripleDesSuccess) {
4579 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4580 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4581 .Authorization(TAG_NO_AUTH_REQUIRED)
4582 .TripleDesEncryptionKey(168)
4583 .EcbMode()
4584 .Padding(PaddingMode::PKCS7),
4585 KeyFormat::RAW, key));
4586
4587 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4588 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4589 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4590 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4591 CheckOrigin();
4592
4593 string message = "Hello World!";
4594 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4595 string ciphertext = EncryptMessage(message, params);
4596 string plaintext = DecryptMessage(ciphertext, params);
4597 EXPECT_EQ(message, plaintext);
4598}
4599
4600/*
4601 * ImportKeyTest.TripleDesFailure
4602 *
4603 * Verifies that importing an invalid 3DES key fails.
4604 */
4605TEST_P(ImportKeyTest, TripleDesFailure) {
4606 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004607 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004608 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004609 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004610 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004611 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004612 .Authorization(TAG_NO_AUTH_REQUIRED)
4613 .TripleDesEncryptionKey(key_size)
4614 .EcbMode()
4615 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004616 KeyFormat::RAW, key);
4617 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004618 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4619 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004620 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004621 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004622 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004623 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4624 ImportKey(AuthorizationSetBuilder()
4625 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004626 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004627 .EcbMode()
4628 .Padding(PaddingMode::PKCS7),
4629 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004630 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004631 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4632 ImportKey(AuthorizationSetBuilder()
4633 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004634 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004635 .EcbMode()
4636 .Padding(PaddingMode::PKCS7),
4637 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004638}
4639
4640/*
4641 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004642 *
4643 * Verifies that importing and using an HMAC key works.
4644 */
4645TEST_P(ImportKeyTest, HmacKeySuccess) {
4646 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4647 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4648 .Authorization(TAG_NO_AUTH_REQUIRED)
4649 .HmacKey(key.size() * 8)
4650 .Digest(Digest::SHA_2_256)
4651 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4652 KeyFormat::RAW, key));
4653
4654 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4655 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4656 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4657 CheckOrigin();
4658
4659 string message = "Hello World!";
4660 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4661 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4662}
4663
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004664/*
4665 * ImportKeyTest.GetKeyCharacteristics
4666 *
4667 * Verifies that imported keys have the correct characteristics.
4668 */
4669TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4670 vector<uint8_t> key_blob;
4671 vector<KeyCharacteristics> key_characteristics;
4672 auto base_builder = AuthorizationSetBuilder()
4673 .Padding(PaddingMode::NONE)
4674 .Authorization(TAG_NO_AUTH_REQUIRED)
4675 .SetDefaultValidity();
4676 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4677 Algorithm::TRIPLE_DES};
4678 ErrorCode result;
4679 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4680 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4681 for (auto alg : algorithms) {
4682 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4683 AuthorizationSetBuilder builder(base_builder);
4684 switch (alg) {
4685 case Algorithm::RSA:
4686 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4687
4688 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4689 &key_characteristics);
4690 break;
4691 case Algorithm::EC:
4692 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4693 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4694 &key_characteristics);
4695 break;
4696 case Algorithm::HMAC:
4697 builder.HmacKey(128)
4698 .Digest(Digest::SHA_2_256)
4699 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4700 result =
4701 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4702 break;
4703 case Algorithm::AES:
4704 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4705 result =
4706 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4707 break;
4708 case Algorithm::TRIPLE_DES:
4709 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4710 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4711 &key_characteristics);
4712 break;
4713 default:
4714 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4715 continue;
4716 }
4717 ASSERT_EQ(ErrorCode::OK, result);
4718 CheckCharacteristics(key_blob, key_characteristics);
4719 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4720 }
4721}
4722
Selene Huang31ab4042020-04-29 04:22:39 -07004723INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4724
4725auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004726 // IKeyMintDevice.aidl
4727 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4728 "020100" // INTEGER length 1 value 0x00 (version)
4729 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4730 "934bf94e2aa28a3f83c9f79297250262"
4731 "fbe3276b5a1c91159bbfa3ef8957aac8"
4732 "4b59b30b455a79c2973480823d8b3863"
4733 "c3deef4a8e243590268d80e18751a0e1"
4734 "30f67ce6a1ace9f79b95e097474febc9"
4735 "81195b1d13a69086c0863f66a7b7fdb4"
4736 "8792227b1ac5e2489febdf087ab54864"
4737 "83033a6f001ca5d1ec1e27f5c30f4cec"
4738 "2642074a39ae68aee552e196627a8e3d"
4739 "867e67a8c01b11e75f13cca0a97ab668"
4740 "b50cda07a8ecb7cd8e3dd7009c963653"
4741 "4f6f239cffe1fc8daa466f78b676c711"
4742 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4743 "99b801597d5220e307eaa5bee507fb94"
4744 "d1fa69f9e519b2de315bac92c36f2ea1"
4745 "fa1df4478c0ddedeae8c70e0233cd098"
4746 "040c" // OCTET STRING length 0x0c (initializationVector)
4747 "d796b02c370f1fa4cc0124f1"
4748 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4749 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4750 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4751 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4752 "3106" // SET length 0x06
4753 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4754 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4755 // } end SET
4756 // } end [1]
4757 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4758 "020120" // INTEGER length 1 value 0x20 (AES)
4759 // } end [2]
4760 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4761 "02020100" // INTEGER length 2 value 0x100
4762 // } end [3]
4763 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4764 "3103" // SET length 0x03 {
4765 "020101" // INTEGER length 1 value 0x01 (ECB)
4766 // } end SET
4767 // } end [4]
4768 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4769 "3103" // SET length 0x03 {
4770 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4771 // } end SET
4772 // } end [5]
4773 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4774 // (noAuthRequired)
4775 "0500" // NULL
4776 // } end [503]
4777 // } end SEQUENCE (AuthorizationList)
4778 // } end SEQUENCE (KeyDescription)
4779 "0420" // OCTET STRING length 0x20 (encryptedKey)
4780 "ccd540855f833a5e1480bfd2d36faf3a"
4781 "eee15df5beabe2691bc82dde2a7aa910"
4782 "0410" // OCTET STRING length 0x10 (tag)
4783 "64c9f689c60ff6223ab6e6999e0eb6e5"
4784 // } SEQUENCE (SecureKeyWrapper)
4785);
Selene Huang31ab4042020-04-29 04:22:39 -07004786
4787auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004788 // IKeyMintDevice.aidl
4789 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4790 "020100" // INTEGER length 1 value 0x00 (version)
4791 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4792 "aad93ed5924f283b4bb5526fbe7a1412"
4793 "f9d9749ec30db9062b29e574a8546f33"
4794 "c88732452f5b8e6a391ee76c39ed1712"
4795 "c61d8df6213dec1cffbc17a8c6d04c7b"
4796 "30893d8daa9b2015213e219468215532"
4797 "07f8f9931c4caba23ed3bee28b36947e"
4798 "47f10e0a5c3dc51c988a628daad3e5e1"
4799 "f4005e79c2d5a96c284b4b8d7e4948f3"
4800 "31e5b85dd5a236f85579f3ea1d1b8484"
4801 "87470bdb0ab4f81a12bee42c99fe0df4"
4802 "bee3759453e69ad1d68a809ce06b949f"
4803 "7694a990429b2fe81e066ff43e56a216"
4804 "02db70757922a4bcc23ab89f1e35da77"
4805 "586775f423e519c2ea394caf48a28d0c"
4806 "8020f1dcf6b3a68ec246f615ae96dae9"
4807 "a079b1f6eb959033c1af5c125fd94168"
4808 "040c" // OCTET STRING length 0x0c (initializationVector)
4809 "6d9721d08589581ab49204a3"
4810 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4811 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4812 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4813 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4814 "3106" // SET length 0x06
4815 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4816 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4817 // } end SET
4818 // } end [1]
4819 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4820 "020120" // INTEGER length 1 value 0x20 (AES)
4821 // } end [2]
4822 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4823 "02020100" // INTEGER length 2 value 0x100
4824 // } end [3]
4825 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4826 "3103" // SET length 0x03 {
4827 "020101" // INTEGER length 1 value 0x01 (ECB)
4828 // } end SET
4829 // } end [4]
4830 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4831 "3103" // SET length 0x03 {
4832 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4833 // } end SET
4834 // } end [5]
4835 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4836 // (noAuthRequired)
4837 "0500" // NULL
4838 // } end [503]
4839 // } end SEQUENCE (AuthorizationList)
4840 // } end SEQUENCE (KeyDescription)
4841 "0420" // OCTET STRING length 0x20 (encryptedKey)
4842 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4843 "c20d1f99a9a024a76f35c8e2cab9b68d"
4844 "0410" // OCTET STRING length 0x10 (tag)
4845 "2560c70109ae67c030f00b98b512a670"
4846 // } SEQUENCE (SecureKeyWrapper)
4847);
Selene Huang31ab4042020-04-29 04:22:39 -07004848
4849auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004850 // RFC 5208 s5
4851 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4852 "020100" // INTEGER length 1 value 0x00 (version)
4853 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4854 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4855 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4856 "0500" // NULL (parameters)
4857 // } SEQUENCE (AlgorithmIdentifier)
4858 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4859 // RFC 8017 A.1.2
4860 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4861 "020100" // INTEGER length 1 value 0x00 (version)
4862 "02820101" // INTEGER length 0x0101 (modulus) value...
4863 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4864 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4865 "7b06e673a837313d56b1c725150a3fef" // 0x30
4866 "86acbddc41bb759c2854eae32d35841e" // 0x40
4867 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4868 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4869 "312d7bd5921ffaea1347c157406fef71" // 0x70
4870 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4871 "f4645c11f5c1374c3886427411c44979" // 0x90
4872 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4873 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4874 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4875 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4876 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4877 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4878 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4879 "55" // 0x101
4880 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4881 "02820100" // INTEGER length 0x100 (privateExponent) value...
4882 "431447b6251908112b1ee76f99f3711a" // 0x10
4883 "52b6630960046c2de70de188d833f8b8" // 0x20
4884 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4885 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4886 "e710b630a03adc683b5d2c43080e52be" // 0x50
4887 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4888 "822bccff087d63c940ba8a45f670feb2" // 0x70
4889 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4890 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4891 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4892 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4893 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4894 "52659d5a5ba05b663737a8696281865b" // 0xd0
4895 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4896 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4897 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4898 "028181" // INTEGER length 0x81 (prime1) value...
4899 "00de392e18d682c829266cc3454e1d61" // 0x10
4900 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4901 "ff841be5bac82a164c5970007047b8c5" // 0x30
4902 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4903 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4904 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4905 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4906 "9e91346130748a6e3c124f9149d71c74" // 0x80
4907 "35"
4908 "028181" // INTEGER length 0x81 (prime2) value...
4909 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4910 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4911 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4912 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4913 "9ed39a2d934c880440aed8832f984316" // 0x50
4914 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4915 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4916 "b880677c068e1be936e81288815252a8" // 0x80
4917 "a1"
4918 "028180" // INTEGER length 0x80 (exponent1) value...
4919 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4920 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4921 "5a063212a4f105a3764743e53281988a" // 0x30
4922 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4923 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4924 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4925 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4926 "4719d6e2b9439823719cd08bcd031781" // 0x80
4927 "028181" // INTEGER length 0x81 (exponent2) value...
4928 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4929 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4930 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4931 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4932 "1254186af30b22c10582a8a43e34fe94" // 0x50
4933 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4934 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4935 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4936 "61"
4937 "028181" // INTEGER length 0x81 (coefficient) value...
4938 "00c931617c77829dfb1270502be9195c" // 0x10
4939 "8f2830885f57dba869536811e6864236" // 0x20
4940 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4941 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4942 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4943 "959356210723287b0affcc9f727044d4" // 0x60
4944 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4945 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4946 "22"
4947 // } SEQUENCE
4948 // } SEQUENCE ()
4949);
Selene Huang31ab4042020-04-29 04:22:39 -07004950
4951string zero_masking_key =
4952 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4953string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4954
4955class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4956
4957TEST_P(ImportWrappedKeyTest, Success) {
4958 auto wrapping_key_desc = AuthorizationSetBuilder()
4959 .RsaEncryptionKey(2048, 65537)
4960 .Digest(Digest::SHA_2_256)
4961 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004962 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4963 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004964
4965 ASSERT_EQ(ErrorCode::OK,
4966 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4967 AuthorizationSetBuilder()
4968 .Digest(Digest::SHA_2_256)
4969 .Padding(PaddingMode::RSA_OAEP)));
4970
4971 string message = "Hello World!";
4972 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4973 string ciphertext = EncryptMessage(message, params);
4974 string plaintext = DecryptMessage(ciphertext, params);
4975 EXPECT_EQ(message, plaintext);
4976}
4977
David Drysdaled2cc8c22021-04-15 13:29:45 +01004978/*
4979 * ImportWrappedKeyTest.SuccessSidsIgnored
4980 *
4981 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
4982 * include Tag:USER_SECURE_ID.
4983 */
4984TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
4985 auto wrapping_key_desc = AuthorizationSetBuilder()
4986 .RsaEncryptionKey(2048, 65537)
4987 .Digest(Digest::SHA_2_256)
4988 .Padding(PaddingMode::RSA_OAEP)
4989 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4990 .SetDefaultValidity();
4991
4992 int64_t password_sid = 42;
4993 int64_t biometric_sid = 24;
4994 ASSERT_EQ(ErrorCode::OK,
4995 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4996 AuthorizationSetBuilder()
4997 .Digest(Digest::SHA_2_256)
4998 .Padding(PaddingMode::RSA_OAEP),
4999 password_sid, biometric_sid));
5000
5001 string message = "Hello World!";
5002 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5003 string ciphertext = EncryptMessage(message, params);
5004 string plaintext = DecryptMessage(ciphertext, params);
5005 EXPECT_EQ(message, plaintext);
5006}
5007
Selene Huang31ab4042020-04-29 04:22:39 -07005008TEST_P(ImportWrappedKeyTest, SuccessMasked) {
5009 auto wrapping_key_desc = AuthorizationSetBuilder()
5010 .RsaEncryptionKey(2048, 65537)
5011 .Digest(Digest::SHA_2_256)
5012 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005013 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5014 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005015
5016 ASSERT_EQ(ErrorCode::OK,
5017 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
5018 AuthorizationSetBuilder()
5019 .Digest(Digest::SHA_2_256)
5020 .Padding(PaddingMode::RSA_OAEP)));
5021}
5022
5023TEST_P(ImportWrappedKeyTest, WrongMask) {
5024 auto wrapping_key_desc = AuthorizationSetBuilder()
5025 .RsaEncryptionKey(2048, 65537)
5026 .Digest(Digest::SHA_2_256)
5027 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005028 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5029 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005030
5031 ASSERT_EQ(
5032 ErrorCode::VERIFICATION_FAILED,
5033 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5034 AuthorizationSetBuilder()
5035 .Digest(Digest::SHA_2_256)
5036 .Padding(PaddingMode::RSA_OAEP)));
5037}
5038
5039TEST_P(ImportWrappedKeyTest, WrongPurpose) {
5040 auto wrapping_key_desc = AuthorizationSetBuilder()
5041 .RsaEncryptionKey(2048, 65537)
5042 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005043 .Padding(PaddingMode::RSA_OAEP)
5044 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005045
5046 ASSERT_EQ(
5047 ErrorCode::INCOMPATIBLE_PURPOSE,
5048 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5049 AuthorizationSetBuilder()
5050 .Digest(Digest::SHA_2_256)
5051 .Padding(PaddingMode::RSA_OAEP)));
5052}
5053
David Drysdaled2cc8c22021-04-15 13:29:45 +01005054TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
5055 auto wrapping_key_desc = AuthorizationSetBuilder()
5056 .RsaEncryptionKey(2048, 65537)
5057 .Digest(Digest::SHA_2_256)
5058 .Padding(PaddingMode::RSA_PSS)
5059 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5060 .SetDefaultValidity();
5061
5062 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
5063 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5064 AuthorizationSetBuilder()
5065 .Digest(Digest::SHA_2_256)
5066 .Padding(PaddingMode::RSA_OAEP)));
5067}
5068
5069TEST_P(ImportWrappedKeyTest, WrongDigest) {
5070 auto wrapping_key_desc = AuthorizationSetBuilder()
5071 .RsaEncryptionKey(2048, 65537)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005072 .Padding(PaddingMode::RSA_OAEP)
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005073 .Digest(Digest::SHA_2_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005074 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5075 .SetDefaultValidity();
5076
5077 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
5078 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5079 AuthorizationSetBuilder()
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005080 .Digest(Digest::SHA_2_512)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005081 .Padding(PaddingMode::RSA_OAEP)));
5082}
5083
Selene Huang31ab4042020-04-29 04:22:39 -07005084INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
5085
5086typedef KeyMintAidlTestBase EncryptionOperationsTest;
5087
5088/*
5089 * EncryptionOperationsTest.RsaNoPaddingSuccess
5090 *
David Drysdale59cae642021-05-12 13:52:03 +01005091 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07005092 */
5093TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00005094 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005095 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005096 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5097 .Authorization(TAG_NO_AUTH_REQUIRED)
5098 .RsaEncryptionKey(2048, exponent)
5099 .Padding(PaddingMode::NONE)
5100 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005101
David Drysdaled2cc8c22021-04-15 13:29:45 +01005102 string message = string(2048 / 8, 'a');
5103 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005104 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005105 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005106
David Drysdale59cae642021-05-12 13:52:03 +01005107 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005108 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005109
David Drysdaled2cc8c22021-04-15 13:29:45 +01005110 // Unpadded RSA is deterministic
5111 EXPECT_EQ(ciphertext1, ciphertext2);
5112
5113 CheckedDeleteKey();
5114 }
Selene Huang31ab4042020-04-29 04:22:39 -07005115}
5116
5117/*
5118 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5119 *
David Drysdale59cae642021-05-12 13:52:03 +01005120 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07005121 */
5122TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5123 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5124 .Authorization(TAG_NO_AUTH_REQUIRED)
5125 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005126 .Padding(PaddingMode::NONE)
5127 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005128
5129 string message = "1";
5130 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5131
David Drysdale59cae642021-05-12 13:52:03 +01005132 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005133 EXPECT_EQ(2048U / 8, ciphertext.size());
5134
5135 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5136 string plaintext = DecryptMessage(ciphertext, params);
5137
5138 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005139}
5140
5141/*
Selene Huang31ab4042020-04-29 04:22:39 -07005142 * EncryptionOperationsTest.RsaOaepSuccess
5143 *
David Drysdale59cae642021-05-12 13:52:03 +01005144 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005145 */
5146TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5147 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5148
5149 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01005150 ASSERT_EQ(ErrorCode::OK,
5151 GenerateKey(AuthorizationSetBuilder()
5152 .Authorization(TAG_NO_AUTH_REQUIRED)
5153 .RsaEncryptionKey(key_size, 65537)
5154 .Padding(PaddingMode::RSA_OAEP)
5155 .Digest(digests)
5156 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
5157 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005158
5159 string message = "Hello";
5160
5161 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005162 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5163
5164 auto params = AuthorizationSetBuilder()
5165 .Digest(digest)
5166 .Padding(PaddingMode::RSA_OAEP)
5167 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5168 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005169 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5170 EXPECT_EQ(key_size / 8, ciphertext1.size());
5171
David Drysdale59cae642021-05-12 13:52:03 +01005172 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005173 EXPECT_EQ(key_size / 8, ciphertext2.size());
5174
5175 // OAEP randomizes padding so every result should be different (with astronomically high
5176 // probability).
5177 EXPECT_NE(ciphertext1, ciphertext2);
5178
5179 string plaintext1 = DecryptMessage(ciphertext1, params);
5180 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5181 string plaintext2 = DecryptMessage(ciphertext2, params);
5182 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5183
5184 // Decrypting corrupted ciphertext should fail.
5185 size_t offset_to_corrupt = random() % ciphertext1.size();
5186 char corrupt_byte;
5187 do {
5188 corrupt_byte = static_cast<char>(random() % 256);
5189 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5190 ciphertext1[offset_to_corrupt] = corrupt_byte;
5191
5192 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5193 string result;
5194 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5195 EXPECT_EQ(0U, result.size());
5196 }
5197}
5198
5199/*
5200 * EncryptionOperationsTest.RsaOaepInvalidDigest
5201 *
David Drysdale59cae642021-05-12 13:52:03 +01005202 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005203 * without a digest.
5204 */
5205TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5206 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5207 .Authorization(TAG_NO_AUTH_REQUIRED)
5208 .RsaEncryptionKey(2048, 65537)
5209 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005210 .Digest(Digest::NONE)
5211 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005212
5213 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005214 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005215}
5216
5217/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005218 * EncryptionOperationsTest.RsaOaepInvalidPadding
5219 *
David Drysdale59cae642021-05-12 13:52:03 +01005220 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005221 * with a padding value that is only suitable for signing/verifying.
5222 */
5223TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5224 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5225 .Authorization(TAG_NO_AUTH_REQUIRED)
5226 .RsaEncryptionKey(2048, 65537)
5227 .Padding(PaddingMode::RSA_PSS)
5228 .Digest(Digest::NONE)
5229 .SetDefaultValidity()));
5230
5231 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005232 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005233}
5234
5235/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005236 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005237 *
David Drysdale59cae642021-05-12 13:52:03 +01005238 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005239 * with a different digest than was used to encrypt.
5240 */
5241TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005242 if (SecLevel() == SecurityLevel::STRONGBOX) {
5243 GTEST_SKIP() << "Test not applicable to StrongBox device";
5244 }
Selene Huang31ab4042020-04-29 04:22:39 -07005245
5246 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5247 .Authorization(TAG_NO_AUTH_REQUIRED)
5248 .RsaEncryptionKey(1024, 65537)
5249 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005250 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5251 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005252 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005253 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005254 message,
5255 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5256
5257 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5258 .Digest(Digest::SHA_2_256)
5259 .Padding(PaddingMode::RSA_OAEP)));
5260 string result;
5261 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5262 EXPECT_EQ(0U, result.size());
5263}
5264
5265/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005266 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5267 *
David Drysdale59cae642021-05-12 13:52:03 +01005268 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005269 * digests.
5270 */
5271TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5272 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5273
5274 size_t key_size = 2048; // Need largish key for SHA-512 test.
5275 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5276 .OaepMGFDigest(digests)
5277 .Authorization(TAG_NO_AUTH_REQUIRED)
5278 .RsaEncryptionKey(key_size, 65537)
5279 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005280 .Digest(Digest::SHA_2_256)
5281 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005282
5283 string message = "Hello";
5284
5285 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005286 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005287 auto params = AuthorizationSetBuilder()
5288 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5289 .Digest(Digest::SHA_2_256)
5290 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005291 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005292 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5293 EXPECT_EQ(key_size / 8, ciphertext1.size());
5294
David Drysdale59cae642021-05-12 13:52:03 +01005295 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005296 EXPECT_EQ(key_size / 8, ciphertext2.size());
5297
5298 // OAEP randomizes padding so every result should be different (with astronomically high
5299 // probability).
5300 EXPECT_NE(ciphertext1, ciphertext2);
5301
5302 string plaintext1 = DecryptMessage(ciphertext1, params);
5303 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5304 string plaintext2 = DecryptMessage(ciphertext2, params);
5305 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5306
5307 // Decrypting corrupted ciphertext should fail.
5308 size_t offset_to_corrupt = random() % ciphertext1.size();
5309 char corrupt_byte;
5310 do {
5311 corrupt_byte = static_cast<char>(random() % 256);
5312 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5313 ciphertext1[offset_to_corrupt] = corrupt_byte;
5314
5315 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5316 string result;
5317 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5318 EXPECT_EQ(0U, result.size());
5319 }
5320}
5321
5322/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005323 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5324 *
5325 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5326 * specified, defaulting to SHA-1.
5327 */
5328TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5329 size_t key_size = 2048;
5330 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5331 .Authorization(TAG_NO_AUTH_REQUIRED)
5332 .RsaEncryptionKey(key_size, 65537)
5333 .Padding(PaddingMode::RSA_OAEP)
5334 .Digest(Digest::SHA_2_256)
5335 .SetDefaultValidity()));
5336
5337 // Do local RSA encryption using the default MGF digest of SHA-1.
5338 string message = "Hello";
5339 auto params =
5340 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5341 string ciphertext = LocalRsaEncryptMessage(message, params);
5342 EXPECT_EQ(key_size / 8, ciphertext.size());
5343
5344 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5345 string plaintext = DecryptMessage(ciphertext, params);
5346 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5347
5348 // Decrypting corrupted ciphertext should fail.
5349 size_t offset_to_corrupt = random() % ciphertext.size();
5350 char corrupt_byte;
5351 do {
5352 corrupt_byte = static_cast<char>(random() % 256);
5353 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5354 ciphertext[offset_to_corrupt] = corrupt_byte;
5355
5356 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5357 string result;
5358 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5359 EXPECT_EQ(0U, result.size());
5360}
5361
5362/*
5363 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5364 *
5365 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5366 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5367 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5368 */
5369TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5370 size_t key_size = 2048;
5371 ASSERT_EQ(ErrorCode::OK,
5372 GenerateKey(AuthorizationSetBuilder()
5373 .Authorization(TAG_NO_AUTH_REQUIRED)
5374 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5375 .RsaEncryptionKey(key_size, 65537)
5376 .Padding(PaddingMode::RSA_OAEP)
5377 .Digest(Digest::SHA_2_256)
5378 .SetDefaultValidity()));
5379
5380 // Do local RSA encryption using the default MGF digest of SHA-1.
5381 string message = "Hello";
5382 auto params =
5383 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5384 string ciphertext = LocalRsaEncryptMessage(message, params);
5385 EXPECT_EQ(key_size / 8, ciphertext.size());
5386
5387 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5388 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5389 // is checked against those values, and found absent.
5390 auto result = Begin(KeyPurpose::DECRYPT, params);
5391 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5392 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5393}
5394
5395/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005396 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5397 *
David Drysdale59cae642021-05-12 13:52:03 +01005398 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005399 * with incompatible MGF digest.
5400 */
5401TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5402 ASSERT_EQ(ErrorCode::OK,
5403 GenerateKey(AuthorizationSetBuilder()
5404 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5405 .Authorization(TAG_NO_AUTH_REQUIRED)
5406 .RsaEncryptionKey(2048, 65537)
5407 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005408 .Digest(Digest::SHA_2_256)
5409 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005410 string message = "Hello World!";
5411
5412 auto params = AuthorizationSetBuilder()
5413 .Padding(PaddingMode::RSA_OAEP)
5414 .Digest(Digest::SHA_2_256)
5415 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005416 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005417}
5418
5419/*
5420 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5421 *
5422 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5423 * with unsupported MGF digest.
5424 */
5425TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5426 ASSERT_EQ(ErrorCode::OK,
5427 GenerateKey(AuthorizationSetBuilder()
5428 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5429 .Authorization(TAG_NO_AUTH_REQUIRED)
5430 .RsaEncryptionKey(2048, 65537)
5431 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005432 .Digest(Digest::SHA_2_256)
5433 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005434 string message = "Hello World!";
5435
5436 auto params = AuthorizationSetBuilder()
5437 .Padding(PaddingMode::RSA_OAEP)
5438 .Digest(Digest::SHA_2_256)
5439 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005440 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005441}
5442
5443/*
Selene Huang31ab4042020-04-29 04:22:39 -07005444 * EncryptionOperationsTest.RsaPkcs1Success
5445 *
5446 * Verifies that RSA PKCS encryption/decrypts works.
5447 */
5448TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5449 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5450 .Authorization(TAG_NO_AUTH_REQUIRED)
5451 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005452 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5453 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005454
5455 string message = "Hello World!";
5456 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005457 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005458 EXPECT_EQ(2048U / 8, ciphertext1.size());
5459
David Drysdale59cae642021-05-12 13:52:03 +01005460 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005461 EXPECT_EQ(2048U / 8, ciphertext2.size());
5462
5463 // PKCS1 v1.5 randomizes padding so every result should be different.
5464 EXPECT_NE(ciphertext1, ciphertext2);
5465
5466 string plaintext = DecryptMessage(ciphertext1, params);
5467 EXPECT_EQ(message, plaintext);
5468
5469 // Decrypting corrupted ciphertext should fail.
5470 size_t offset_to_corrupt = random() % ciphertext1.size();
5471 char corrupt_byte;
5472 do {
5473 corrupt_byte = static_cast<char>(random() % 256);
5474 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5475 ciphertext1[offset_to_corrupt] = corrupt_byte;
5476
5477 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5478 string result;
5479 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5480 EXPECT_EQ(0U, result.size());
5481}
5482
5483/*
Selene Huang31ab4042020-04-29 04:22:39 -07005484 * EncryptionOperationsTest.EcdsaEncrypt
5485 *
5486 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5487 */
5488TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5489 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5490 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005491 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005492 .Digest(Digest::NONE)
5493 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005494 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5495 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5496 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5497}
5498
5499/*
5500 * EncryptionOperationsTest.HmacEncrypt
5501 *
5502 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5503 */
5504TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5505 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5506 .Authorization(TAG_NO_AUTH_REQUIRED)
5507 .HmacKey(128)
5508 .Digest(Digest::SHA_2_256)
5509 .Padding(PaddingMode::NONE)
5510 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5511 auto params = AuthorizationSetBuilder()
5512 .Digest(Digest::SHA_2_256)
5513 .Padding(PaddingMode::NONE)
5514 .Authorization(TAG_MAC_LENGTH, 128);
5515 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5516 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5517}
5518
5519/*
5520 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5521 *
5522 * Verifies that AES ECB mode works.
5523 */
5524TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5525 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5526 .Authorization(TAG_NO_AUTH_REQUIRED)
5527 .AesEncryptionKey(128)
5528 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5529 .Padding(PaddingMode::NONE)));
5530
5531 ASSERT_GT(key_blob_.size(), 0U);
5532 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5533
5534 // Two-block message.
5535 string message = "12345678901234567890123456789012";
5536 string ciphertext1 = EncryptMessage(message, params);
5537 EXPECT_EQ(message.size(), ciphertext1.size());
5538
5539 string ciphertext2 = EncryptMessage(string(message), params);
5540 EXPECT_EQ(message.size(), ciphertext2.size());
5541
5542 // ECB is deterministic.
5543 EXPECT_EQ(ciphertext1, ciphertext2);
5544
5545 string plaintext = DecryptMessage(ciphertext1, params);
5546 EXPECT_EQ(message, plaintext);
5547}
5548
5549/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005550 * EncryptionOperationsTest.AesEcbUnknownTag
5551 *
5552 * Verifies that AES ECB operations ignore unknown tags.
5553 */
5554TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5555 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5556 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5557 KeyParameter unknown_param;
5558 unknown_param.tag = unknown_tag;
5559
5560 vector<KeyCharacteristics> key_characteristics;
5561 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5562 .Authorization(TAG_NO_AUTH_REQUIRED)
5563 .AesEncryptionKey(128)
5564 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5565 .Padding(PaddingMode::NONE)
5566 .Authorization(unknown_param),
5567 &key_blob_, &key_characteristics));
5568 ASSERT_GT(key_blob_.size(), 0U);
5569
5570 // Unknown tags should not be returned in key characteristics.
5571 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5572 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5573 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5574 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5575
5576 // Encrypt without mentioning the unknown parameter.
5577 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5578 string message = "12345678901234567890123456789012";
5579 string ciphertext = EncryptMessage(message, params);
5580 EXPECT_EQ(message.size(), ciphertext.size());
5581
5582 // Decrypt including the unknown parameter.
5583 auto decrypt_params = AuthorizationSetBuilder()
5584 .BlockMode(BlockMode::ECB)
5585 .Padding(PaddingMode::NONE)
5586 .Authorization(unknown_param);
5587 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5588 EXPECT_EQ(message, plaintext);
5589}
5590
5591/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005592 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005593 *
5594 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5595 */
5596TEST_P(EncryptionOperationsTest, AesWrongMode) {
5597 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5598 .Authorization(TAG_NO_AUTH_REQUIRED)
5599 .AesEncryptionKey(128)
5600 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5601 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005602 ASSERT_GT(key_blob_.size(), 0U);
5603
Selene Huang31ab4042020-04-29 04:22:39 -07005604 EXPECT_EQ(
5605 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5606 Begin(KeyPurpose::ENCRYPT,
5607 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5608}
5609
5610/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005611 * EncryptionOperationsTest.AesWrongPadding
5612 *
5613 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5614 */
5615TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5616 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5617 .Authorization(TAG_NO_AUTH_REQUIRED)
5618 .AesEncryptionKey(128)
5619 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5620 .Padding(PaddingMode::NONE)));
5621 ASSERT_GT(key_blob_.size(), 0U);
5622
5623 EXPECT_EQ(
5624 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5625 Begin(KeyPurpose::ENCRYPT,
5626 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5627}
5628
5629/*
5630 * EncryptionOperationsTest.AesInvalidParams
5631 *
5632 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5633 */
5634TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5635 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5636 .Authorization(TAG_NO_AUTH_REQUIRED)
5637 .AesEncryptionKey(128)
5638 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5639 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5640 .Padding(PaddingMode::NONE)
5641 .Padding(PaddingMode::PKCS7)));
5642 ASSERT_GT(key_blob_.size(), 0U);
5643
5644 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5645 .BlockMode(BlockMode::CBC)
5646 .BlockMode(BlockMode::ECB)
5647 .Padding(PaddingMode::NONE));
5648 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5649 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5650
5651 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5652 .BlockMode(BlockMode::ECB)
5653 .Padding(PaddingMode::NONE)
5654 .Padding(PaddingMode::PKCS7));
5655 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5656 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5657}
5658
5659/*
Selene Huang31ab4042020-04-29 04:22:39 -07005660 * EncryptionOperationsTest.AesWrongPurpose
5661 *
5662 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5663 * specified.
5664 */
5665TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5666 auto err = GenerateKey(AuthorizationSetBuilder()
5667 .Authorization(TAG_NO_AUTH_REQUIRED)
5668 .AesKey(128)
5669 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5670 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5671 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5672 .Padding(PaddingMode::NONE));
5673 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5674 ASSERT_GT(key_blob_.size(), 0U);
5675
5676 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5677 .BlockMode(BlockMode::GCM)
5678 .Padding(PaddingMode::NONE)
5679 .Authorization(TAG_MAC_LENGTH, 128));
5680 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5681
5682 CheckedDeleteKey();
5683
5684 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5685 .Authorization(TAG_NO_AUTH_REQUIRED)
5686 .AesKey(128)
5687 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5688 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5689 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5690 .Padding(PaddingMode::NONE)));
5691
5692 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5693 .BlockMode(BlockMode::GCM)
5694 .Padding(PaddingMode::NONE)
5695 .Authorization(TAG_MAC_LENGTH, 128));
5696 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5697}
5698
5699/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005700 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005701 *
5702 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5703 * multiple of the block size and no padding is specified.
5704 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005705TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5706 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005707 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005708 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5709 .Authorization(TAG_NO_AUTH_REQUIRED)
5710 .AesEncryptionKey(128)
5711 .Authorization(TAG_BLOCK_MODE, blockMode)
5712 .Padding(PaddingMode::NONE)));
5713 // Message is slightly shorter than two blocks.
5714 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005715
David Drysdaled2cc8c22021-04-15 13:29:45 +01005716 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5717 AuthorizationSet out_params;
5718 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5719 string ciphertext;
5720 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5721 EXPECT_EQ(0U, ciphertext.size());
5722
5723 CheckedDeleteKey();
5724 }
Selene Huang31ab4042020-04-29 04:22:39 -07005725}
5726
5727/*
5728 * EncryptionOperationsTest.AesEcbPkcs7Padding
5729 *
5730 * Verifies that AES PKCS7 padding works for any message length.
5731 */
5732TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5733 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5734 .Authorization(TAG_NO_AUTH_REQUIRED)
5735 .AesEncryptionKey(128)
5736 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5737 .Padding(PaddingMode::PKCS7)));
5738
5739 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5740
5741 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005742 for (size_t i = 0; i <= 48; i++) {
5743 SCOPED_TRACE(testing::Message() << "i = " << i);
5744 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5745 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005746 string ciphertext = EncryptMessage(message, params);
5747 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5748 string plaintext = DecryptMessage(ciphertext, params);
5749 EXPECT_EQ(message, plaintext);
5750 }
5751}
5752
5753/*
5754 * EncryptionOperationsTest.AesEcbWrongPadding
5755 *
5756 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5757 * specified.
5758 */
5759TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5760 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5761 .Authorization(TAG_NO_AUTH_REQUIRED)
5762 .AesEncryptionKey(128)
5763 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5764 .Padding(PaddingMode::NONE)));
5765
5766 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5767
5768 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005769 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005770 string message(i, 'a');
5771 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5772 }
5773}
5774
5775/*
5776 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5777 *
5778 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5779 */
5780TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5781 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5782 .Authorization(TAG_NO_AUTH_REQUIRED)
5783 .AesEncryptionKey(128)
5784 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5785 .Padding(PaddingMode::PKCS7)));
5786
5787 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5788
5789 string message = "a";
5790 string ciphertext = EncryptMessage(message, params);
5791 EXPECT_EQ(16U, ciphertext.size());
5792 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005793
Seth Moore7a55ae32021-06-23 14:28:11 -07005794 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5795 ++ciphertext[ciphertext.size() / 2];
5796
5797 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5798 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005799 ErrorCode error = Finish(ciphertext, &plaintext);
5800 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005801 // This is the expected error, we can exit the test now.
5802 return;
5803 } else {
5804 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005805 ASSERT_EQ(error, ErrorCode::OK)
5806 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005807 }
5808 }
5809 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005810}
5811
David Drysdaleb8093292022-04-08 12:22:35 +01005812/*
5813 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5814 *
5815 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5816 */
5817TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5818 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5819 .Authorization(TAG_NO_AUTH_REQUIRED)
5820 .AesEncryptionKey(128)
5821 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5822 .Padding(PaddingMode::PKCS7)));
5823
5824 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5825
5826 string message = "a";
5827 string ciphertext = EncryptMessage(message, params);
5828 EXPECT_EQ(16U, ciphertext.size());
5829 EXPECT_NE(ciphertext, message);
5830
5831 // Shorten the ciphertext.
5832 ciphertext.resize(ciphertext.size() - 1);
5833 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5834 string plaintext;
5835 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5836}
5837
Selene Huang31ab4042020-04-29 04:22:39 -07005838vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5839 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005840 EXPECT_TRUE(iv);
5841 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005842}
5843
5844/*
5845 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5846 *
5847 * Verifies that AES CTR mode works.
5848 */
5849TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5850 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5851 .Authorization(TAG_NO_AUTH_REQUIRED)
5852 .AesEncryptionKey(128)
5853 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5854 .Padding(PaddingMode::NONE)));
5855
5856 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5857
5858 string message = "123";
5859 AuthorizationSet out_params;
5860 string ciphertext1 = EncryptMessage(message, params, &out_params);
5861 vector<uint8_t> iv1 = CopyIv(out_params);
5862 EXPECT_EQ(16U, iv1.size());
5863
5864 EXPECT_EQ(message.size(), ciphertext1.size());
5865
5866 out_params.Clear();
5867 string ciphertext2 = EncryptMessage(message, params, &out_params);
5868 vector<uint8_t> iv2 = CopyIv(out_params);
5869 EXPECT_EQ(16U, iv2.size());
5870
5871 // IVs should be random, so ciphertexts should differ.
5872 EXPECT_NE(ciphertext1, ciphertext2);
5873
5874 auto params_iv1 =
5875 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5876 auto params_iv2 =
5877 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5878
5879 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5880 EXPECT_EQ(message, plaintext);
5881 plaintext = DecryptMessage(ciphertext2, params_iv2);
5882 EXPECT_EQ(message, plaintext);
5883
5884 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5885 plaintext = DecryptMessage(ciphertext1, params_iv2);
5886 EXPECT_NE(message, plaintext);
5887 plaintext = DecryptMessage(ciphertext2, params_iv1);
5888 EXPECT_NE(message, plaintext);
5889}
5890
5891/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305892 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07005893 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305894 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07005895 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305896TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5897 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5898}
Selene Huang31ab4042020-04-29 04:22:39 -07005899
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305900/*
5901 * EncryptionOperationsTest.AesCbcIncremental
5902 *
5903 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5904 */
5905TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5906 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5907}
Selene Huang31ab4042020-04-29 04:22:39 -07005908
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305909/*
5910 * EncryptionOperationsTest.AesCtrIncremental
5911 *
5912 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5913 */
5914TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5915 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5916}
Selene Huang31ab4042020-04-29 04:22:39 -07005917
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305918/*
5919 * EncryptionOperationsTest.AesGcmIncremental
5920 *
5921 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5922 */
5923TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5924 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07005925}
5926
Prashant Patildd5f7f02022-07-06 18:58:07 +00005927/*
5928 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
5929 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5930 */
5931TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
5932 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
5933 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
5934 string kat_plaintext =
5935 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
5936 "809FFF37081C22EF278F896AB213A2A631");
5937 string kat_ciphertext =
5938 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
5939 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
5940 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5941 kat_ciphertext);
5942}
5943
5944/*
5945 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
5946 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5947 */
5948TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
5949 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
5950 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
5951 string kat_plaintext =
5952 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
5953 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
5954 string kat_ciphertext =
5955 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
5956 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
5957 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
5958 kat_plaintext, kat_ciphertext);
5959}
5960
5961/*
5962 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
5963 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
5964 */
5965TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
5966 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
5967 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
5968 string kat_plaintext =
5969 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
5970 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
5971 string kat_ciphertext =
5972 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
5973 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
5974 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
5975 kat_ciphertext);
5976}
5977
5978/*
5979 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
5980 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
5981 */
5982TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
5983 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
5984 string kat_plaintext =
5985 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
5986 "7B6168A9A27BCE554BEA94EF26E6C742A0");
5987 string kat_ciphertext =
5988 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
5989 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
5990 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
5991 kat_ciphertext);
5992}
5993
5994/*
5995 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
5996 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
5997 */
5998TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
5999 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
6000 string kat_plaintext =
6001 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
6002 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
6003 string kat_ciphertext =
6004 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
6005 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
6006 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6007 kat_ciphertext);
6008}
6009
6010/*
6011 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
6012 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6013 */
6014TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
6015 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
6016 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
6017 string kat_plaintext =
6018 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
6019 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
6020 string kat_ciphertext =
6021 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
6022 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
6023 "bdfcc0cba0");
6024
6025 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6026 kat_ciphertext);
6027}
6028
6029/*
6030 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
6031 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6032 */
6033TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
6034 if (SecLevel() == SecurityLevel::STRONGBOX) {
6035 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6036 }
6037 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
6038 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
6039 string kat_plaintext =
6040 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
6041 "167f2497c994bd496eb80bfb2ba2c9d5af");
6042 string kat_ciphertext =
6043 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
6044 "72c134552f3a138e726fbe493b3a839598");
6045 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6046 kat_ciphertext);
6047}
6048
6049/*
6050 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
6051 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6052 */
6053TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
6054 if (SecLevel() == SecurityLevel::STRONGBOX) {
6055 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6056 }
6057 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
6058 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
6059 string kat_plaintext =
6060 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
6061 "b170");
6062 string kat_ciphertext =
6063 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
6064 "4e3884138ff403a41fd99818708ada301c");
6065 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6066 kat_plaintext, kat_ciphertext);
6067}
6068
6069/*
6070 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
6071 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6072 */
6073TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
6074 if (SecLevel() == SecurityLevel::STRONGBOX) {
6075 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6076 }
6077 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
6078 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
6079 string kat_plaintext =
6080 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
6081 "28091e09cdbbd3b42b");
6082 string kat_ciphertext =
6083 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
6084 "2ae0f90f0c19f42b4a");
6085 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6086 kat_ciphertext);
6087}
6088
6089/*
6090 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
6091 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6092 */
6093TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
6094 if (SecLevel() == SecurityLevel::STRONGBOX) {
6095 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6096 }
6097 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
6098 string kat_plaintext =
6099 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
6100 "44ab");
6101 string kat_ciphertext =
6102 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
6103 "2453");
6104 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6105 kat_ciphertext);
6106}
6107
6108/*
6109 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6110 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6111 */
6112TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6113 if (SecLevel() == SecurityLevel::STRONGBOX) {
6114 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6115 }
6116 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6117 string kat_plaintext =
6118 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6119 "e2c7");
6120 string kat_ciphertext =
6121 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6122 "bb7e3a889dd4a9589098b44acf1056e7aa");
6123 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6124 kat_ciphertext);
6125}
6126
6127/*
6128 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6129 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6130 */
6131TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6132 if (SecLevel() == SecurityLevel::STRONGBOX) {
6133 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6134 }
6135 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6136 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6137 string kat_plaintext =
6138 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6139 "ff52");
6140 string kat_ciphertext =
6141 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6142 "1413ad70fb0e1970669095ad77ebb5974ae8");
6143
6144 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6145 kat_ciphertext);
6146}
6147
6148/*
6149 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6150 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6151 */
6152TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6153 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6154 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6155 string kat_plaintext =
6156 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6157 "494cb53caca353e4b637ba05687be20f8d");
6158 string kat_ciphertext =
6159 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6160 "6047da1e4fd7c4e1cf2656097f75ae8685");
6161 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6162 kat_ciphertext);
6163}
6164
6165/*
6166 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6167 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6168 */
6169TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6170 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6171 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6172 string kat_plaintext =
6173 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6174 "2545a82b73c48078b9dae62261c65909");
6175 string kat_ciphertext =
6176 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6177 "9403a71987b95124073d69f2a3cb95b0ab");
6178 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6179 kat_plaintext, kat_ciphertext);
6180}
6181
6182/*
6183 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6184 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6185 */
6186TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6187 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6188 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6189 string kat_plaintext =
6190 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6191 "1f6db3c884");
6192 string kat_ciphertext =
6193 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6194 "a7be30d4c3");
6195 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6196 kat_ciphertext);
6197}
6198
6199/*
6200 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6201 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6202 */
6203TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6204 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6205 string kat_plaintext =
6206 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6207 "31a476d6806b8116089c6ec50bb543200f");
6208 string kat_ciphertext =
6209 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6210 "c83e377faf246288931136bef2a07c0be4");
6211 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6212 kat_ciphertext);
6213}
6214
6215/*
6216 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6217 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6218 */
6219TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6220 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6221 string kat_plaintext =
6222 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6223 "6f");
6224 string kat_ciphertext =
6225 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6226 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6227 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6228 kat_ciphertext);
6229}
6230
6231/*
6232 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6233 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6234 */
6235TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6236 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6237 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6238 string kat_plaintext =
6239 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6240 "f0");
6241 string kat_ciphertext =
6242 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6243 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6244
6245 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6246 kat_ciphertext);
6247}
6248
Selene Huang31ab4042020-04-29 04:22:39 -07006249struct AesCtrSp80038aTestVector {
6250 const char* key;
6251 const char* nonce;
6252 const char* plaintext;
6253 const char* ciphertext;
6254};
6255
6256// These test vectors are taken from
6257// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6258static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6259 // AES-128
6260 {
6261 "2b7e151628aed2a6abf7158809cf4f3c",
6262 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6263 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6264 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6265 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6266 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6267 },
6268 // AES-192
6269 {
6270 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6271 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6272 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6273 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6274 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6275 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6276 },
6277 // AES-256
6278 {
6279 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6280 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6281 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6282 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6283 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6284 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6285 },
6286};
6287
6288/*
6289 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6290 *
6291 * Verifies AES CTR implementation against SP800-38A test vectors.
6292 */
6293TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6294 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6295 for (size_t i = 0; i < 3; i++) {
6296 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6297 const string key = hex2str(test.key);
6298 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6299 InvalidSizes.end())
6300 continue;
6301 const string nonce = hex2str(test.nonce);
6302 const string plaintext = hex2str(test.plaintext);
6303 const string ciphertext = hex2str(test.ciphertext);
6304 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6305 }
6306}
6307
6308/*
6309 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6310 *
6311 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6312 */
6313TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6314 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6315 .Authorization(TAG_NO_AUTH_REQUIRED)
6316 .AesEncryptionKey(128)
6317 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6318 .Padding(PaddingMode::PKCS7)));
6319 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6320 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6321}
6322
6323/*
6324 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6325 *
6326 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6327 */
6328TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6329 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6330 .Authorization(TAG_NO_AUTH_REQUIRED)
6331 .AesEncryptionKey(128)
6332 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6333 .Authorization(TAG_CALLER_NONCE)
6334 .Padding(PaddingMode::NONE)));
6335
6336 auto params = AuthorizationSetBuilder()
6337 .BlockMode(BlockMode::CTR)
6338 .Padding(PaddingMode::NONE)
6339 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6340 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6341
6342 params = AuthorizationSetBuilder()
6343 .BlockMode(BlockMode::CTR)
6344 .Padding(PaddingMode::NONE)
6345 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6346 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6347
6348 params = AuthorizationSetBuilder()
6349 .BlockMode(BlockMode::CTR)
6350 .Padding(PaddingMode::NONE)
6351 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6352 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6353}
6354
6355/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006356 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006357 *
6358 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6359 */
6360TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6361 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6362 .Authorization(TAG_NO_AUTH_REQUIRED)
6363 .AesEncryptionKey(128)
6364 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6365 .Padding(PaddingMode::NONE)));
6366 // Two-block message.
6367 string message = "12345678901234567890123456789012";
6368 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6369 AuthorizationSet out_params;
6370 string ciphertext1 = EncryptMessage(message, params, &out_params);
6371 vector<uint8_t> iv1 = CopyIv(out_params);
6372 EXPECT_EQ(message.size(), ciphertext1.size());
6373
6374 out_params.Clear();
6375
6376 string ciphertext2 = EncryptMessage(message, params, &out_params);
6377 vector<uint8_t> iv2 = CopyIv(out_params);
6378 EXPECT_EQ(message.size(), ciphertext2.size());
6379
6380 // IVs should be random, so ciphertexts should differ.
6381 EXPECT_NE(ciphertext1, ciphertext2);
6382
6383 params.push_back(TAG_NONCE, iv1);
6384 string plaintext = DecryptMessage(ciphertext1, params);
6385 EXPECT_EQ(message, plaintext);
6386}
6387
6388/*
Tommy Chiuee705692021-09-23 20:09:13 +08006389 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6390 *
6391 * Verifies that keymaster generates correct output on zero-input with
6392 * NonePadding mode
6393 */
6394TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6395 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6396 .Authorization(TAG_NO_AUTH_REQUIRED)
6397 .AesEncryptionKey(128)
6398 .BlockMode(BlockMode::CBC)
6399 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6400
6401 // Zero input message
6402 string message = "";
6403 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006404 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006405 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6406 AuthorizationSet out_params;
6407 string ciphertext1 = EncryptMessage(message, params, &out_params);
6408 vector<uint8_t> iv1 = CopyIv(out_params);
6409 if (padding == PaddingMode::NONE)
6410 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6411 else
6412 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6413
6414 out_params.Clear();
6415
6416 string ciphertext2 = EncryptMessage(message, params, &out_params);
6417 vector<uint8_t> iv2 = CopyIv(out_params);
6418 if (padding == PaddingMode::NONE)
6419 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6420 else
6421 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6422
6423 // IVs should be random
6424 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6425
6426 params.push_back(TAG_NONCE, iv1);
6427 string plaintext = DecryptMessage(ciphertext1, params);
6428 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6429 }
6430}
6431
6432/*
Selene Huang31ab4042020-04-29 04:22:39 -07006433 * EncryptionOperationsTest.AesCallerNonce
6434 *
6435 * Verifies that AES caller-provided nonces work correctly.
6436 */
6437TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6438 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6439 .Authorization(TAG_NO_AUTH_REQUIRED)
6440 .AesEncryptionKey(128)
6441 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6442 .Authorization(TAG_CALLER_NONCE)
6443 .Padding(PaddingMode::NONE)));
6444
6445 string message = "12345678901234567890123456789012";
6446
6447 // Don't specify nonce, should get a random one.
6448 AuthorizationSetBuilder params =
6449 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6450 AuthorizationSet out_params;
6451 string ciphertext = EncryptMessage(message, params, &out_params);
6452 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006453 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006454
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006455 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006456 string plaintext = DecryptMessage(ciphertext, params);
6457 EXPECT_EQ(message, plaintext);
6458
6459 // Now specify a nonce, should also work.
6460 params = AuthorizationSetBuilder()
6461 .BlockMode(BlockMode::CBC)
6462 .Padding(PaddingMode::NONE)
6463 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6464 out_params.Clear();
6465 ciphertext = EncryptMessage(message, params, &out_params);
6466
6467 // Decrypt with correct nonce.
6468 plaintext = DecryptMessage(ciphertext, params);
6469 EXPECT_EQ(message, plaintext);
6470
6471 // Try with wrong nonce.
6472 params = AuthorizationSetBuilder()
6473 .BlockMode(BlockMode::CBC)
6474 .Padding(PaddingMode::NONE)
6475 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6476 plaintext = DecryptMessage(ciphertext, params);
6477 EXPECT_NE(message, plaintext);
6478}
6479
6480/*
6481 * EncryptionOperationsTest.AesCallerNonceProhibited
6482 *
6483 * Verifies that caller-provided nonces are not permitted when not specified in the key
6484 * authorizations.
6485 */
6486TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6487 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6488 .Authorization(TAG_NO_AUTH_REQUIRED)
6489 .AesEncryptionKey(128)
6490 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6491 .Padding(PaddingMode::NONE)));
6492
6493 string message = "12345678901234567890123456789012";
6494
6495 // Don't specify nonce, should get a random one.
6496 AuthorizationSetBuilder params =
6497 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6498 AuthorizationSet out_params;
6499 string ciphertext = EncryptMessage(message, params, &out_params);
6500 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006501 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006502
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006503 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006504 string plaintext = DecryptMessage(ciphertext, params);
6505 EXPECT_EQ(message, plaintext);
6506
6507 // Now specify a nonce, should fail
6508 params = AuthorizationSetBuilder()
6509 .BlockMode(BlockMode::CBC)
6510 .Padding(PaddingMode::NONE)
6511 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6512 out_params.Clear();
6513 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6514}
6515
6516/*
6517 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6518 *
6519 * Verifies that AES GCM mode works.
6520 */
6521TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6522 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6523 .Authorization(TAG_NO_AUTH_REQUIRED)
6524 .AesEncryptionKey(128)
6525 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6526 .Padding(PaddingMode::NONE)
6527 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6528
6529 string aad = "foobar";
6530 string message = "123456789012345678901234567890123456";
6531
6532 auto begin_params = AuthorizationSetBuilder()
6533 .BlockMode(BlockMode::GCM)
6534 .Padding(PaddingMode::NONE)
6535 .Authorization(TAG_MAC_LENGTH, 128);
6536
Selene Huang31ab4042020-04-29 04:22:39 -07006537 // Encrypt
6538 AuthorizationSet begin_out_params;
6539 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6540 << "Begin encrypt";
6541 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006542 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6543 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006544 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6545
6546 // Grab nonce
6547 begin_params.push_back(begin_out_params);
6548
6549 // Decrypt.
6550 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006551 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006552 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006553 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006554 EXPECT_EQ(message.length(), plaintext.length());
6555 EXPECT_EQ(message, plaintext);
6556}
6557
6558/*
6559 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6560 *
6561 * Verifies that AES GCM mode works, even when there's a long delay
6562 * between operations.
6563 */
6564TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6565 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6566 .Authorization(TAG_NO_AUTH_REQUIRED)
6567 .AesEncryptionKey(128)
6568 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6569 .Padding(PaddingMode::NONE)
6570 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6571
6572 string aad = "foobar";
6573 string message = "123456789012345678901234567890123456";
6574
6575 auto begin_params = AuthorizationSetBuilder()
6576 .BlockMode(BlockMode::GCM)
6577 .Padding(PaddingMode::NONE)
6578 .Authorization(TAG_MAC_LENGTH, 128);
6579
Selene Huang31ab4042020-04-29 04:22:39 -07006580 // Encrypt
6581 AuthorizationSet begin_out_params;
6582 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6583 << "Begin encrypt";
6584 string ciphertext;
6585 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006586 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006587 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006588 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006589
6590 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6591
6592 // Grab nonce
6593 begin_params.push_back(begin_out_params);
6594
6595 // Decrypt.
6596 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6597 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006598 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006599 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006600 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006601 sleep(5);
6602 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6603 EXPECT_EQ(message.length(), plaintext.length());
6604 EXPECT_EQ(message, plaintext);
6605}
6606
6607/*
6608 * EncryptionOperationsTest.AesGcmDifferentNonces
6609 *
6610 * Verifies that encrypting the same data with different nonces produces different outputs.
6611 */
6612TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6613 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6614 .Authorization(TAG_NO_AUTH_REQUIRED)
6615 .AesEncryptionKey(128)
6616 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6617 .Padding(PaddingMode::NONE)
6618 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6619 .Authorization(TAG_CALLER_NONCE)));
6620
6621 string aad = "foobar";
6622 string message = "123456789012345678901234567890123456";
6623 string nonce1 = "000000000000";
6624 string nonce2 = "111111111111";
6625 string nonce3 = "222222222222";
6626
6627 string ciphertext1 =
6628 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6629 string ciphertext2 =
6630 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6631 string ciphertext3 =
6632 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6633
6634 ASSERT_NE(ciphertext1, ciphertext2);
6635 ASSERT_NE(ciphertext1, ciphertext3);
6636 ASSERT_NE(ciphertext2, ciphertext3);
6637}
6638
6639/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006640 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6641 *
6642 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6643 */
6644TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6645 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6646 .Authorization(TAG_NO_AUTH_REQUIRED)
6647 .AesEncryptionKey(128)
6648 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6649 .Padding(PaddingMode::NONE)
6650 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6651
6652 string aad = "foobar";
6653 string message = "123456789012345678901234567890123456";
6654
6655 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6656 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6657 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6658
6659 ASSERT_NE(ciphertext1, ciphertext2);
6660 ASSERT_NE(ciphertext1, ciphertext3);
6661 ASSERT_NE(ciphertext2, ciphertext3);
6662}
6663
6664/*
Selene Huang31ab4042020-04-29 04:22:39 -07006665 * EncryptionOperationsTest.AesGcmTooShortTag
6666 *
6667 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6668 */
6669TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6670 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6671 .Authorization(TAG_NO_AUTH_REQUIRED)
6672 .AesEncryptionKey(128)
6673 .BlockMode(BlockMode::GCM)
6674 .Padding(PaddingMode::NONE)
6675 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6676 string message = "123456789012345678901234567890123456";
6677 auto params = AuthorizationSetBuilder()
6678 .BlockMode(BlockMode::GCM)
6679 .Padding(PaddingMode::NONE)
6680 .Authorization(TAG_MAC_LENGTH, 96);
6681
6682 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6683}
6684
6685/*
6686 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6687 *
6688 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6689 */
6690TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6691 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6692 .Authorization(TAG_NO_AUTH_REQUIRED)
6693 .AesEncryptionKey(128)
6694 .BlockMode(BlockMode::GCM)
6695 .Padding(PaddingMode::NONE)
6696 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6697 string aad = "foobar";
6698 string message = "123456789012345678901234567890123456";
6699 auto params = AuthorizationSetBuilder()
6700 .BlockMode(BlockMode::GCM)
6701 .Padding(PaddingMode::NONE)
6702 .Authorization(TAG_MAC_LENGTH, 128);
6703
Selene Huang31ab4042020-04-29 04:22:39 -07006704 // Encrypt
6705 AuthorizationSet begin_out_params;
6706 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6707 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006708 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006709
6710 AuthorizationSet finish_out_params;
6711 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006712 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6713 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006714
6715 params = AuthorizationSetBuilder()
6716 .Authorizations(begin_out_params)
6717 .BlockMode(BlockMode::GCM)
6718 .Padding(PaddingMode::NONE)
6719 .Authorization(TAG_MAC_LENGTH, 96);
6720
6721 // Decrypt.
6722 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6723}
6724
6725/*
6726 * EncryptionOperationsTest.AesGcmCorruptKey
6727 *
6728 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6729 */
6730TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6731 const uint8_t nonce_bytes[] = {
6732 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6733 };
6734 string nonce = make_string(nonce_bytes);
6735 const uint8_t ciphertext_bytes[] = {
6736 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6737 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6738 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6739 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6740 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6741 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6742 };
6743 string ciphertext = make_string(ciphertext_bytes);
6744
6745 auto params = AuthorizationSetBuilder()
6746 .BlockMode(BlockMode::GCM)
6747 .Padding(PaddingMode::NONE)
6748 .Authorization(TAG_MAC_LENGTH, 128)
6749 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6750
6751 auto import_params = AuthorizationSetBuilder()
6752 .Authorization(TAG_NO_AUTH_REQUIRED)
6753 .AesEncryptionKey(128)
6754 .BlockMode(BlockMode::GCM)
6755 .Padding(PaddingMode::NONE)
6756 .Authorization(TAG_CALLER_NONCE)
6757 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6758
6759 // Import correct key and decrypt
6760 const uint8_t key_bytes[] = {
6761 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6762 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6763 };
6764 string key = make_string(key_bytes);
6765 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6766 string plaintext = DecryptMessage(ciphertext, params);
6767 CheckedDeleteKey();
6768
6769 // Corrupt key and attempt to decrypt
6770 key[0] = 0;
6771 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6772 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6773 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6774 CheckedDeleteKey();
6775}
6776
6777/*
6778 * EncryptionOperationsTest.AesGcmAadNoData
6779 *
6780 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6781 * encrypt.
6782 */
6783TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6784 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6785 .Authorization(TAG_NO_AUTH_REQUIRED)
6786 .AesEncryptionKey(128)
6787 .BlockMode(BlockMode::GCM)
6788 .Padding(PaddingMode::NONE)
6789 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6790
6791 string aad = "1234567890123456";
6792 auto params = AuthorizationSetBuilder()
6793 .BlockMode(BlockMode::GCM)
6794 .Padding(PaddingMode::NONE)
6795 .Authorization(TAG_MAC_LENGTH, 128);
6796
Selene Huang31ab4042020-04-29 04:22:39 -07006797 // Encrypt
6798 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006799 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006800 string ciphertext;
6801 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006802 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6803 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006804 EXPECT_TRUE(finish_out_params.empty());
6805
6806 // Grab nonce
6807 params.push_back(begin_out_params);
6808
6809 // Decrypt.
6810 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006811 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006812 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006813 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006814
6815 EXPECT_TRUE(finish_out_params.empty());
6816
6817 EXPECT_EQ("", plaintext);
6818}
6819
6820/*
6821 * EncryptionOperationsTest.AesGcmMultiPartAad
6822 *
6823 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6824 * chunks.
6825 */
6826TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6827 const size_t tag_bits = 128;
6828 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6829 .Authorization(TAG_NO_AUTH_REQUIRED)
6830 .AesEncryptionKey(128)
6831 .BlockMode(BlockMode::GCM)
6832 .Padding(PaddingMode::NONE)
6833 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6834
6835 string message = "123456789012345678901234567890123456";
6836 auto begin_params = AuthorizationSetBuilder()
6837 .BlockMode(BlockMode::GCM)
6838 .Padding(PaddingMode::NONE)
6839 .Authorization(TAG_MAC_LENGTH, tag_bits);
6840 AuthorizationSet begin_out_params;
6841
David Drysdale7fc26b92022-05-13 09:54:24 +01006842 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006843
6844 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006845 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6846 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006847 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006848 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6849 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006850
Selene Huang31ab4042020-04-29 04:22:39 -07006851 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006852 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006853
6854 // Grab nonce.
6855 begin_params.push_back(begin_out_params);
6856
6857 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01006858 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006859 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006860 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006861 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006862 EXPECT_EQ(message, plaintext);
6863}
6864
6865/*
6866 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6867 *
6868 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6869 */
6870TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6871 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6872 .Authorization(TAG_NO_AUTH_REQUIRED)
6873 .AesEncryptionKey(128)
6874 .BlockMode(BlockMode::GCM)
6875 .Padding(PaddingMode::NONE)
6876 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6877
6878 string message = "123456789012345678901234567890123456";
6879 auto begin_params = AuthorizationSetBuilder()
6880 .BlockMode(BlockMode::GCM)
6881 .Padding(PaddingMode::NONE)
6882 .Authorization(TAG_MAC_LENGTH, 128);
6883 AuthorizationSet begin_out_params;
6884
David Drysdale7fc26b92022-05-13 09:54:24 +01006885 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006886
Shawn Willden92d79c02021-02-19 07:31:55 -07006887 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006888 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006889 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6890 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006891
David Drysdaled2cc8c22021-04-15 13:29:45 +01006892 // The failure should have already cancelled the operation.
6893 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6894
Shawn Willden92d79c02021-02-19 07:31:55 -07006895 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006896}
6897
6898/*
6899 * EncryptionOperationsTest.AesGcmBadAad
6900 *
6901 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6902 */
6903TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6904 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6905 .Authorization(TAG_NO_AUTH_REQUIRED)
6906 .AesEncryptionKey(128)
6907 .BlockMode(BlockMode::GCM)
6908 .Padding(PaddingMode::NONE)
6909 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6910
6911 string message = "12345678901234567890123456789012";
6912 auto begin_params = AuthorizationSetBuilder()
6913 .BlockMode(BlockMode::GCM)
6914 .Padding(PaddingMode::NONE)
6915 .Authorization(TAG_MAC_LENGTH, 128);
6916
Selene Huang31ab4042020-04-29 04:22:39 -07006917 // Encrypt
6918 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006919 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006920 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006921 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006922 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006923
6924 // Grab nonce
6925 begin_params.push_back(begin_out_params);
6926
Selene Huang31ab4042020-04-29 04:22:39 -07006927 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006928 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006929 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006930 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006931 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006932}
6933
6934/*
6935 * EncryptionOperationsTest.AesGcmWrongNonce
6936 *
6937 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6938 */
6939TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6940 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6941 .Authorization(TAG_NO_AUTH_REQUIRED)
6942 .AesEncryptionKey(128)
6943 .BlockMode(BlockMode::GCM)
6944 .Padding(PaddingMode::NONE)
6945 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6946
6947 string message = "12345678901234567890123456789012";
6948 auto begin_params = AuthorizationSetBuilder()
6949 .BlockMode(BlockMode::GCM)
6950 .Padding(PaddingMode::NONE)
6951 .Authorization(TAG_MAC_LENGTH, 128);
6952
Selene Huang31ab4042020-04-29 04:22:39 -07006953 // Encrypt
6954 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006955 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006956 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006957 string ciphertext;
6958 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006959 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006960
6961 // Wrong nonce
6962 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6963
6964 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006965 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006966 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006967 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006968 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006969
6970 // With wrong nonce, should have gotten garbage plaintext (or none).
6971 EXPECT_NE(message, plaintext);
6972}
6973
6974/*
6975 * EncryptionOperationsTest.AesGcmCorruptTag
6976 *
6977 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6978 */
6979TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6980 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6981 .Authorization(TAG_NO_AUTH_REQUIRED)
6982 .AesEncryptionKey(128)
6983 .BlockMode(BlockMode::GCM)
6984 .Padding(PaddingMode::NONE)
6985 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6986
6987 string aad = "1234567890123456";
6988 string message = "123456789012345678901234567890123456";
6989
6990 auto params = AuthorizationSetBuilder()
6991 .BlockMode(BlockMode::GCM)
6992 .Padding(PaddingMode::NONE)
6993 .Authorization(TAG_MAC_LENGTH, 128);
6994
Selene Huang31ab4042020-04-29 04:22:39 -07006995 // Encrypt
6996 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006997 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006998 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006999 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007000 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007001
7002 // Corrupt tag
7003 ++(*ciphertext.rbegin());
7004
7005 // Grab nonce
7006 params.push_back(begin_out_params);
7007
7008 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007009 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007010 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007011 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007012 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007013}
7014
7015/*
7016 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
7017 *
7018 * Verifies that 3DES is basically functional.
7019 */
7020TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
7021 auto auths = AuthorizationSetBuilder()
7022 .TripleDesEncryptionKey(168)
7023 .BlockMode(BlockMode::ECB)
7024 .Authorization(TAG_NO_AUTH_REQUIRED)
7025 .Padding(PaddingMode::NONE);
7026
7027 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
7028 // Two-block message.
7029 string message = "1234567890123456";
7030 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7031 string ciphertext1 = EncryptMessage(message, inParams);
7032 EXPECT_EQ(message.size(), ciphertext1.size());
7033
7034 string ciphertext2 = EncryptMessage(string(message), inParams);
7035 EXPECT_EQ(message.size(), ciphertext2.size());
7036
7037 // ECB is deterministic.
7038 EXPECT_EQ(ciphertext1, ciphertext2);
7039
7040 string plaintext = DecryptMessage(ciphertext1, inParams);
7041 EXPECT_EQ(message, plaintext);
7042}
7043
7044/*
7045 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
7046 *
7047 * Verifies that CBC keys reject ECB usage.
7048 */
7049TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
7050 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7051 .TripleDesEncryptionKey(168)
7052 .BlockMode(BlockMode::CBC)
7053 .Authorization(TAG_NO_AUTH_REQUIRED)
7054 .Padding(PaddingMode::NONE)));
7055
7056 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7057 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7058}
7059
7060/*
7061 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
7062 *
7063 * Tests ECB mode with PKCS#7 padding, various message sizes.
7064 */
7065TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
7066 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7067 .TripleDesEncryptionKey(168)
7068 .BlockMode(BlockMode::ECB)
7069 .Authorization(TAG_NO_AUTH_REQUIRED)
7070 .Padding(PaddingMode::PKCS7)));
7071
7072 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007073 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007074 string message(i, 'a');
7075 auto inParams =
7076 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7077 string ciphertext = EncryptMessage(message, inParams);
7078 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7079 string plaintext = DecryptMessage(ciphertext, inParams);
7080 EXPECT_EQ(message, plaintext);
7081 }
7082}
7083
7084/*
7085 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
7086 *
7087 * Verifies that keys configured for no padding reject PKCS7 padding
7088 */
7089TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
7090 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7091 .TripleDesEncryptionKey(168)
7092 .BlockMode(BlockMode::ECB)
7093 .Authorization(TAG_NO_AUTH_REQUIRED)
7094 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00007095 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7096 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07007097}
7098
7099/*
7100 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
7101 *
7102 * Verifies that corrupted padding is detected.
7103 */
7104TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
7105 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7106 .TripleDesEncryptionKey(168)
7107 .BlockMode(BlockMode::ECB)
7108 .Authorization(TAG_NO_AUTH_REQUIRED)
7109 .Padding(PaddingMode::PKCS7)));
7110
7111 string message = "a";
7112 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7113 EXPECT_EQ(8U, ciphertext.size());
7114 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007115
7116 AuthorizationSetBuilder begin_params;
7117 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7118 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07007119
7120 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7121 ++ciphertext[ciphertext.size() / 2];
7122
David Drysdale7fc26b92022-05-13 09:54:24 +01007123 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007124 string plaintext;
7125 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7126 ErrorCode error = Finish(&plaintext);
7127 if (error == ErrorCode::INVALID_ARGUMENT) {
7128 // This is the expected error, we can exit the test now.
7129 return;
7130 } else {
7131 // Very small chance we got valid decryption, so try again.
7132 ASSERT_EQ(error, ErrorCode::OK);
7133 }
7134 }
7135 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007136}
7137
7138struct TripleDesTestVector {
7139 const char* name;
7140 const KeyPurpose purpose;
7141 const BlockMode block_mode;
7142 const PaddingMode padding_mode;
7143 const char* key;
7144 const char* iv;
7145 const char* input;
7146 const char* output;
7147};
7148
7149// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7150// of the NIST vectors are multiples of the block size.
7151static const TripleDesTestVector kTripleDesTestVectors[] = {
7152 {
7153 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7154 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7155 "", // IV
7156 "329d86bdf1bc5af4", // input
7157 "d946c2756d78633f", // output
7158 },
7159 {
7160 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7161 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7162 "", // IV
7163 "6b1540781b01ce1997adae102dbf3c5b", // input
7164 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7165 },
7166 {
7167 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7168 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7169 "", // IV
7170 "6daad94ce08acfe7", // input
7171 "660e7d32dcc90e79", // output
7172 },
7173 {
7174 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7175 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7176 "", // IV
7177 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7178 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7179 },
7180 {
7181 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7182 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7183 "43f791134c5647ba", // IV
7184 "dcc153cef81d6f24", // input
7185 "92538bd8af18d3ba", // output
7186 },
7187 {
7188 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7189 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7190 "c2e999cb6249023c", // IV
7191 "c689aee38a301bb316da75db36f110b5", // input
7192 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7193 },
7194 {
7195 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7196 PaddingMode::PKCS7,
7197 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7198 "c2e999cb6249023c", // IV
7199 "c689aee38a301bb316da75db36f110b500", // input
7200 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7201 },
7202 {
7203 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7204 PaddingMode::PKCS7,
7205 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7206 "c2e999cb6249023c", // IV
7207 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7208 "c689aee38a301bb316da75db36f110b500", // output
7209 },
7210 {
7211 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7212 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7213 "41746c7e442d3681", // IV
7214 "c53a7b0ec40600fe", // input
7215 "d4f00eb455de1034", // output
7216 },
7217 {
7218 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7219 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7220 "3982bc02c3727d45", // IV
7221 "6006f10adef52991fcc777a1238bbb65", // input
7222 "edae09288e9e3bc05746d872b48e3b29", // output
7223 },
7224};
7225
7226/*
7227 * EncryptionOperationsTest.TripleDesTestVector
7228 *
7229 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7230 */
7231TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7232 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7233 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7234 SCOPED_TRACE(test->name);
7235 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7236 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7237 hex2str(test->output));
7238 }
7239}
7240
7241/*
7242 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7243 *
7244 * Validates CBC mode functionality.
7245 */
7246TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7247 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7248 .TripleDesEncryptionKey(168)
7249 .BlockMode(BlockMode::CBC)
7250 .Authorization(TAG_NO_AUTH_REQUIRED)
7251 .Padding(PaddingMode::NONE)));
7252
7253 ASSERT_GT(key_blob_.size(), 0U);
7254
Brian J Murray734c8412022-01-13 14:55:30 -08007255 // Four-block message.
7256 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007257 vector<uint8_t> iv1;
7258 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7259 EXPECT_EQ(message.size(), ciphertext1.size());
7260
7261 vector<uint8_t> iv2;
7262 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7263 EXPECT_EQ(message.size(), ciphertext2.size());
7264
7265 // IVs should be random, so ciphertexts should differ.
7266 EXPECT_NE(iv1, iv2);
7267 EXPECT_NE(ciphertext1, ciphertext2);
7268
7269 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7270 EXPECT_EQ(message, plaintext);
7271}
7272
7273/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007274 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7275 *
7276 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7277 */
7278TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7279 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7280 .TripleDesEncryptionKey(168)
7281 .BlockMode(BlockMode::CBC)
7282 .Authorization(TAG_NO_AUTH_REQUIRED)
7283 .Authorization(TAG_CALLER_NONCE)
7284 .Padding(PaddingMode::NONE)));
7285 auto params = AuthorizationSetBuilder()
7286 .BlockMode(BlockMode::CBC)
7287 .Padding(PaddingMode::NONE)
7288 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7289 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7290}
7291
7292/*
Selene Huang31ab4042020-04-29 04:22:39 -07007293 * EncryptionOperationsTest.TripleDesCallerIv
7294 *
7295 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7296 */
7297TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7298 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7299 .TripleDesEncryptionKey(168)
7300 .BlockMode(BlockMode::CBC)
7301 .Authorization(TAG_NO_AUTH_REQUIRED)
7302 .Authorization(TAG_CALLER_NONCE)
7303 .Padding(PaddingMode::NONE)));
7304 string message = "1234567890123456";
7305 vector<uint8_t> iv;
7306 // Don't specify IV, should get a random one.
7307 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7308 EXPECT_EQ(message.size(), ciphertext1.size());
7309 EXPECT_EQ(8U, iv.size());
7310
7311 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7312 EXPECT_EQ(message, plaintext);
7313
7314 // Now specify an IV, should also work.
7315 iv = AidlBuf("abcdefgh");
7316 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7317
7318 // Decrypt with correct IV.
7319 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7320 EXPECT_EQ(message, plaintext);
7321
7322 // Now try with wrong IV.
7323 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7324 EXPECT_NE(message, plaintext);
7325}
7326
7327/*
7328 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7329 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007330 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007331 */
7332TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7333 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7334 .TripleDesEncryptionKey(168)
7335 .BlockMode(BlockMode::CBC)
7336 .Authorization(TAG_NO_AUTH_REQUIRED)
7337 .Padding(PaddingMode::NONE)));
7338
7339 string message = "12345678901234567890123456789012";
7340 vector<uint8_t> iv;
7341 // Don't specify nonce, should get a random one.
7342 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7343 EXPECT_EQ(message.size(), ciphertext1.size());
7344 EXPECT_EQ(8U, iv.size());
7345
7346 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7347 EXPECT_EQ(message, plaintext);
7348
7349 // Now specify a nonce, should fail.
7350 auto input_params = AuthorizationSetBuilder()
7351 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7352 .BlockMode(BlockMode::CBC)
7353 .Padding(PaddingMode::NONE);
7354 AuthorizationSet output_params;
7355 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7356 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7357}
7358
7359/*
7360 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7361 *
7362 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7363 */
7364TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7365 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7366 .TripleDesEncryptionKey(168)
7367 .BlockMode(BlockMode::ECB)
7368 .Authorization(TAG_NO_AUTH_REQUIRED)
7369 .Padding(PaddingMode::NONE)));
7370 // Two-block message.
7371 string message = "1234567890123456";
7372 auto begin_params =
7373 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7374 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7375}
7376
7377/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007378 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007379 *
7380 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7381 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007382TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7383 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007384 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007385 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7386 .TripleDesEncryptionKey(168)
7387 .BlockMode(blockMode)
7388 .Authorization(TAG_NO_AUTH_REQUIRED)
7389 .Padding(PaddingMode::NONE)));
7390 // Message is slightly shorter than two blocks.
7391 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007392
David Drysdaled2cc8c22021-04-15 13:29:45 +01007393 auto begin_params =
7394 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7395 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007396 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007397 string ciphertext;
7398 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7399
7400 CheckedDeleteKey();
7401 }
Selene Huang31ab4042020-04-29 04:22:39 -07007402}
7403
7404/*
7405 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7406 *
7407 * Verifies that PKCS7 padding works correctly in CBC mode.
7408 */
7409TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7410 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7411 .TripleDesEncryptionKey(168)
7412 .BlockMode(BlockMode::CBC)
7413 .Authorization(TAG_NO_AUTH_REQUIRED)
7414 .Padding(PaddingMode::PKCS7)));
7415
7416 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007417 for (size_t i = 0; i <= 32; i++) {
7418 SCOPED_TRACE(testing::Message() << "i = " << i);
7419 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7420 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007421 vector<uint8_t> iv;
7422 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7423 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7424 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7425 EXPECT_EQ(message, plaintext);
7426 }
7427}
7428
7429/*
7430 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7431 *
7432 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7433 */
7434TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7435 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7436 .TripleDesEncryptionKey(168)
7437 .BlockMode(BlockMode::CBC)
7438 .Authorization(TAG_NO_AUTH_REQUIRED)
7439 .Padding(PaddingMode::NONE)));
7440
7441 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007442 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007443 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007444 auto begin_params =
7445 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7446 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7447 }
7448}
7449
7450/*
7451 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7452 *
7453 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7454 */
7455TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7456 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7457 .TripleDesEncryptionKey(168)
7458 .BlockMode(BlockMode::CBC)
7459 .Authorization(TAG_NO_AUTH_REQUIRED)
7460 .Padding(PaddingMode::PKCS7)));
7461
7462 string message = "a";
7463 vector<uint8_t> iv;
7464 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7465 EXPECT_EQ(8U, ciphertext.size());
7466 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007467
7468 auto begin_params = AuthorizationSetBuilder()
7469 .BlockMode(BlockMode::CBC)
7470 .Padding(PaddingMode::PKCS7)
7471 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007472
7473 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007474 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007475 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007476 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007477 string plaintext;
7478 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7479 ErrorCode error = Finish(&plaintext);
7480 if (error == ErrorCode::INVALID_ARGUMENT) {
7481 // This is the expected error, we can exit the test now.
7482 return;
7483 } else {
7484 // Very small chance we got valid decryption, so try again.
7485 ASSERT_EQ(error, ErrorCode::OK);
7486 }
7487 }
7488 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007489}
7490
7491/*
7492 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7493 *
7494 * Verifies that 3DES CBC works with many different input sizes.
7495 */
7496TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7497 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7498 .TripleDesEncryptionKey(168)
7499 .BlockMode(BlockMode::CBC)
7500 .Authorization(TAG_NO_AUTH_REQUIRED)
7501 .Padding(PaddingMode::NONE)));
7502
7503 int increment = 7;
7504 string message(240, 'a');
7505 AuthorizationSet input_params =
7506 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7507 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007508 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007509
7510 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007511 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007512 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007513 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7514 EXPECT_EQ(message.size(), ciphertext.size());
7515
7516 // Move TAG_NONCE into input_params
7517 input_params = output_params;
7518 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7519 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7520 output_params.Clear();
7521
David Drysdale7fc26b92022-05-13 09:54:24 +01007522 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007523 string plaintext;
7524 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007525 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007526 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7527 EXPECT_EQ(ciphertext.size(), plaintext.size());
7528 EXPECT_EQ(message, plaintext);
7529}
7530
7531INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7532
7533typedef KeyMintAidlTestBase MaxOperationsTest;
7534
7535/*
7536 * MaxOperationsTest.TestLimitAes
7537 *
7538 * Verifies that the max uses per boot tag works correctly with AES keys.
7539 */
7540TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007541 if (SecLevel() == SecurityLevel::STRONGBOX) {
7542 GTEST_SKIP() << "Test not applicable to StrongBox device";
7543 }
Selene Huang31ab4042020-04-29 04:22:39 -07007544
7545 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7546 .Authorization(TAG_NO_AUTH_REQUIRED)
7547 .AesEncryptionKey(128)
7548 .EcbMode()
7549 .Padding(PaddingMode::NONE)
7550 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7551
7552 string message = "1234567890123456";
7553
7554 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7555
7556 EncryptMessage(message, params);
7557 EncryptMessage(message, params);
7558 EncryptMessage(message, params);
7559
7560 // Fourth time should fail.
7561 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7562}
7563
7564/*
Qi Wud22ec842020-11-26 13:27:53 +08007565 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007566 *
7567 * Verifies that the max uses per boot tag works correctly with RSA keys.
7568 */
7569TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007570 if (SecLevel() == SecurityLevel::STRONGBOX) {
7571 GTEST_SKIP() << "Test not applicable to StrongBox device";
7572 }
Selene Huang31ab4042020-04-29 04:22:39 -07007573
7574 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7575 .Authorization(TAG_NO_AUTH_REQUIRED)
7576 .RsaSigningKey(1024, 65537)
7577 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007578 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7579 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007580
7581 string message = "1234567890123456";
7582
7583 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7584
7585 SignMessage(message, params);
7586 SignMessage(message, params);
7587 SignMessage(message, params);
7588
7589 // Fourth time should fail.
7590 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7591}
7592
7593INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7594
Qi Wud22ec842020-11-26 13:27:53 +08007595typedef KeyMintAidlTestBase UsageCountLimitTest;
7596
7597/*
Qi Wubeefae42021-01-28 23:16:37 +08007598 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007599 *
Qi Wubeefae42021-01-28 23:16:37 +08007600 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007601 */
Qi Wubeefae42021-01-28 23:16:37 +08007602TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007603 if (SecLevel() == SecurityLevel::STRONGBOX) {
7604 GTEST_SKIP() << "Test not applicable to StrongBox device";
7605 }
Qi Wud22ec842020-11-26 13:27:53 +08007606
7607 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7608 .Authorization(TAG_NO_AUTH_REQUIRED)
7609 .AesEncryptionKey(128)
7610 .EcbMode()
7611 .Padding(PaddingMode::NONE)
7612 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7613
7614 // Check the usage count limit tag appears in the authorizations.
7615 AuthorizationSet auths;
7616 for (auto& entry : key_characteristics_) {
7617 auths.push_back(AuthorizationSet(entry.authorizations));
7618 }
7619 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7620 << "key usage count limit " << 1U << " missing";
7621
7622 string message = "1234567890123456";
7623 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7624
Qi Wubeefae42021-01-28 23:16:37 +08007625 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7626 AuthorizationSet keystore_auths =
7627 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7628
Qi Wud22ec842020-11-26 13:27:53 +08007629 // First usage of AES key should work.
7630 EncryptMessage(message, params);
7631
Qi Wud22ec842020-11-26 13:27:53 +08007632 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7633 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7634 // must be invalidated from secure storage (such as RPMB partition).
7635 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7636 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007637 // Usage count limit tag is enforced by keystore, keymint does nothing.
7638 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007639 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007640 }
7641}
7642
7643/*
Qi Wubeefae42021-01-28 23:16:37 +08007644 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007645 *
Qi Wubeefae42021-01-28 23:16:37 +08007646 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007647 */
Qi Wubeefae42021-01-28 23:16:37 +08007648TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007649 if (SecLevel() == SecurityLevel::STRONGBOX) {
7650 GTEST_SKIP() << "Test not applicable to StrongBox device";
7651 }
Qi Wubeefae42021-01-28 23:16:37 +08007652
7653 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7654 .Authorization(TAG_NO_AUTH_REQUIRED)
7655 .AesEncryptionKey(128)
7656 .EcbMode()
7657 .Padding(PaddingMode::NONE)
7658 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7659
7660 // Check the usage count limit tag appears in the authorizations.
7661 AuthorizationSet auths;
7662 for (auto& entry : key_characteristics_) {
7663 auths.push_back(AuthorizationSet(entry.authorizations));
7664 }
7665 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7666 << "key usage count limit " << 3U << " missing";
7667
7668 string message = "1234567890123456";
7669 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7670
7671 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7672 AuthorizationSet keystore_auths =
7673 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7674
7675 EncryptMessage(message, params);
7676 EncryptMessage(message, params);
7677 EncryptMessage(message, params);
7678
7679 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7680 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7681 // must be invalidated from secure storage (such as RPMB partition).
7682 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7683 } else {
7684 // Usage count limit tag is enforced by keystore, keymint does nothing.
7685 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007686 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007687 }
7688}
7689
7690/*
7691 * UsageCountLimitTest.TestSingleUseRsa
7692 *
7693 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7694 */
7695TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007696 if (SecLevel() == SecurityLevel::STRONGBOX) {
7697 GTEST_SKIP() << "Test not applicable to StrongBox device";
7698 }
Qi Wud22ec842020-11-26 13:27:53 +08007699
7700 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7701 .Authorization(TAG_NO_AUTH_REQUIRED)
7702 .RsaSigningKey(1024, 65537)
7703 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007704 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7705 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007706
7707 // Check the usage count limit tag appears in the authorizations.
7708 AuthorizationSet auths;
7709 for (auto& entry : key_characteristics_) {
7710 auths.push_back(AuthorizationSet(entry.authorizations));
7711 }
7712 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7713 << "key usage count limit " << 1U << " missing";
7714
7715 string message = "1234567890123456";
7716 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7717
Qi Wubeefae42021-01-28 23:16:37 +08007718 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7719 AuthorizationSet keystore_auths =
7720 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7721
Qi Wud22ec842020-11-26 13:27:53 +08007722 // First usage of RSA key should work.
7723 SignMessage(message, params);
7724
Qi Wud22ec842020-11-26 13:27:53 +08007725 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7726 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7727 // must be invalidated from secure storage (such as RPMB partition).
7728 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7729 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007730 // Usage count limit tag is enforced by keystore, keymint does nothing.
7731 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007732 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007733 }
7734}
7735
7736/*
7737 * UsageCountLimitTest.TestLimitUseRsa
7738 *
7739 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7740 */
7741TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007742 if (SecLevel() == SecurityLevel::STRONGBOX) {
7743 GTEST_SKIP() << "Test not applicable to StrongBox device";
7744 }
Qi Wubeefae42021-01-28 23:16:37 +08007745
7746 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7747 .Authorization(TAG_NO_AUTH_REQUIRED)
7748 .RsaSigningKey(1024, 65537)
7749 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007750 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7751 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007752
7753 // Check the usage count limit tag appears in the authorizations.
7754 AuthorizationSet auths;
7755 for (auto& entry : key_characteristics_) {
7756 auths.push_back(AuthorizationSet(entry.authorizations));
7757 }
7758 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7759 << "key usage count limit " << 3U << " missing";
7760
7761 string message = "1234567890123456";
7762 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7763
7764 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7765 AuthorizationSet keystore_auths =
7766 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7767
7768 SignMessage(message, params);
7769 SignMessage(message, params);
7770 SignMessage(message, params);
7771
7772 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7773 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7774 // must be invalidated from secure storage (such as RPMB partition).
7775 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7776 } else {
7777 // Usage count limit tag is enforced by keystore, keymint does nothing.
7778 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007779 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007780 }
7781}
7782
Qi Wu8e727f72021-02-11 02:49:33 +08007783/*
7784 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7785 *
7786 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7787 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7788 * in hardware.
7789 */
7790TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01007791 if (SecLevel() == SecurityLevel::STRONGBOX) {
7792 GTEST_SKIP() << "Test not applicable to StrongBox device";
7793 }
Qi Wu8e727f72021-02-11 02:49:33 +08007794
7795 auto error = GenerateKey(AuthorizationSetBuilder()
7796 .RsaSigningKey(2048, 65537)
7797 .Digest(Digest::NONE)
7798 .Padding(PaddingMode::NONE)
7799 .Authorization(TAG_NO_AUTH_REQUIRED)
7800 .Authorization(TAG_ROLLBACK_RESISTANCE)
7801 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007802 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7803 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007804 }
David Drysdale513bf122021-10-06 11:53:13 +01007805
7806 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7807 ASSERT_EQ(ErrorCode::OK, error);
7808 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7809 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7810 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7811
7812 // The KeyMint should also enforce single use key in hardware when it supports rollback
7813 // resistance.
7814 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7815 .Authorization(TAG_NO_AUTH_REQUIRED)
7816 .RsaSigningKey(1024, 65537)
7817 .NoDigestOrPadding()
7818 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7819 .SetDefaultValidity()));
7820
7821 // Check the usage count limit tag appears in the hardware authorizations.
7822 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7823 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7824 << "key usage count limit " << 1U << " missing";
7825
7826 string message = "1234567890123456";
7827 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7828
7829 // First usage of RSA key should work.
7830 SignMessage(message, params);
7831
7832 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7833 // must be invalidated from secure storage (such as RPMB partition).
7834 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007835}
7836
Qi Wud22ec842020-11-26 13:27:53 +08007837INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7838
David Drysdale7de9feb2021-03-05 14:56:19 +00007839typedef KeyMintAidlTestBase GetHardwareInfoTest;
7840
7841TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7842 // Retrieving hardware info should give the same result each time.
7843 KeyMintHardwareInfo info;
7844 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7845 KeyMintHardwareInfo info2;
7846 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7847 EXPECT_EQ(info, info2);
7848}
7849
7850INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7851
Selene Huang31ab4042020-04-29 04:22:39 -07007852typedef KeyMintAidlTestBase AddEntropyTest;
7853
7854/*
7855 * AddEntropyTest.AddEntropy
7856 *
7857 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7858 * is actually added.
7859 */
7860TEST_P(AddEntropyTest, AddEntropy) {
7861 string data = "foo";
7862 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7863}
7864
7865/*
7866 * AddEntropyTest.AddEmptyEntropy
7867 *
7868 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7869 */
7870TEST_P(AddEntropyTest, AddEmptyEntropy) {
7871 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7872}
7873
7874/*
7875 * AddEntropyTest.AddLargeEntropy
7876 *
7877 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7878 */
7879TEST_P(AddEntropyTest, AddLargeEntropy) {
7880 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7881}
7882
David Drysdalebb3d85e2021-04-13 11:15:51 +01007883/*
7884 * AddEntropyTest.AddTooLargeEntropy
7885 *
7886 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7887 */
7888TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7889 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7890 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7891}
7892
Selene Huang31ab4042020-04-29 04:22:39 -07007893INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7894
Selene Huang31ab4042020-04-29 04:22:39 -07007895typedef KeyMintAidlTestBase KeyDeletionTest;
7896
7897/**
7898 * KeyDeletionTest.DeleteKey
7899 *
7900 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7901 * valid key blob.
7902 */
7903TEST_P(KeyDeletionTest, DeleteKey) {
7904 auto error = GenerateKey(AuthorizationSetBuilder()
7905 .RsaSigningKey(2048, 65537)
7906 .Digest(Digest::NONE)
7907 .Padding(PaddingMode::NONE)
7908 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007909 .Authorization(TAG_ROLLBACK_RESISTANCE)
7910 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007911 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7912 GTEST_SKIP() << "Rollback resistance not supported";
7913 }
Selene Huang31ab4042020-04-29 04:22:39 -07007914
7915 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007916 ASSERT_EQ(ErrorCode::OK, error);
7917 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7918 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007919
David Drysdale513bf122021-10-06 11:53:13 +01007920 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007921
David Drysdale513bf122021-10-06 11:53:13 +01007922 string message = "12345678901234567890123456789012";
7923 AuthorizationSet begin_out_params;
7924 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7925 Begin(KeyPurpose::SIGN, key_blob_,
7926 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7927 &begin_out_params));
7928 AbortIfNeeded();
7929 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007930}
7931
7932/**
7933 * KeyDeletionTest.DeleteInvalidKey
7934 *
7935 * This test checks that the HAL excepts invalid key blobs..
7936 */
7937TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7938 // Generate key just to check if rollback protection is implemented
7939 auto error = GenerateKey(AuthorizationSetBuilder()
7940 .RsaSigningKey(2048, 65537)
7941 .Digest(Digest::NONE)
7942 .Padding(PaddingMode::NONE)
7943 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007944 .Authorization(TAG_ROLLBACK_RESISTANCE)
7945 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007946 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7947 GTEST_SKIP() << "Rollback resistance not supported";
7948 }
Selene Huang31ab4042020-04-29 04:22:39 -07007949
7950 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007951 ASSERT_EQ(ErrorCode::OK, error);
7952 AuthorizationSet enforced(SecLevelAuthorizations());
7953 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007954
David Drysdale513bf122021-10-06 11:53:13 +01007955 // Delete the key we don't care about the result at this point.
7956 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007957
David Drysdale513bf122021-10-06 11:53:13 +01007958 // Now create an invalid key blob and delete it.
7959 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007960
David Drysdale513bf122021-10-06 11:53:13 +01007961 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007962}
7963
7964/**
7965 * KeyDeletionTest.DeleteAllKeys
7966 *
7967 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7968 *
7969 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7970 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7971 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7972 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7973 * credentials stored in Keystore/Keymint.
7974 */
7975TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007976 if (!arm_deleteAllKeys) {
7977 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7978 return;
7979 }
Selene Huang31ab4042020-04-29 04:22:39 -07007980 auto error = GenerateKey(AuthorizationSetBuilder()
7981 .RsaSigningKey(2048, 65537)
7982 .Digest(Digest::NONE)
7983 .Padding(PaddingMode::NONE)
7984 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007985 .Authorization(TAG_ROLLBACK_RESISTANCE)
7986 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007987 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7988 GTEST_SKIP() << "Rollback resistance not supported";
7989 }
Selene Huang31ab4042020-04-29 04:22:39 -07007990
7991 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007992 ASSERT_EQ(ErrorCode::OK, error);
7993 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7994 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007995
David Drysdale513bf122021-10-06 11:53:13 +01007996 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007997
David Drysdale513bf122021-10-06 11:53:13 +01007998 string message = "12345678901234567890123456789012";
7999 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07008000
David Drysdale513bf122021-10-06 11:53:13 +01008001 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8002 Begin(KeyPurpose::SIGN, key_blob_,
8003 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8004 &begin_out_params));
8005 AbortIfNeeded();
8006 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008007}
8008
8009INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
8010
David Drysdaled2cc8c22021-04-15 13:29:45 +01008011typedef KeyMintAidlTestBase KeyUpgradeTest;
8012
8013/**
8014 * KeyUpgradeTest.UpgradeInvalidKey
8015 *
8016 * This test checks that the HAL excepts invalid key blobs..
8017 */
8018TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
8019 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
8020
8021 std::vector<uint8_t> new_blob;
8022 Status result = keymint_->upgradeKey(key_blob,
8023 AuthorizationSetBuilder()
8024 .Authorization(TAG_APPLICATION_ID, "clientid")
8025 .Authorization(TAG_APPLICATION_DATA, "appdata")
8026 .vector_data(),
8027 &new_blob);
8028 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
8029}
8030
8031INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
8032
Selene Huang31ab4042020-04-29 04:22:39 -07008033using UpgradeKeyTest = KeyMintAidlTestBase;
8034
8035/*
8036 * UpgradeKeyTest.UpgradeKey
8037 *
8038 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
8039 */
8040TEST_P(UpgradeKeyTest, UpgradeKey) {
8041 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8042 .AesEncryptionKey(128)
8043 .Padding(PaddingMode::NONE)
8044 .Authorization(TAG_NO_AUTH_REQUIRED)));
8045
8046 auto result = UpgradeKey(key_blob_);
8047
8048 // Key doesn't need upgrading. Should get okay, but no new key blob.
8049 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
8050}
8051
8052INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
8053
8054using ClearOperationsTest = KeyMintAidlTestBase;
8055
8056/*
8057 * ClearSlotsTest.TooManyOperations
8058 *
8059 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
8060 * operations are started without being finished or aborted. Also verifies
8061 * that aborting the operations clears the operations.
8062 *
8063 */
8064TEST_P(ClearOperationsTest, TooManyOperations) {
8065 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8066 .Authorization(TAG_NO_AUTH_REQUIRED)
8067 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08008068 .Padding(PaddingMode::NONE)
8069 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07008070
8071 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
8072 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08008073 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07008074 AuthorizationSet out_params;
8075 ErrorCode result;
8076 size_t i;
8077
8078 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00008079 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07008080 if (ErrorCode::OK != result) {
8081 break;
8082 }
8083 }
8084 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
8085 // Try again just in case there's a weird overflow bug
8086 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00008087 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008088 for (size_t j = 0; j < i; j++) {
8089 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
8090 << "Aboort failed for i = " << j << std::endl;
8091 }
David Drysdale7fc26b92022-05-13 09:54:24 +01008092 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008093 AbortIfNeeded();
8094}
8095
8096INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
8097
8098typedef KeyMintAidlTestBase TransportLimitTest;
8099
8100/*
David Drysdale7de9feb2021-03-05 14:56:19 +00008101 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07008102 *
8103 * Verifies that passing input data to finish succeeds as expected.
8104 */
8105TEST_P(TransportLimitTest, LargeFinishInput) {
8106 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8107 .Authorization(TAG_NO_AUTH_REQUIRED)
8108 .AesEncryptionKey(128)
8109 .BlockMode(BlockMode::ECB)
8110 .Padding(PaddingMode::NONE)));
8111
8112 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008113 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07008114 auto cipher_params =
8115 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8116
8117 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01008118 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008119
8120 string plain_message = std::string(1 << msg_size, 'x');
8121 string encrypted_message;
8122 auto rc = Finish(plain_message, &encrypted_message);
8123
8124 EXPECT_EQ(ErrorCode::OK, rc);
8125 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8126 << "Encrypt finish returned OK, but did not consume all of the given input";
8127 cipher_params.push_back(out_params);
8128
David Drysdale7fc26b92022-05-13 09:54:24 +01008129 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008130
8131 string decrypted_message;
8132 rc = Finish(encrypted_message, &decrypted_message);
8133 EXPECT_EQ(ErrorCode::OK, rc);
8134 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8135 << "Decrypt finish returned OK, did not consume all of the given input";
8136 }
8137}
8138
8139INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8140
Seth Moored79a0ec2021-12-13 20:03:33 +00008141static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008142 switch (curve) {
8143 case EcCurve::P_224:
8144 return NID_secp224r1;
8145 case EcCurve::P_256:
8146 return NID_X9_62_prime256v1;
8147 case EcCurve::P_384:
8148 return NID_secp384r1;
8149 case EcCurve::P_521:
8150 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008151 case EcCurve::CURVE_25519:
8152 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008153 }
8154}
8155
David Drysdale42fe1892021-10-14 14:43:46 +01008156class KeyAgreementTest : public KeyMintAidlTestBase {
8157 protected:
8158 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8159 std::vector<uint8_t>* localPublicKey) {
8160 // Generate EC key locally (with access to private key material)
8161 if (localCurve == EcCurve::CURVE_25519) {
8162 uint8_t privKeyData[32];
8163 uint8_t pubKeyData[32];
8164 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008165 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8166 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8167 } else {
8168 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8169 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8170 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8171 ASSERT_NE(group, nullptr);
8172 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8173 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8174 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8175 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008176 }
David Drysdalea410b772022-05-09 16:44:13 +01008177
8178 // Get encoded form of the public part of the locally generated key...
8179 unsigned char* p = nullptr;
8180 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8181 ASSERT_GT(localPublicKeySize, 0);
8182 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8183 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8184 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008185 }
8186
8187 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8188 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008189 auto builder = AuthorizationSetBuilder()
8190 .Authorization(TAG_NO_AUTH_REQUIRED)
8191 .Authorization(TAG_EC_CURVE, curve)
8192 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8193 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8194 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8195 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8196 .SetDefaultValidity();
8197 ErrorCode result = GenerateKey(builder);
8198
8199 if (SecLevel() == SecurityLevel::STRONGBOX) {
8200 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8201 result = GenerateKeyWithSelfSignedAttestKey(
8202 AuthorizationSetBuilder()
8203 .EcdsaKey(EcCurve::P_256)
8204 .AttestKey()
8205 .SetDefaultValidity(), /* attest key params */
8206 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8207 }
8208 }
David Drysdale42fe1892021-10-14 14:43:46 +01008209 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8210 ASSERT_GT(cert_chain_.size(), 0);
8211 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8212 ASSERT_NE(kmKeyCert, nullptr);
8213 // Check that keyAgreement (bit 4) is set in KeyUsage
8214 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8215 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8216 ASSERT_NE(*kmPubKey, nullptr);
8217 if (dump_Attestations) {
8218 for (size_t n = 0; n < cert_chain_.size(); n++) {
8219 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8220 }
8221 }
8222 }
8223
8224 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8225 const std::vector<uint8_t>& localPublicKey) {
8226 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8227 string ZabFromKeyMintStr;
8228 ASSERT_EQ(ErrorCode::OK,
8229 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8230 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8231 vector<uint8_t> ZabFromTest;
8232
8233 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8234 size_t kmPubKeySize = 32;
8235 uint8_t kmPubKeyData[32];
8236 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8237 ASSERT_EQ(kmPubKeySize, 32);
8238
8239 uint8_t localPrivKeyData[32];
8240 size_t localPrivKeySize = 32;
8241 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8242 &localPrivKeySize));
8243 ASSERT_EQ(localPrivKeySize, 32);
8244
8245 uint8_t sharedKey[32];
8246 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8247 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8248 } else {
8249 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8250 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8251 ASSERT_NE(ctx, nullptr);
8252 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8253 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8254 size_t ZabFromTestLen = 0;
8255 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8256 ZabFromTest.resize(ZabFromTestLen);
8257 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8258 }
8259 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8260 }
8261};
8262
David Zeuthene0c40892021-01-08 12:54:11 -05008263/*
8264 * KeyAgreementTest.Ecdh
8265 *
David Drysdale42fe1892021-10-14 14:43:46 +01008266 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008267 */
8268TEST_P(KeyAgreementTest, Ecdh) {
8269 // Because it's possible to use this API with keys on different curves, we
8270 // check all N^2 combinations where N is the number of supported
8271 // curves.
8272 //
8273 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8274 // lot more curves we can be smart about things and just pick |otherCurve| so
8275 // it's not |curve| and that way we end up with only 2*N runs
8276 //
8277 for (auto curve : ValidCurves()) {
8278 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008279 SCOPED_TRACE(testing::Message()
8280 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8281
David Zeuthene0c40892021-01-08 12:54:11 -05008282 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008283 EVP_PKEY_Ptr localPrivKey;
8284 vector<uint8_t> localPublicKey;
8285 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008286
8287 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008288 EVP_PKEY_Ptr kmPubKey;
8289 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008290
8291 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8292 if (curve != localCurve) {
8293 // If the keys are using different curves KeyMint should fail with
8294 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008295 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008296 string ZabFromKeyMintStr;
8297 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008298 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008299 &ZabFromKeyMintStr));
8300
8301 } else {
8302 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008303 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008304 }
8305
8306 CheckedDeleteKey();
8307 }
8308 }
8309}
8310
David Drysdale42fe1892021-10-14 14:43:46 +01008311/*
8312 * KeyAgreementTest.EcdhCurve25519
8313 *
8314 * Verifies that ECDH works for curve25519. This is also covered by the general
8315 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8316 * KeyMint 1.0.
8317 */
8318TEST_P(KeyAgreementTest, EcdhCurve25519) {
8319 if (!Curve25519Supported()) {
8320 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8321 }
8322
8323 // Generate EC key in KeyMint (only access to public key material)
8324 EcCurve curve = EcCurve::CURVE_25519;
8325 EVP_PKEY_Ptr kmPubKey = nullptr;
8326 GenerateKeyMintEcKey(curve, &kmPubKey);
8327
8328 // Generate EC key on same curve locally (with access to private key material).
8329 EVP_PKEY_Ptr privKey;
8330 vector<uint8_t> encodedPublicKey;
8331 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8332
8333 // Agree on a key between local and KeyMint and check it.
8334 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8335
8336 CheckedDeleteKey();
8337}
8338
8339/*
8340 * KeyAgreementTest.EcdhCurve25519Imported
8341 *
8342 * Verifies that ECDH works for an imported curve25519 key.
8343 */
8344TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8345 if (!Curve25519Supported()) {
8346 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8347 }
8348
8349 // Import x25519 key into KeyMint.
8350 EcCurve curve = EcCurve::CURVE_25519;
8351 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8352 .Authorization(TAG_NO_AUTH_REQUIRED)
8353 .EcdsaKey(EcCurve::CURVE_25519)
8354 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8355 .SetDefaultValidity(),
8356 KeyFormat::PKCS8, x25519_pkcs8_key));
8357 ASSERT_GT(cert_chain_.size(), 0);
8358 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8359 ASSERT_NE(kmKeyCert, nullptr);
8360 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8361 ASSERT_NE(kmPubKey.get(), nullptr);
8362
8363 // Expect the import to emit corresponding public key data.
8364 size_t kmPubKeySize = 32;
8365 uint8_t kmPubKeyData[32];
8366 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8367 ASSERT_EQ(kmPubKeySize, 32);
8368 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8369 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8370
8371 // Generate EC key on same curve locally (with access to private key material).
8372 EVP_PKEY_Ptr privKey;
8373 vector<uint8_t> encodedPublicKey;
8374 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8375
8376 // Agree on a key between local and KeyMint and check it.
8377 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8378
8379 CheckedDeleteKey();
8380}
8381
8382/*
8383 * KeyAgreementTest.EcdhCurve25519InvalidSize
8384 *
8385 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8386 */
8387TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8388 if (!Curve25519Supported()) {
8389 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8390 }
8391
8392 // Generate EC key in KeyMint (only access to public key material)
8393 EcCurve curve = EcCurve::CURVE_25519;
8394 EVP_PKEY_Ptr kmPubKey = nullptr;
8395 GenerateKeyMintEcKey(curve, &kmPubKey);
8396
8397 // Generate EC key on same curve locally (with access to private key material).
8398 EVP_PKEY_Ptr privKey;
8399 vector<uint8_t> encodedPublicKey;
8400 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8401
8402 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8403 string ZabFromKeyMintStr;
8404 // Send in an incomplete public key.
8405 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8406 &ZabFromKeyMintStr));
8407
8408 CheckedDeleteKey();
8409}
8410
8411/*
8412 * KeyAgreementTest.EcdhCurve25519Mismatch
8413 *
8414 * Verifies that ECDH fails between curve25519 and other curves.
8415 */
8416TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8417 if (!Curve25519Supported()) {
8418 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8419 }
8420
8421 // Generate EC key in KeyMint (only access to public key material)
8422 EcCurve curve = EcCurve::CURVE_25519;
8423 EVP_PKEY_Ptr kmPubKey = nullptr;
8424 GenerateKeyMintEcKey(curve, &kmPubKey);
8425
8426 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008427 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008428 if (localCurve == curve) {
8429 continue;
8430 }
8431 // Generate EC key on a different curve locally (with access to private key material).
8432 EVP_PKEY_Ptr privKey;
8433 vector<uint8_t> encodedPublicKey;
8434 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8435
David Drysdale7fc26b92022-05-13 09:54:24 +01008436 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008437 string ZabFromKeyMintStr;
8438 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8439 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8440 &ZabFromKeyMintStr));
8441 }
8442
8443 CheckedDeleteKey();
8444}
8445
David Zeuthene0c40892021-01-08 12:54:11 -05008446INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8447
David Drysdaled2cc8c22021-04-15 13:29:45 +01008448using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8449
8450// This is a problematic test, as it can render the device under test permanently unusable.
8451// Re-enable and run at your own risk.
8452TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8453 auto result = DestroyAttestationIds();
8454 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8455}
8456
8457INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8458
Shawn Willdend659c7c2021-02-19 14:51:51 -07008459using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008460
David Drysdaledb0dcf52021-05-18 11:43:31 +01008461/*
8462 * EarlyBootKeyTest.CreateEarlyBootKeys
8463 *
8464 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8465 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008466TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008467 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008468 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8469 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8470
David Drysdaleadfe6112021-05-27 12:00:53 +01008471 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8472 ASSERT_GT(keyData.blob.size(), 0U);
8473 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8474 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8475 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008476 CheckedDeleteKey(&aesKeyData.blob);
8477 CheckedDeleteKey(&hmacKeyData.blob);
8478 CheckedDeleteKey(&rsaKeyData.blob);
8479 CheckedDeleteKey(&ecdsaKeyData.blob);
8480}
8481
David Drysdaledb0dcf52021-05-18 11:43:31 +01008482/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008483 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8484 *
8485 * Verifies that creating an early boot key with attestation succeeds.
8486 */
8487TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8488 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8489 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8490 builder->AttestationChallenge("challenge");
8491 builder->AttestationApplicationId("app_id");
8492 });
8493
8494 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008495 // Strongbox may not support factory attestation. Key creation might fail with
8496 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8497 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8498 continue;
8499 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008500 ASSERT_GT(keyData.blob.size(), 0U);
8501 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8502 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8503 }
8504 CheckedDeleteKey(&aesKeyData.blob);
8505 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00008506 if (rsaKeyData.blob.size() != 0U) {
8507 CheckedDeleteKey(&rsaKeyData.blob);
8508 }
8509 if (ecdsaKeyData.blob.size() != 0U) {
8510 CheckedDeleteKey(&ecdsaKeyData.blob);
8511 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008512}
8513
8514/*
8515 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008516 *
8517 * Verifies that using early boot keys at a later stage fails.
8518 */
8519TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8520 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8521 .Authorization(TAG_NO_AUTH_REQUIRED)
8522 .Authorization(TAG_EARLY_BOOT_ONLY)
8523 .HmacKey(128)
8524 .Digest(Digest::SHA_2_256)
8525 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8526 AuthorizationSet output_params;
8527 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8528 AuthorizationSetBuilder()
8529 .Digest(Digest::SHA_2_256)
8530 .Authorization(TAG_MAC_LENGTH, 256),
8531 &output_params));
8532}
8533
8534/*
8535 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8536 *
8537 * Verifies that importing early boot keys fails.
8538 */
8539TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8540 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8541 .Authorization(TAG_NO_AUTH_REQUIRED)
8542 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008543 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008544 .Digest(Digest::SHA_2_256)
8545 .SetDefaultValidity(),
8546 KeyFormat::PKCS8, ec_256_key));
8547}
8548
David Drysdaled2cc8c22021-04-15 13:29:45 +01008549// 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 +00008550// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8551// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8552// early boot, so you'll have to reboot between runs.
8553TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8554 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8555 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8556 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8557 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8558 EXPECT_TRUE(
8559 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8560 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8561 EXPECT_TRUE(
8562 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8563
8564 // Should be able to use keys, since early boot has not ended
8565 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8566 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8567 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8568 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8569
8570 // End early boot
8571 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8572 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8573
8574 // Should not be able to use already-created keys.
8575 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8576 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8577 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8578 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8579
8580 CheckedDeleteKey(&aesKeyData.blob);
8581 CheckedDeleteKey(&hmacKeyData.blob);
8582 CheckedDeleteKey(&rsaKeyData.blob);
8583 CheckedDeleteKey(&ecdsaKeyData.blob);
8584
8585 // Should not be able to create new keys
8586 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
8587 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
8588
8589 CheckedDeleteKey(&aesKeyData.blob);
8590 CheckedDeleteKey(&hmacKeyData.blob);
8591 CheckedDeleteKey(&rsaKeyData.blob);
8592 CheckedDeleteKey(&ecdsaKeyData.blob);
8593}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008594
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008595INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8596
Shawn Willdend659c7c2021-02-19 14:51:51 -07008597using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008598
8599// This may be a problematic test. It can't be run repeatedly without unlocking the device in
8600// between runs... and on most test devices there are no enrolled credentials so it can't be
8601// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8602// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8603// a manual test process, which includes unlocking between runs, which is why it's included here.
8604// Well, that and the fact that it's the only test we can do without also making calls into the
8605// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8606// implications might be, so that may or may not be a solution.
8607TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8608 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8609 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
8610
8611 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8612 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8613 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8614 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8615
8616 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008617 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008618 ASSERT_EQ(ErrorCode::OK, rc);
8619 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8620 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8621 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8622 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
8623
8624 CheckedDeleteKey(&aesKeyData.blob);
8625 CheckedDeleteKey(&hmacKeyData.blob);
8626 CheckedDeleteKey(&rsaKeyData.blob);
8627 CheckedDeleteKey(&ecdsaKeyData.blob);
8628}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008629
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008630INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8631
Shawn Willden22fb9c12022-06-02 14:04:33 -06008632using VsrRequirementTest = KeyMintAidlTestBase;
8633
8634TEST_P(VsrRequirementTest, Vsr13Test) {
8635 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008636 if (vsr_api_level < __ANDROID_API_T__) {
Shawn Willden22fb9c12022-06-02 14:04:33 -06008637 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8638 }
8639 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8640}
8641
Eran Messerib9346f52022-12-15 14:58:34 +00008642TEST_P(VsrRequirementTest, Vsr14Test) {
8643 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008644 if (vsr_api_level < __ANDROID_API_U__) {
Eran Messerib9346f52022-12-15 14:58:34 +00008645 GTEST_SKIP() << "Applies only to VSR API level 34, this device is: " << vsr_api_level;
8646 }
8647 EXPECT_GE(AidlVersion(), 3) << "VSR 14+ requires KeyMint version 3";
8648}
8649
Shawn Willden22fb9c12022-06-02 14:04:33 -06008650INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8651
Janis Danisevskis24c04702020-12-16 18:28:39 -08008652} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008653
8654int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008655 std::cout << "Testing ";
8656 auto halInstances =
8657 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8658 std::cout << "HAL instances:\n";
8659 for (auto& entry : halInstances) {
8660 std::cout << " " << entry << '\n';
8661 }
8662
Selene Huang31ab4042020-04-29 04:22:39 -07008663 ::testing::InitGoogleTest(&argc, argv);
8664 for (int i = 1; i < argc; ++i) {
8665 if (argv[i][0] == '-') {
8666 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008667 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8668 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008669 }
8670 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008671 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8672 dump_Attestations = true;
8673 } else {
8674 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008675 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008676 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8677 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8678 // be run in emulated environments that don't have the normal bootloader
8679 // interactions.
8680 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8681 }
David Drysdale9f5c0c52022-11-03 15:10:16 +00008682 if (std::string(argv[i]) == "--keyblob_dir") {
8683 if (i + 1 >= argc) {
8684 std::cerr << "Missing argument for --keyblob_dir\n";
8685 return 1;
8686 }
8687 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::keyblob_dir =
8688 std::string(argv[i + 1]);
8689 ++i;
8690 }
Selene Huang31ab4042020-04-29 04:22:39 -07008691 }
8692 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008693 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008694}