blob: ca18082c90ab6ea51532377ad66826dfa61dd35d [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
David Drysdale37af4b32021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Drysdale42fe1892021-10-14 14:43:46 +010025#include <openssl/curve25519.h>
David Zeuthene0c40892021-01-08 12:54:11 -050026#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070027#include <openssl/evp.h>
28#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050029#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070030
31#include <cutils/properties.h>
32
David Drysdale4dc01072021-04-01 12:17:35 +010033#include <android/binder_manager.h>
34
35#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080036#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070037
Shawn Willden08a7e432020-12-11 13:05:27 +000038#include <keymint_support/key_param_output.h>
39#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070040
41#include "KeyMintAidlTestBase.h"
42
Janis Danisevskis24c04702020-12-16 18:28:39 -080043using aidl::android::hardware::security::keymint::AuthorizationSet;
44using aidl::android::hardware::security::keymint::KeyCharacteristics;
45using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070046
Selene Huang31ab4042020-04-29 04:22:39 -070047namespace std {
48
Janis Danisevskis24c04702020-12-16 18:28:39 -080049using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070050
51template <>
52struct std::equal_to<KeyCharacteristics> {
53 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070054 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070055
Shawn Willden7f424372021-01-10 18:06:50 -070056 // this isn't very efficient. Oh, well.
57 AuthorizationSet a_auths(a.authorizations);
58 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070059
Shawn Willden7f424372021-01-10 18:06:50 -070060 a_auths.Sort();
61 b_auths.Sort();
62
63 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070064 }
65};
66
67} // namespace std
68
Janis Danisevskis24c04702020-12-16 18:28:39 -080069namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000070
Selene Huang31ab4042020-04-29 04:22:39 -070071namespace {
72
David Drysdalefeab5d92022-01-06 15:46:23 +000073// Maximum supported Ed25519 message size.
74const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
75
David Drysdaledbbbe2e2021-12-02 07:44:23 +000076// Whether to check that BOOT_PATCHLEVEL is populated.
77bool check_boot_pl = true;
78
Seth Moore7a55ae32021-06-23 14:28:11 -070079// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000080// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070081// is a small (roughly 1/256) chance that corrupting ciphertext still results
82// in valid PKCS7 padding.
83constexpr size_t kMaxPaddingCorruptionRetries = 8;
84
Selene Huang31ab4042020-04-29 04:22:39 -070085template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000086bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
87 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070088 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080089 if (auto p = authorizationValue(ttag, param)) {
90 return *p == expected_value;
91 }
92 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070093 });
94 return (it != set.end());
95}
96
97template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000098bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070099 auto it = std::find_if(set.begin(), set.end(),
100 [&](const KeyParameter& param) { return param.tag == tag; });
101 return (it != set.end());
102}
103
104constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
108 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
110 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
111 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
114 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
115 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
117 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
120
121string hex2str(string a) {
122 string b;
123 size_t num = a.size() / 2;
124 b.resize(num);
125 for (size_t i = 0; i < num; i++) {
126 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
127 }
128 return b;
129}
130
David Drysdaled2cc8c22021-04-15 13:29:45 +0100131string rsa_key = hex2str(
132 // RFC 5208 s5
133 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
134 "020100" // INTEGER length 1 value 0x00 (version)
135 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
136 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
137 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
138 "0500" // NULL (parameters)
139 // } end SEQUENCE (AlgorithmIdentifier)
140 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
141 // RFC 8017 A.1.2
142 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
143 "020100" // INTEGER length 1 value 0x00 (version)
144 "028181" // INTEGER length 0x81 value (modulus) ...
145 "00c6095409047d8634812d5a218176e4"
146 "5c41d60a75b13901f234226cffe77652"
147 "1c5a77b9e389417b71c0b6a44d13afe4"
148 "e4a2805d46c9da2935adb1ff0c1f24ea"
149 "06e62b20d776430a4d435157233c6f91"
150 "6783c30e310fcbd89b85c2d567711697"
151 "85ac12bca244abda72bfb19fc44d27c8"
152 "1e1d92de284f4061edfd99280745ea6d"
153 "25"
154 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
155 "028180" // INTEGER length 0x80 (privateExponent) value...
156 "1be0f04d9cae3718691f035338308e91"
157 "564b55899ffb5084d2460e6630257e05"
158 "b3ceab02972dfabcd6ce5f6ee2589eb6"
159 "7911ed0fac16e43a444b8c861e544a05"
160 "93365772f8baf6b22fc9e3c5f1024b06"
161 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
162 "ace7240290bef16c0b3f7f3cdd64ce3a"
163 "b5912cf6e32f39ab188358afcccd8081"
164 "0241" // INTEGER length 0x41 (prime1)
165 "00e4b49ef50f765d3b24dde01aceaaf1"
166 "30f2c76670a91a61ae08af497b4a82be"
167 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
168 "8c92bfab137fba2285227b83c342ff7c"
169 "55"
170 "0241" // INTEGER length 0x41 (prime2)
171 "00ddabb5839c4c7f6bf3d4183231f005"
172 "b31aa58affdda5c79e4cce217f6bc930"
173 "dbe563d480706c24e9ebfcab28a6cdef"
174 "d324b77e1bf7251b709092c24ff501fd"
175 "91"
176 "0240" // INTEGER length 0x40 (exponent1)
177 "23d4340eda3445d8cd26c14411da6fdc"
178 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
179 "842c1d280405bc2f6c1bea214a1d742a"
180 "b996b35b63a82a5e470fa88dbf823cdd"
181 "0240" // INTEGER length 0x40 (exponent2)
182 "1b7b57449ad30d1518249a5f56bb9829"
183 "4d4b6ac12ffc86940497a5a5837a6cf9"
184 "46262b494526d328c11e1126380fde04"
185 "c24f916dec250892db09a6d77cdba351"
186 "0240" // INTEGER length 0x40 (coefficient)
187 "7762cd8f4d050da56bd591adb515d24d"
188 "7ccd32cca0d05f866d583514bd7324d5"
189 "f33645e8ed8b4a1cb3cc4a1d67987399"
190 "f2a09f5b3fb68c88d5e5d90ac33492d6"
191 // } end SEQUENCE (PrivateKey)
192 // } end SEQUENCE (PrivateKeyInfo)
193);
Selene Huang31ab4042020-04-29 04:22:39 -0700194
Selene Huange5727e62021-04-13 22:41:20 -0700195/*
196 * DER-encoded PKCS#8 format RSA key. Generated using:
197 *
198 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
199 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100200string rsa_2048_key = hex2str(
201 // RFC 5208 s5
202 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
203 "020100" // INTEGER length 1 value 0x00 (version)
204 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
205 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
206 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
207 "0500" // NULL (parameters)
208 // } end SEQUENCE (AlgorithmIdentifier)
209 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
210 // RFC 8017 A.1.2
211 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
212 "020100" // INTEGER length 1 value 0x00 (version)
213 "02820101" // INTEGER length 0x101 value (modulus) ...
214 "00BEBC342B56D443B1299F9A6A7056E8"
215 "0A897E318476A5A18029E63B2ED739A6"
216 "1791D339F58DC763D9D14911F2EDEC38"
217 "3DEE11F6319B44510E7A3ECD9B79B973"
218 "82E49500ACF8117DC89CAF0E621F7775"
219 "6554A2FD4664BFE7AB8B59AB48340DBF"
220 "A27B93B5A81F6ECDEB02D0759307128D"
221 "F3E3BAD4055C8B840216DFAA5700670E"
222 "6C5126F0962FCB70FF308F25049164CC"
223 "F76CC2DA66A7DD9A81A714C2809D6918"
224 "6133D29D84568E892B6FFBF3199BDB14"
225 "383EE224407F190358F111A949552ABA"
226 "6714227D1BD7F6B20DD0CB88F9467B71"
227 "9339F33BFF35B3870B3F62204E4286B0"
228 "948EA348B524544B5F9838F29EE643B0"
229 "79EEF8A713B220D7806924CDF7295070"
230 "C5"
231 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
232 "02820100" // INTEGER length 0x100 (privateExponent) value...
233 "69F377F35F2F584EF075353CCD1CA997"
234 "38DB3DBC7C7FF35F9366CE176DFD1B13"
235 "5AB10030344ABF5FBECF1D4659FDEF1C"
236 "0FC430834BE1BE3911951377BB3D563A"
237 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
238 "2686C7B4B3C09A7B8354133E6F93F790"
239 "D59EAEB92E84C9A4339302CCE28FDF04"
240 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
241 "6AB706645BF074A4E4090D06FB163124"
242 "365FD5EE7A20D350E9958CC30D91326E"
243 "1B292E9EF5DB408EC42DAF737D201497"
244 "04D0A678A0FB5B5446863B099228A352"
245 "D604BA8091A164D01D5AB05397C71EAD"
246 "20BE2A08FC528FE442817809C787FEE4"
247 "AB97F97B9130D022153EDC6EB6CBE7B0"
248 "F8E3473F2E901209B5DB10F93604DB01"
249 "028181" // INTEGER length 0x81 (prime1)
250 "00E83C0998214941EA4F9293F1B77E2E"
251 "99E6CF305FAF358238E126124FEAF2EB"
252 "9724B2EA7B78E6032343821A80E55D1D"
253 "88FB12D220C3F41A56142FEC85796D19"
254 "17F1E8C774F142B67D3D6E7B7E6B4383"
255 "E94DB5929089DBB346D5BDAB40CC2D96"
256 "EE0409475E175C63BF78CFD744136740"
257 "838127EA723FF3FE7FA368C1311B4A4E"
258 "05"
259 "028181" // INTEGER length 0x81 (prime2)
260 "00D240FCC0F5D7715CDE21CB2DC86EA1"
261 "46132EA3B06F61FF2AF54BF38473F59D"
262 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
263 "B1B58C39F95E4798CCBB43E83D0119AC"
264 "F532F359CA743C85199F0286610E2009"
265 "97D7312917179AC9B67558773212EC96"
266 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
267 "94D94E066A0900B7B70E82A44FB30053"
268 "C1"
269 "028181" // INTEGER length 0x81 (exponent1)
270 "00AD15DA1CBD6A492B66851BA8C316D3"
271 "8AB700E2CFDDD926A658003513C54BAA"
272 "152B30021D667D20078F500F8AD3E7F3"
273 "945D74A891ED1A28EAD0FEEAEC8C14A8"
274 "E834CF46A13D1378C99D18940823CFDD"
275 "27EC5810D59339E0C34198AC638E09C8"
276 "7CBB1B634A9864AE9F4D5EB2D53514F6"
277 "7B4CAEC048C8AB849A02E397618F3271"
278 "35"
279 "028180" // INTEGER length 0x80 (exponent2)
280 "1FA2C1A5331880A92D8F3E281C617108"
281 "BF38244F16E352E69ED417C7153F9EC3"
282 "18F211839C643DCF8B4DD67CE2AC312E"
283 "95178D5D952F06B1BF779F4916924B70"
284 "F582A23F11304E02A5E7565AE22A35E7"
285 "4FECC8B6FDC93F92A1A37703E4CF0E63"
286 "783BD02EB716A7ECBBFA606B10B74D01"
287 "579522E7EF84D91FC522292108D902C1"
288 "028180" // INTEGER length 0x80 (coefficient)
289 "796FE3825F9DCC85DF22D58690065D93"
290 "898ACD65C087BEA8DA3A63BF4549B795"
291 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
292 "0D74F40DED8E1102C52152A31B6165F8"
293 "3A6722AECFCC35A493D7634664B888A0"
294 "8D3EB034F12EA28BFEE346E205D33482"
295 "7F778B16ED40872BD29FCB36536B6E93"
296 "FFB06778696B4A9D81BB0A9423E63DE5"
297 // } end SEQUENCE (PrivateKey)
298 // } end SEQUENCE (PrivateKeyInfo)
299);
Selene Huange5727e62021-04-13 22:41:20 -0700300
David Drysdaled2cc8c22021-04-15 13:29:45 +0100301string ec_256_key = hex2str(
302 // RFC 5208 s5
303 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
304 "020100" // INTEGER length 1 value 0 (version)
305 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
306 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
307 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
308 "0608" // OBJECT IDENTIFIER length 8 (param)
309 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
310 // } end SEQUENCE (AlgorithmIdentifier)
311 "046d" // OCTET STRING length 0x6d (privateKey) holding...
312 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
313 "020101" // INTEGER length 1 value 1 (version)
314 "0420" // OCTET STRING length 0x20 (privateKey)
315 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
316 "941eed09366bc03299986481f3a4d859"
317 "a144" // TAG [1] len 0x44 (publicKey) {
318 "03420004bf85d7720d07c25461683bc6"
319 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
320 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
321 "bcc41c6eb00083cf3376d11fd44949e0"
322 "b2183bfe"
323 // } end SEQUENCE (ECPrivateKey)
324 // } end SEQUENCE (PrivateKeyInfo)
325);
Selene Huang31ab4042020-04-29 04:22:39 -0700326
David Drysdaled2cc8c22021-04-15 13:29:45 +0100327string ec_521_key = hex2str(
328 // RFC 5208 s5
329 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
330 "020100" // INTEGER length 1 value 0 (version)
331 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
332 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
333 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
334 "0605" // OBJECT IDENTIFIER length 5 (param)
335 "2B81040023" // 1.3.132.0.35 (secp521r1)
336 // } end SEQUENCE (AlgorithmIdentifier)
337 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
338 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
339 "020101" // INTEGER length 1 value 1 (version)
340 "0442" // OCTET STRING length 0x42 (privateKey)
341 "0011458C586DB5DAA92AFAB03F4FE46A"
342 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
343 "9D18D7D08B5BCFA0E53C75B064AD51C4"
344 "49BAE0258D54B94B1E885DED08ED4FB2"
345 "5CE9"
346 "A18189" // TAG [1] len 0x89 (publicKey) {
347 "03818600040149EC11C6DF0FA122C6A9"
348 "AFD9754A4FA9513A627CA329E349535A"
349 "5629875A8ADFBE27DCB932C051986377"
350 "108D054C28C6F39B6F2C9AF81802F9F3"
351 "26B842FF2E5F3C00AB7635CFB36157FC"
352 "0882D574A10D839C1A0C049DC5E0D775"
353 "E2EE50671A208431BB45E78E70BEFE93"
354 "0DB34818EE4D5C26259F5C6B8E28A652"
355 "950F9F88D7B4B2C9D9"
356 // } end SEQUENCE (ECPrivateKey)
357 // } end SEQUENCE (PrivateKeyInfo)
358);
Selene Huang31ab4042020-04-29 04:22:39 -0700359
David Drysdaled2cc8c22021-04-15 13:29:45 +0100360string ec_256_key_rfc5915 = hex2str(
361 // RFC 5208 s5
362 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
363 "020100" // INTEGER length 1 value 0 (version)
364 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
365 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
366 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
367 "0608" // OBJECT IDENTIFIER length 8 (param)
368 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
369 // } end SEQUENCE (AlgorithmIdentifier)
370 "0479" // OCTET STRING length 0x79 (privateKey) holding...
371 // RFC 5915 s3
372 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
373 "020101" // INTEGER length 1 value 1 (version)
374 "0420" // OCTET STRING length 0x42 (privateKey)
375 "782370a8c8ce5537baadd04dcff079c8"
376 "158cfa9c67b818b38e8d21c9fa750c1d"
377 "a00a" // TAG [0] length 0xa (parameters)
378 "0608" // OBJECT IDENTIFIER length 8
379 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
380 // } end TAG [0]
381 "a144" // TAG [1] length 0x44 (publicKey) {
382 "0342" // BIT STRING length 0x42
383 "00" // no pad bits
384 "04e2cc561ee701da0ad0ef0d176bb0c9"
385 "19d42e79c393fdc1bd6c4010d85cf2cf"
386 "8e68c905464666f98dad4f01573ba810"
387 "78b3428570a439ba3229fbc026c55068"
388 "2f"
389 // } end SEQUENCE (ECPrivateKey)
390 // } end SEQUENCE (PrivateKeyInfo)
391);
Selene Huang31ab4042020-04-29 04:22:39 -0700392
David Drysdaled2cc8c22021-04-15 13:29:45 +0100393string ec_256_key_sec1 = hex2str(
394 // RFC 5208 s5
395 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
396 "020100" // INTEGER length 1 value 0 (version)
397 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
398 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
399 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
400 "0608" // OBJECT IDENTIFIER length 8 (param)
401 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
402 // } end SEQUENCE (AlgorithmIdentifier)
403 "046d" // OCTET STRING length 0x6d (privateKey) holding...
404 // SEC1-v2 C.4
405 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
406 "020101" // INTEGER length 1 value 0x01 (version)
407 "0420" // OCTET STRING length 0x20 (privateKey)
408 "782370a8c8ce5537baadd04dcff079c8"
409 "158cfa9c67b818b38e8d21c9fa750c1d"
410 "a144" // TAG [1] length 0x44 (publicKey) {
411 "0342" // BIT STRING length 0x42
412 "00" // no pad bits
413 "04e2cc561ee701da0ad0ef0d176bb0c9"
414 "19d42e79c393fdc1bd6c4010d85cf2cf"
415 "8e68c905464666f98dad4f01573ba810"
416 "78b3428570a439ba3229fbc026c55068"
417 "2f"
418 // } end TAG [1] (publicKey)
419 // } end SEQUENCE (PrivateKeyInfo)
420);
Selene Huang31ab4042020-04-29 04:22:39 -0700421
David Drysdale42fe1892021-10-14 14:43:46 +0100422/**
423 * Ed25519 key pair generated as follows:
424 * ```
425 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
426 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
427 * Generating a ED25519 private key writing new private key to
428 * 'ed25519_priv.key'
429 * -----
430 * % cat ed25519_priv.key
431 * -----BEGIN PRIVATE KEY-----
432 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
433 * -----END PRIVATE KEY-----
434 * % der2ascii -pem -i ed25519_priv.key
435 * SEQUENCE {
436 * INTEGER { 0 }
437 * SEQUENCE {
438 * # ed25519
439 * OBJECT_IDENTIFIER { 1.3.101.112 }
440 * }
441 * OCTET_STRING {
442 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
443 * }
444 * }
445 * % cat ed25519.pem
446 * -----BEGIN CERTIFICATE-----
447 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
448 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
449 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
450 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
451 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
452 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
453 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
454 * -----END CERTIFICATE-----
455 * % openssl x509 -in ed25519.pem -text -noout
456 * Certificate:
457 * Data:
458 * Version: 3 (0x2)
459 * Serial Number:
460 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
461 * Signature Algorithm: ED25519
462 * Issuer: CN = fake.ed25519.com
463 * Validity
464 * Not Before: Oct 20 08:27:42 2021 GMT
465 * Not After : Sep 20 08:27:42 2023 GMT
466 * Subject: CN = fake.ed25519.com
467 * Subject Public Key Info:
468 * Public Key Algorithm: ED25519
469 * ED25519 Public-Key:
470 * pub:
471 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
472 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
473 * 56:91
474 * X509v3 extensions:
475 * X509v3 Subject Key Identifier:
476 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
477 * X509v3 Authority Key Identifier:
478 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
479 *
480 * X509v3 Basic Constraints: critical
481 * CA:TRUE
482 * Signature Algorithm: ED25519
483 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
484 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
485 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
486 * e7:07:32:60:32:8d:bb:eb:f6:0f
487 * ```
488 */
489string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
490string ed25519_pkcs8_key = hex2str(
491 // RFC 5208 s5
492 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
493 "0201" // INTEGER length 1 (Version)
494 "00" // version 0
495 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
496 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
497 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
498 // } end SEQUENCE (AlgorithmIdentifier)
499 "0422" // OCTET STRING length 0x22 (PrivateKey)
500 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
501 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
502 // } end SEQUENCE (PrivateKeyInfo)
503);
504string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
505
506/**
507 * X25519 key pair generated as follows:
508 * ```
509 * % openssl genpkey -algorithm X25519 > x25519_priv.key
510 * % cat x25519_priv.key
511 * -----BEGIN PRIVATE KEY-----
512 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
513 * -----END PRIVATE KEY-----
514 * % der2ascii -pem -i x25519_priv.key
515 * SEQUENCE {
516 * INTEGER { 0 }
517 * SEQUENCE {
518 * # x25519
519 * OBJECT_IDENTIFIER { 1.3.101.110 }
520 * }
521 * OCTET_STRING {
522 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
523 * }
524 * }
525 * ```
526 */
527
528string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
529string x25519_pkcs8_key = hex2str(
530 // RFC 5208 s5
531 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
532 "0201" // INTEGER length 1 (Version)
533 "00" // version 0
534 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
535 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
536 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
537 "0422" // OCTET STRING length 0x22 (PrivateKey)
538 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
539 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
540string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
541
Selene Huang31ab4042020-04-29 04:22:39 -0700542struct RSA_Delete {
543 void operator()(RSA* p) { RSA_free(p); }
544};
545
Selene Huang31ab4042020-04-29 04:22:39 -0700546std::string make_string(const uint8_t* data, size_t length) {
547 return std::string(reinterpret_cast<const char*>(data), length);
548}
549
550template <size_t N>
551std::string make_string(const uint8_t (&a)[N]) {
552 return make_string(a, N);
553}
554
555class AidlBuf : public vector<uint8_t> {
556 typedef vector<uint8_t> super;
557
558 public:
559 AidlBuf() {}
560 AidlBuf(const super& other) : super(other) {}
561 AidlBuf(super&& other) : super(std::move(other)) {}
562 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
563
564 AidlBuf& operator=(const super& other) {
565 super::operator=(other);
566 return *this;
567 }
568
569 AidlBuf& operator=(super&& other) {
570 super::operator=(std::move(other));
571 return *this;
572 }
573
574 AidlBuf& operator=(const string& other) {
575 resize(other.size());
576 for (size_t i = 0; i < other.size(); ++i) {
577 (*this)[i] = static_cast<uint8_t>(other[i]);
578 }
579 return *this;
580 }
581
582 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
583};
584
David Drysdale4dc01072021-04-01 12:17:35 +0100585string device_suffix(const string& name) {
586 size_t pos = name.find('/');
587 if (pos == string::npos) {
588 return name;
589 }
590 return name.substr(pos + 1);
591}
592
593bool matching_rp_instance(const string& km_name,
594 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
595 string km_suffix = device_suffix(km_name);
596
597 vector<string> rp_names =
598 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
599 for (const string& rp_name : rp_names) {
600 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
601 // KeyMint instance, assume they match.
602 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
603 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
604 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
605 return true;
606 }
607 }
608 return false;
609}
610
Selene Huang31ab4042020-04-29 04:22:39 -0700611} // namespace
612
613class NewKeyGenerationTest : public KeyMintAidlTestBase {
614 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700615 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000616 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
Selene Huang31ab4042020-04-29 04:22:39 -0700617 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700618
Selene Huang31ab4042020-04-29 04:22:39 -0700619 // Check that some unexpected tags/values are NOT present.
620 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
621 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000622 }
623
624 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000625 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
David Drysdale7de9feb2021-03-05 14:56:19 +0000626 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
627 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
628
629 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000630 }
631
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000632 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics,
633 const KeyOrigin expectedKeyOrigin) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000634 // TODO(swillden): Distinguish which params should be in which auth list.
635 AuthorizationSet auths;
636 for (auto& entry : keyCharacteristics) {
637 auths.push_back(AuthorizationSet(entry.authorizations));
638 }
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000639 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, expectedKeyOrigin));
David Drysdale7de9feb2021-03-05 14:56:19 +0000640
641 // Verify that App data, ROT and auth timeout are NOT included.
642 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
643 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700644 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
645
David Drysdaled2cc8c22021-04-15 13:29:45 +0100646 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
647 // never adds it.
648 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
649
David Drysdale7de9feb2021-03-05 14:56:19 +0000650 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700651 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000652 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700653 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700654 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000655 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700656 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000657
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000658 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100659 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
660 EXPECT_TRUE(vendor_pl);
661 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000662
663 // Should include boot patchlevel (but there are some test scenarios where this is not
664 // possible).
665 if (check_boot_pl) {
666 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
667 EXPECT_TRUE(boot_pl);
668 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100669
David Drysdale7de9feb2021-03-05 14:56:19 +0000670 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700671 }
672};
673
674/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000675 * NewKeyGenerationTest.Aes
676 *
677 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
678 * have correct characteristics.
679 */
680TEST_P(NewKeyGenerationTest, Aes) {
681 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
682 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
683 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
684 SCOPED_TRACE(testing::Message()
685 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
686 vector<uint8_t> key_blob;
687 vector<KeyCharacteristics> key_characteristics;
688 auto builder = AuthorizationSetBuilder()
689 .AesEncryptionKey(key_size)
690 .BlockMode(block_mode)
691 .Padding(padding_mode)
692 .SetDefaultValidity();
693 if (block_mode == BlockMode::GCM) {
694 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
695 }
696 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
697
698 EXPECT_GT(key_blob.size(), 0U);
699 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100700 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000701
702 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
703
704 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
705 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
706 << "Key size " << key_size << "missing";
707
708 CheckedDeleteKey(&key_blob);
709 }
710 }
711 }
712}
713
714/*
715 * NewKeyGenerationTest.AesInvalidSize
716 *
717 * Verifies that specifying an invalid key size for AES key generation returns
718 * UNSUPPORTED_KEY_SIZE.
719 */
720TEST_P(NewKeyGenerationTest, AesInvalidSize) {
721 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
722 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
723 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
724 SCOPED_TRACE(testing::Message()
725 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
726 vector<uint8_t> key_blob;
727 vector<KeyCharacteristics> key_characteristics;
728 auto builder = AuthorizationSetBuilder()
729 .AesEncryptionKey(key_size)
730 .BlockMode(block_mode)
731 .Padding(padding_mode)
732 .SetDefaultValidity();
733 if (block_mode == BlockMode::GCM) {
734 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
735 }
736 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
737 GenerateKey(builder, &key_blob, &key_characteristics));
738 }
739 }
740 }
741
742 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
743 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100744 SCOPED_TRACE(testing::Message() << "AES-unknown-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000745 vector<uint8_t> key_blob;
746 vector<KeyCharacteristics> key_characteristics;
747 // No key size specified
748 auto builder = AuthorizationSetBuilder()
749 .Authorization(TAG_ALGORITHM, Algorithm::AES)
750 .BlockMode(block_mode)
751 .Padding(padding_mode)
752 .SetDefaultValidity();
753 if (block_mode == BlockMode::GCM) {
754 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
755 }
756 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
757 GenerateKey(builder, &key_blob, &key_characteristics));
758 }
759 }
760}
761
762/*
763 * NewKeyGenerationTest.AesInvalidPadding
764 *
765 * Verifies that specifying an invalid padding on AES keys gives a failure
766 * somewhere along the way.
767 */
768TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
769 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
770 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
771 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
772 SCOPED_TRACE(testing::Message()
773 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000774 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800775 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000776 .AesEncryptionKey(key_size)
777 .BlockMode(block_mode)
778 .Padding(padding_mode)
779 .SetDefaultValidity();
780 if (block_mode == BlockMode::GCM) {
781 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
782 }
783
Tommy Chiu3950b452021-05-03 22:01:46 +0800784 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000785 if (result == ErrorCode::OK) {
786 // Key creation was OK but has generated a key that cannot be used.
787 auto params =
788 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800789 if (block_mode == BlockMode::GCM) {
790 params.Authorization(TAG_MAC_LENGTH, 128);
791 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000792 auto result = Begin(KeyPurpose::ENCRYPT, params);
793 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100794 result == ErrorCode::INVALID_KEY_BLOB)
795 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000796 } else {
797 // The KeyMint implementation detected that the generated key
798 // is unusable.
799 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
800 }
801 }
802 }
803 }
804}
805
806/*
807 * NewKeyGenerationTest.AesGcmMissingMinMac
808 *
809 * Verifies that specifying an invalid key size for AES key generation returns
810 * UNSUPPORTED_KEY_SIZE.
811 */
812TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
813 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
814 BlockMode block_mode = BlockMode::GCM;
815 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
816 SCOPED_TRACE(testing::Message()
817 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
818 vector<uint8_t> key_blob;
819 vector<KeyCharacteristics> key_characteristics;
820 // No MIN_MAC_LENGTH provided.
821 auto builder = AuthorizationSetBuilder()
822 .AesEncryptionKey(key_size)
823 .BlockMode(block_mode)
824 .Padding(padding_mode)
825 .SetDefaultValidity();
826 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
827 GenerateKey(builder, &key_blob, &key_characteristics));
828 }
829 }
830}
831
832/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100833 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
834 *
835 * Verifies that specifying an invalid min MAC size for AES key generation returns
836 * UNSUPPORTED_MIN_MAC_LENGTH.
837 */
838TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
839 for (size_t min_mac_len : {88, 136}) {
840 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
841 BlockMode block_mode = BlockMode::GCM;
842 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
843 SCOPED_TRACE(testing::Message()
844 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
845 vector<uint8_t> key_blob;
846 vector<KeyCharacteristics> key_characteristics;
847 auto builder = AuthorizationSetBuilder()
848 .AesEncryptionKey(key_size)
849 .BlockMode(block_mode)
850 .Padding(padding_mode)
851 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
852 .SetDefaultValidity();
853 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
854 GenerateKey(builder, &key_blob, &key_characteristics));
855 }
856 }
857 }
858}
859
860/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000861 * NewKeyGenerationTest.TripleDes
862 *
863 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
864 * have correct characteristics.
865 */
866TEST_P(NewKeyGenerationTest, TripleDes) {
867 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
868 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
869 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
870 SCOPED_TRACE(testing::Message()
871 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
872 vector<uint8_t> key_blob;
873 vector<KeyCharacteristics> key_characteristics;
874 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
875 .TripleDesEncryptionKey(key_size)
876 .BlockMode(block_mode)
877 .Padding(padding_mode)
878 .Authorization(TAG_NO_AUTH_REQUIRED)
879 .SetDefaultValidity(),
880 &key_blob, &key_characteristics));
881
882 EXPECT_GT(key_blob.size(), 0U);
883 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100884 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000885
886 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
887
888 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
889 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
890 << "Key size " << key_size << "missing";
891
892 CheckedDeleteKey(&key_blob);
893 }
894 }
895 }
896}
897
898/*
899 * NewKeyGenerationTest.TripleDesWithAttestation
900 *
901 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
902 * have correct characteristics.
903 *
904 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
905 * put in a certificate) but which isn't an error.
906 */
907TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
908 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
909 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
910 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
911 SCOPED_TRACE(testing::Message()
912 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
913
914 auto challenge = "hello";
915 auto app_id = "foo";
916
917 vector<uint8_t> key_blob;
918 vector<KeyCharacteristics> key_characteristics;
919 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
920 .TripleDesEncryptionKey(key_size)
921 .BlockMode(block_mode)
922 .Padding(padding_mode)
923 .Authorization(TAG_NO_AUTH_REQUIRED)
924 .AttestationChallenge(challenge)
925 .AttestationApplicationId(app_id)
926 .SetDefaultValidity(),
927 &key_blob, &key_characteristics));
928
929 EXPECT_GT(key_blob.size(), 0U);
930 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100931 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000932
933 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
934
935 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
936 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
937 << "Key size " << key_size << "missing";
938
939 CheckedDeleteKey(&key_blob);
940 }
941 }
942 }
943}
944
945/*
946 * NewKeyGenerationTest.TripleDesInvalidSize
947 *
948 * Verifies that specifying an invalid key size for 3-DES key generation returns
949 * UNSUPPORTED_KEY_SIZE.
950 */
951TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
952 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
953 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
954 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
955 SCOPED_TRACE(testing::Message()
956 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
957 vector<uint8_t> key_blob;
958 vector<KeyCharacteristics> key_characteristics;
959 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
960 GenerateKey(AuthorizationSetBuilder()
961 .TripleDesEncryptionKey(key_size)
962 .BlockMode(block_mode)
963 .Padding(padding_mode)
964 .Authorization(TAG_NO_AUTH_REQUIRED)
965 .SetDefaultValidity(),
966 &key_blob, &key_characteristics));
967 }
968 }
969 }
970
971 // Omitting the key size fails.
972 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
973 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
974 SCOPED_TRACE(testing::Message()
975 << "3DES-default-" << block_mode << "-" << padding_mode);
976 vector<uint8_t> key_blob;
977 vector<KeyCharacteristics> key_characteristics;
978 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
979 GenerateKey(AuthorizationSetBuilder()
980 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
981 .BlockMode(block_mode)
982 .Padding(padding_mode)
983 .Authorization(TAG_NO_AUTH_REQUIRED)
984 .SetDefaultValidity(),
985 &key_blob, &key_characteristics));
986 }
987 }
988}
989
990/*
Selene Huang31ab4042020-04-29 04:22:39 -0700991 * NewKeyGenerationTest.Rsa
992 *
993 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
994 * have correct characteristics.
995 */
996TEST_P(NewKeyGenerationTest, Rsa) {
997 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100998 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -0700999 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001000 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001001 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1002 .RsaSigningKey(key_size, 65537)
1003 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001004 .Padding(PaddingMode::NONE)
1005 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001006 &key_blob, &key_characteristics));
1007
1008 ASSERT_GT(key_blob.size(), 0U);
1009 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001010 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001011
Shawn Willden7f424372021-01-10 18:06:50 -07001012 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001013
1014 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1015 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1016 << "Key size " << key_size << "missing";
1017 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1018
1019 CheckedDeleteKey(&key_blob);
1020 }
1021}
1022
1023/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001024 * NewKeyGenerationTest.RsaWithMissingValidity
1025 *
1026 * Verifies that keymint returns an error while generating asymmetric key
1027 * without providing NOT_BEFORE and NOT_AFTER parameters.
1028 */
1029TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
Seth Moore7dc1fda2022-12-12 16:56:20 -08001030 if (AidlVersion() < 3) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001031 /*
1032 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1033 * specified for asymmetric key generation. However, this was not
1034 * checked at the time so we can only be strict about checking this for
1035 * implementations of KeyMint version 2 and above.
1036 */
1037 GTEST_SKIP() << "Validity strict since KeyMint v2";
1038 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001039 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1040 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1041 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1042
1043 vector<uint8_t> key_blob;
1044 vector<KeyCharacteristics> key_characteristics;
1045 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1046 GenerateKey(AuthorizationSetBuilder()
1047 .RsaSigningKey(2048, 65537)
1048 .Digest(Digest::NONE)
1049 .Padding(PaddingMode::NONE)
1050 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1051 kUndefinedExpirationDateTime),
1052 &key_blob, &key_characteristics));
1053
1054 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1055 GenerateKey(AuthorizationSetBuilder()
1056 .RsaSigningKey(2048, 65537)
1057 .Digest(Digest::NONE)
1058 .Padding(PaddingMode::NONE)
1059 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1060 &key_blob, &key_characteristics));
1061}
1062
1063/*
Qi Wud22ec842020-11-26 13:27:53 +08001064 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001065 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001066 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1067 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001068 */
1069TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001070 auto challenge = "hello";
1071 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001072
Selene Huang6e46f142021-04-20 19:20:11 -07001073 auto subject = "cert subj 2";
1074 vector<uint8_t> subject_der(make_name_from_str(subject));
1075
1076 uint64_t serial_int = 66;
1077 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1078
Selene Huang4f64c222021-04-13 19:54:36 -07001079 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001080 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001081 vector<uint8_t> key_blob;
1082 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001083 auto builder = AuthorizationSetBuilder()
1084 .RsaSigningKey(key_size, 65537)
1085 .Digest(Digest::NONE)
1086 .Padding(PaddingMode::NONE)
1087 .AttestationChallenge(challenge)
1088 .AttestationApplicationId(app_id)
1089 .Authorization(TAG_NO_AUTH_REQUIRED)
1090 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1091 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1092 .SetDefaultValidity();
1093
1094 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001095 // Strongbox may not support factory provisioned attestation key.
1096 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001097 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1098 result = GenerateKeyWithSelfSignedAttestKey(
1099 AuthorizationSetBuilder()
1100 .RsaKey(key_size, 65537)
1101 .AttestKey()
1102 .SetDefaultValidity(), /* attest key params */
1103 builder, &key_blob, &key_characteristics);
1104 }
subrahmanyaman05642492022-02-05 07:10:56 +00001105 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001106 ASSERT_EQ(ErrorCode::OK, result);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001107 ASSERT_GT(key_blob.size(), 0U);
1108 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001109 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001110
1111 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1112
1113 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1114 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1115 << "Key size " << key_size << "missing";
1116 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1117
David Drysdalea8a888e2022-06-08 12:43:56 +01001118 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001119 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001120 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001121
1122 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1123 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001124 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001125 sw_enforced, hw_enforced, SecLevel(),
1126 cert_chain_[0].encodedCertificate));
1127
1128 CheckedDeleteKey(&key_blob);
1129 }
1130}
1131
1132/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001133 * NewKeyGenerationTest.RsaWithRkpAttestation
David Drysdale4dc01072021-04-01 12:17:35 +01001134 *
Seth Moore7dc1fda2022-12-12 16:56:20 -08001135 * Verifies that keymint can generate all required RSA key sizes using an attestation key
David Drysdale4dc01072021-04-01 12:17:35 +01001136 * that has been generated using an associate IRemotelyProvisionedComponent.
1137 */
Seth Moore7dc1fda2022-12-12 16:56:20 -08001138TEST_P(NewKeyGenerationTest, RsaWithRkpAttestation) {
1139 if (AidlVersion() < 2) {
1140 GTEST_SKIP() << "Only required starting with KeyMint v2";
1141 }
1142
David Drysdale4dc01072021-04-01 12:17:35 +01001143 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
1144 // instance.
1145 std::shared_ptr<IRemotelyProvisionedComponent> rp;
1146 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
1147 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
1148
1149 // Generate a P-256 keypair to use as an attestation key.
1150 MacedPublicKey macedPubKey;
1151 std::vector<uint8_t> privateKeyBlob;
1152 auto status =
1153 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1154 ASSERT_TRUE(status.isOk());
1155 vector<uint8_t> coseKeyData;
1156 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1157
1158 AttestationKey attestation_key;
1159 attestation_key.keyBlob = std::move(privateKeyBlob);
1160 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1161
1162 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001163 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdale4dc01072021-04-01 12:17:35 +01001164 auto challenge = "hello";
1165 auto app_id = "foo";
1166
1167 vector<uint8_t> key_blob;
1168 vector<KeyCharacteristics> key_characteristics;
1169 ASSERT_EQ(ErrorCode::OK,
1170 GenerateKey(AuthorizationSetBuilder()
1171 .RsaSigningKey(key_size, 65537)
1172 .Digest(Digest::NONE)
1173 .Padding(PaddingMode::NONE)
1174 .AttestationChallenge(challenge)
1175 .AttestationApplicationId(app_id)
1176 .Authorization(TAG_NO_AUTH_REQUIRED)
1177 .SetDefaultValidity(),
1178 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1179
1180 ASSERT_GT(key_blob.size(), 0U);
1181 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001182 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001183
1184 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1185
1186 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1187 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1188 << "Key size " << key_size << "missing";
1189 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1190
1191 // Attestation by itself is not valid (last entry is not self-signed).
1192 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1193
1194 // The signature over the attested key should correspond to the P256 public key.
David Drysdalea8a888e2022-06-08 12:43:56 +01001195 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale4dc01072021-04-01 12:17:35 +01001196 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1197 ASSERT_TRUE(key_cert.get());
1198 EVP_PKEY_Ptr signing_pubkey;
1199 p256_pub_key(coseKeyData, &signing_pubkey);
1200 ASSERT_TRUE(signing_pubkey.get());
1201
1202 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1203 << "Verification of attested certificate failed "
1204 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1205
1206 CheckedDeleteKey(&key_blob);
1207 }
1208}
1209
1210/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001211 * NewKeyGenerationTest.EcdsaWithRkpAttestation
1212 *
1213 * Verifies that keymint can generate all required ECDSA key sizes using an attestation key
1214 * that has been generated using an associate IRemotelyProvisionedComponent.
1215 */
1216TEST_P(NewKeyGenerationTest, EcdsaWithRkpAttestation) {
1217 if (AidlVersion() < 2) {
1218 GTEST_SKIP() << "Only required starting with KeyMint v2";
1219 }
1220
1221 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
1222 // instance.
1223 std::shared_ptr<IRemotelyProvisionedComponent> rp;
1224 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
1225 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
1226
1227 // Generate a P-256 keypair to use as an attestation key.
1228 MacedPublicKey macedPubKey;
1229 std::vector<uint8_t> privateKeyBlob;
1230 auto status =
1231 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1232 ASSERT_TRUE(status.isOk());
1233 vector<uint8_t> coseKeyData;
1234 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1235
1236 AttestationKey attestation_key;
1237 attestation_key.keyBlob = std::move(privateKeyBlob);
1238 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1239
1240 for (auto curve : ValidCurves()) {
1241 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
1242 auto challenge = "hello";
1243 auto app_id = "foo";
1244
1245 vector<uint8_t> key_blob;
1246 vector<KeyCharacteristics> key_characteristics;
1247 ASSERT_EQ(ErrorCode::OK,
1248 GenerateKey(AuthorizationSetBuilder()
1249 .EcdsaSigningKey(curve)
1250 .Digest(Digest::NONE)
1251 .AttestationChallenge(challenge)
1252 .AttestationApplicationId(app_id)
1253 .Authorization(TAG_NO_AUTH_REQUIRED)
1254 .SetDefaultValidity(),
1255 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1256
1257 ASSERT_GT(key_blob.size(), 0U);
1258 CheckBaseParams(key_characteristics);
1259 CheckCharacteristics(key_blob, key_characteristics);
1260
1261 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1262
1263 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1264 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1265
1266 // Attestation by itself is not valid (last entry is not self-signed).
1267 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1268
1269 // The signature over the attested key should correspond to the P256 public key.
1270 ASSERT_GT(cert_chain_.size(), 0);
1271 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1272 ASSERT_TRUE(key_cert.get());
1273 EVP_PKEY_Ptr signing_pubkey;
1274 p256_pub_key(coseKeyData, &signing_pubkey);
1275 ASSERT_TRUE(signing_pubkey.get());
1276
1277 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1278 << "Verification of attested certificate failed "
1279 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1280
1281 CheckedDeleteKey(&key_blob);
1282 }
1283}
1284
1285/*
Selene Huang4f64c222021-04-13 19:54:36 -07001286 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1287 *
1288 * Verifies that keymint attestation for RSA encryption keys with challenge and
1289 * app id is also successful.
1290 */
1291TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1292 auto key_size = 2048;
1293 auto challenge = "hello";
1294 auto app_id = "foo";
1295
Selene Huang6e46f142021-04-20 19:20:11 -07001296 auto subject = "subj 2";
1297 vector<uint8_t> subject_der(make_name_from_str(subject));
1298
1299 uint64_t serial_int = 111166;
1300 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1301
Selene Huang4f64c222021-04-13 19:54:36 -07001302 vector<uint8_t> key_blob;
1303 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001304 auto builder = AuthorizationSetBuilder()
1305 .RsaEncryptionKey(key_size, 65537)
1306 .Padding(PaddingMode::NONE)
1307 .AttestationChallenge(challenge)
1308 .AttestationApplicationId(app_id)
1309 .Authorization(TAG_NO_AUTH_REQUIRED)
1310 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1311 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1312 .SetDefaultValidity();
1313
1314 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001315 // Strongbox may not support factory provisioned attestation key.
1316 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001317 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1318 result = GenerateKeyWithSelfSignedAttestKey(
1319 AuthorizationSetBuilder()
1320 .RsaKey(key_size, 65537)
1321 .AttestKey()
1322 .SetDefaultValidity(), /* attest key params */
1323 builder, &key_blob, &key_characteristics);
1324 }
subrahmanyaman05642492022-02-05 07:10:56 +00001325 }
1326 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001327
1328 ASSERT_GT(key_blob.size(), 0U);
1329 AuthorizationSet auths;
1330 for (auto& entry : key_characteristics) {
1331 auths.push_back(AuthorizationSet(entry.authorizations));
1332 }
1333
1334 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1335 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1336
1337 // Verify that App data and ROT are NOT included.
1338 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1339 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1340
1341 // Check that some unexpected tags/values are NOT present.
1342 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1343 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1344
1345 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1346
1347 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1348 ASSERT_TRUE(os_ver);
1349 EXPECT_EQ(*os_ver, os_version());
1350
1351 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1352
1353 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1354 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1355 << "Key size " << key_size << "missing";
1356 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1357
David Drysdalea8a888e2022-06-08 12:43:56 +01001358 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001359 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001360 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001361
1362 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1363 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001364 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001365 sw_enforced, hw_enforced, SecLevel(),
1366 cert_chain_[0].encodedCertificate));
1367
1368 CheckedDeleteKey(&key_blob);
1369}
1370
1371/*
1372 * NewKeyGenerationTest.RsaWithSelfSign
1373 *
1374 * Verifies that attesting to RSA key generation is successful, and returns
1375 * self signed certificate if no challenge is provided. And signing etc
1376 * works as expected.
1377 */
1378TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001379 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1380 vector<uint8_t> subject_der(make_name_from_str(subject));
1381
1382 uint64_t serial_int = 0;
1383 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1384
Selene Huang4f64c222021-04-13 19:54:36 -07001385 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001386 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang4f64c222021-04-13 19:54:36 -07001387 vector<uint8_t> key_blob;
1388 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001389 ASSERT_EQ(ErrorCode::OK,
1390 GenerateKey(AuthorizationSetBuilder()
1391 .RsaSigningKey(key_size, 65537)
1392 .Digest(Digest::NONE)
1393 .Padding(PaddingMode::NONE)
1394 .Authorization(TAG_NO_AUTH_REQUIRED)
1395 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1396 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1397 .SetDefaultValidity(),
1398 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001399
1400 ASSERT_GT(key_blob.size(), 0U);
1401 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001402 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001403
1404 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1405
1406 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1407 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1408 << "Key size " << key_size << "missing";
1409 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1410
David Drysdalea8a888e2022-06-08 12:43:56 +01001411 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang6e46f142021-04-20 19:20:11 -07001412 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001413 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001414
1415 CheckedDeleteKey(&key_blob);
1416 }
1417}
1418
1419/*
1420 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1421 *
1422 * Verifies that attesting to RSA checks for missing app ID.
1423 */
1424TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1425 auto challenge = "hello";
1426 vector<uint8_t> key_blob;
1427 vector<KeyCharacteristics> key_characteristics;
1428
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001429 auto builder = AuthorizationSetBuilder()
1430 .RsaSigningKey(2048, 65537)
1431 .Digest(Digest::NONE)
1432 .Padding(PaddingMode::NONE)
1433 .AttestationChallenge(challenge)
1434 .Authorization(TAG_NO_AUTH_REQUIRED)
1435 .SetDefaultValidity();
1436
1437 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001438 // Strongbox may not support factory provisioned attestation key.
1439 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001440 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1441 result = GenerateKeyWithSelfSignedAttestKey(
1442 AuthorizationSetBuilder()
1443 .RsaKey(2048, 65537)
1444 .AttestKey()
1445 .SetDefaultValidity(), /* attest key params */
1446 builder, &key_blob, &key_characteristics);
1447 }
subrahmanyaman05642492022-02-05 07:10:56 +00001448 }
1449 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001450}
1451
1452/*
1453 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1454 *
1455 * Verifies that attesting to RSA ignores app id if challenge is missing.
1456 */
1457TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1458 auto key_size = 2048;
1459 auto app_id = "foo";
1460
Selene Huang6e46f142021-04-20 19:20:11 -07001461 auto subject = "cert subj 2";
1462 vector<uint8_t> subject_der(make_name_from_str(subject));
1463
1464 uint64_t serial_int = 1;
1465 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1466
Selene Huang4f64c222021-04-13 19:54:36 -07001467 vector<uint8_t> key_blob;
1468 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001469 ASSERT_EQ(ErrorCode::OK,
1470 GenerateKey(AuthorizationSetBuilder()
1471 .RsaSigningKey(key_size, 65537)
1472 .Digest(Digest::NONE)
1473 .Padding(PaddingMode::NONE)
1474 .AttestationApplicationId(app_id)
1475 .Authorization(TAG_NO_AUTH_REQUIRED)
1476 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1477 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1478 .SetDefaultValidity(),
1479 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001480
1481 ASSERT_GT(key_blob.size(), 0U);
1482 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001483 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001484
1485 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1486
1487 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1488 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1489 << "Key size " << key_size << "missing";
1490 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1491
David Drysdalea8a888e2022-06-08 12:43:56 +01001492 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001493 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001494 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1495 ASSERT_EQ(cert_chain_.size(), 1);
1496
1497 CheckedDeleteKey(&key_blob);
1498}
1499
1500/*
Qi Wud22ec842020-11-26 13:27:53 +08001501 * NewKeyGenerationTest.LimitedUsageRsa
1502 *
1503 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1504 * resulting keys have correct characteristics.
1505 */
1506TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1507 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001508 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wud22ec842020-11-26 13:27:53 +08001509 vector<uint8_t> key_blob;
1510 vector<KeyCharacteristics> key_characteristics;
1511 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1512 .RsaSigningKey(key_size, 65537)
1513 .Digest(Digest::NONE)
1514 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001515 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1516 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001517 &key_blob, &key_characteristics));
1518
1519 ASSERT_GT(key_blob.size(), 0U);
1520 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001521 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001522
1523 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1524
1525 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1526 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1527 << "Key size " << key_size << "missing";
1528 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1529
1530 // Check the usage count limit tag appears in the authorizations.
1531 AuthorizationSet auths;
1532 for (auto& entry : key_characteristics) {
1533 auths.push_back(AuthorizationSet(entry.authorizations));
1534 }
1535 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1536 << "key usage count limit " << 1U << " missing";
1537
1538 CheckedDeleteKey(&key_blob);
1539 }
1540}
1541
1542/*
Qi Wubeefae42021-01-28 23:16:37 +08001543 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1544 *
1545 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1546 * resulting keys have correct characteristics and attestation.
1547 */
1548TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001549 auto challenge = "hello";
1550 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001551
Selene Huang6e46f142021-04-20 19:20:11 -07001552 auto subject = "cert subj 2";
1553 vector<uint8_t> subject_der(make_name_from_str(subject));
1554
1555 uint64_t serial_int = 66;
1556 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1557
Selene Huang4f64c222021-04-13 19:54:36 -07001558 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001559 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wubeefae42021-01-28 23:16:37 +08001560 vector<uint8_t> key_blob;
1561 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001562 auto builder = AuthorizationSetBuilder()
1563 .RsaSigningKey(key_size, 65537)
1564 .Digest(Digest::NONE)
1565 .Padding(PaddingMode::NONE)
1566 .AttestationChallenge(challenge)
1567 .AttestationApplicationId(app_id)
1568 .Authorization(TAG_NO_AUTH_REQUIRED)
1569 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1570 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1571 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1572 .SetDefaultValidity();
1573
1574 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001575 // Strongbox may not support factory provisioned attestation key.
1576 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001577 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1578 result = GenerateKeyWithSelfSignedAttestKey(
1579 AuthorizationSetBuilder()
1580 .RsaKey(key_size, 65537)
1581 .AttestKey()
1582 .SetDefaultValidity(), /* attest key params */
1583 builder, &key_blob, &key_characteristics);
1584 }
subrahmanyaman05642492022-02-05 07:10:56 +00001585 }
1586 ASSERT_EQ(ErrorCode::OK, result);
Qi Wubeefae42021-01-28 23:16:37 +08001587
1588 ASSERT_GT(key_blob.size(), 0U);
1589 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001590 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001591
1592 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1593
1594 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1595 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1596 << "Key size " << key_size << "missing";
1597 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1598
1599 // Check the usage count limit tag appears in the authorizations.
1600 AuthorizationSet auths;
1601 for (auto& entry : key_characteristics) {
1602 auths.push_back(AuthorizationSet(entry.authorizations));
1603 }
1604 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1605 << "key usage count limit " << 1U << " missing";
1606
1607 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001608 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001609 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001610 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001611
1612 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1613 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001614 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001615 sw_enforced, hw_enforced, SecLevel(),
1616 cert_chain_[0].encodedCertificate));
1617
1618 CheckedDeleteKey(&key_blob);
1619 }
1620}
1621
1622/*
Selene Huang31ab4042020-04-29 04:22:39 -07001623 * NewKeyGenerationTest.NoInvalidRsaSizes
1624 *
1625 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1626 */
1627TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1628 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001629 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07001630 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001631 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001632 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1633 GenerateKey(AuthorizationSetBuilder()
1634 .RsaSigningKey(key_size, 65537)
1635 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001636 .Padding(PaddingMode::NONE)
1637 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001638 &key_blob, &key_characteristics));
1639 }
1640}
1641
1642/*
1643 * NewKeyGenerationTest.RsaNoDefaultSize
1644 *
1645 * Verifies that failing to specify a key size for RSA key generation returns
1646 * UNSUPPORTED_KEY_SIZE.
1647 */
1648TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1649 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1650 GenerateKey(AuthorizationSetBuilder()
1651 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1652 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001653 .SigningKey()
1654 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001655}
1656
1657/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001658 * NewKeyGenerationTest.RsaMissingParams
1659 *
1660 * Verifies that omitting optional tags works.
1661 */
1662TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1663 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001664 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdaled2cc8c22021-04-15 13:29:45 +01001665 ASSERT_EQ(ErrorCode::OK,
1666 GenerateKey(
1667 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1668 CheckedDeleteKey();
1669 }
1670}
1671
1672/*
Selene Huang31ab4042020-04-29 04:22:39 -07001673 * NewKeyGenerationTest.Ecdsa
1674 *
David Drysdale42fe1892021-10-14 14:43:46 +01001675 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001676 * have correct characteristics.
1677 */
1678TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001679 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001680 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07001681 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001682 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001683 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001684 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001685 .Digest(Digest::NONE)
1686 .SetDefaultValidity(),
1687 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001688 ASSERT_GT(key_blob.size(), 0U);
1689 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001690 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001691
Shawn Willden7f424372021-01-10 18:06:50 -07001692 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001693
1694 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001695 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001696
1697 CheckedDeleteKey(&key_blob);
1698 }
1699}
1700
1701/*
David Drysdale42fe1892021-10-14 14:43:46 +01001702 * NewKeyGenerationTest.EcdsaCurve25519
1703 *
1704 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1705 * has correct characteristics.
1706 */
1707TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1708 if (!Curve25519Supported()) {
1709 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1710 }
1711
1712 EcCurve curve = EcCurve::CURVE_25519;
1713 vector<uint8_t> key_blob;
1714 vector<KeyCharacteristics> key_characteristics;
1715 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1716 .EcdsaSigningKey(curve)
1717 .Digest(Digest::NONE)
1718 .SetDefaultValidity(),
1719 &key_blob, &key_characteristics);
1720 ASSERT_EQ(result, ErrorCode::OK);
1721 ASSERT_GT(key_blob.size(), 0U);
1722
1723 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1724 ASSERT_GT(cert_chain_.size(), 0);
1725
1726 CheckBaseParams(key_characteristics);
1727 CheckCharacteristics(key_blob, key_characteristics);
1728
1729 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1730
1731 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1732 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1733
1734 CheckedDeleteKey(&key_blob);
1735}
1736
1737/*
1738 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1739 *
1740 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1741 * SIGN and AGREE_KEY.
1742 */
1743TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1744 if (!Curve25519Supported()) {
1745 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1746 }
1747
1748 EcCurve curve = EcCurve::CURVE_25519;
1749 vector<uint8_t> key_blob;
1750 vector<KeyCharacteristics> key_characteristics;
1751 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1752 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1753 .EcdsaSigningKey(curve)
1754 .Digest(Digest::NONE)
1755 .SetDefaultValidity(),
1756 &key_blob, &key_characteristics);
1757 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1758}
1759
1760/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001761 * NewKeyGenerationTest.EcdsaWithMissingValidity
1762 *
1763 * Verifies that keymint returns an error while generating asymmetric key
1764 * without providing NOT_BEFORE and NOT_AFTER parameters.
1765 */
1766TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001767 if (AidlVersion() < 2) {
1768 /*
1769 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1770 * specified for asymmetric key generation. However, this was not
1771 * checked at the time so we can only be strict about checking this for
1772 * implementations of KeyMint version 2 and above.
1773 */
1774 GTEST_SKIP() << "Validity strict since KeyMint v2";
1775 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001776 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1777 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1778 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1779
1780 vector<uint8_t> key_blob;
1781 vector<KeyCharacteristics> key_characteristics;
1782 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1783 GenerateKey(AuthorizationSetBuilder()
1784 .EcdsaSigningKey(EcCurve::P_256)
1785 .Digest(Digest::NONE)
1786 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1787 kUndefinedExpirationDateTime),
1788 &key_blob, &key_characteristics));
1789
1790 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1791 GenerateKey(AuthorizationSetBuilder()
1792 .EcdsaSigningKey(EcCurve::P_256)
1793 .Digest(Digest::NONE)
1794 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1795 &key_blob, &key_characteristics));
1796}
1797
1798/*
Selene Huang4f64c222021-04-13 19:54:36 -07001799 * NewKeyGenerationTest.EcdsaAttestation
1800 *
1801 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1802 * an attestation will be generated.
1803 */
1804TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1805 auto challenge = "hello";
1806 auto app_id = "foo";
1807
Selene Huang6e46f142021-04-20 19:20:11 -07001808 auto subject = "cert subj 2";
1809 vector<uint8_t> subject_der(make_name_from_str(subject));
1810
1811 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1812 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1813
David Drysdaledf09e542021-06-08 15:46:11 +01001814 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001815 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07001816 vector<uint8_t> key_blob;
1817 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001818 auto builder = AuthorizationSetBuilder()
1819 .Authorization(TAG_NO_AUTH_REQUIRED)
1820 .EcdsaSigningKey(curve)
1821 .Digest(Digest::NONE)
1822 .AttestationChallenge(challenge)
1823 .AttestationApplicationId(app_id)
1824 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1825 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1826 .SetDefaultValidity();
1827
1828 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001829 // Strongbox may not support factory provisioned attestation key.
1830 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001831 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1832 result = GenerateKeyWithSelfSignedAttestKey(
1833 AuthorizationSetBuilder()
1834 .EcdsaKey(curve)
1835 .AttestKey()
1836 .SetDefaultValidity(), /* attest key params */
1837 builder, &key_blob, &key_characteristics);
1838 }
subrahmanyaman05642492022-02-05 07:10:56 +00001839 }
1840 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001841 ASSERT_GT(key_blob.size(), 0U);
1842 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001843 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001844
1845 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1846
1847 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001848 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001849
1850 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1851 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001852 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001853
1854 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1855 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001856 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001857 sw_enforced, hw_enforced, SecLevel(),
1858 cert_chain_[0].encodedCertificate));
1859
1860 CheckedDeleteKey(&key_blob);
1861 }
1862}
1863
1864/*
David Drysdale42fe1892021-10-14 14:43:46 +01001865 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1866 *
1867 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1868 * an attestation will be generated.
1869 */
1870TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1871 if (!Curve25519Supported()) {
1872 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1873 }
1874
1875 EcCurve curve = EcCurve::CURVE_25519;
1876 auto challenge = "hello";
1877 auto app_id = "foo";
1878
1879 auto subject = "cert subj 2";
1880 vector<uint8_t> subject_der(make_name_from_str(subject));
1881
1882 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1883 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1884
1885 vector<uint8_t> key_blob;
1886 vector<KeyCharacteristics> key_characteristics;
1887 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1888 .Authorization(TAG_NO_AUTH_REQUIRED)
1889 .EcdsaSigningKey(curve)
1890 .Digest(Digest::NONE)
1891 .AttestationChallenge(challenge)
1892 .AttestationApplicationId(app_id)
1893 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1894 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1895 .SetDefaultValidity(),
1896 &key_blob, &key_characteristics);
1897 ASSERT_EQ(ErrorCode::OK, result);
1898 ASSERT_GT(key_blob.size(), 0U);
1899 CheckBaseParams(key_characteristics);
1900 CheckCharacteristics(key_blob, key_characteristics);
1901
1902 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1903
1904 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1905 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1906
1907 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1908 ASSERT_GT(cert_chain_.size(), 0);
1909 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1910
1911 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1912 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1913 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1914 sw_enforced, hw_enforced, SecLevel(),
1915 cert_chain_[0].encodedCertificate));
1916
1917 CheckedDeleteKey(&key_blob);
1918}
1919
1920/*
David Drysdale37af4b32021-05-14 16:46:59 +01001921 * NewKeyGenerationTest.EcdsaAttestationTags
1922 *
1923 * Verifies that creation of an attested ECDSA key includes various tags in the
1924 * attestation extension.
1925 */
1926TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1927 auto challenge = "hello";
1928 auto app_id = "foo";
1929 auto subject = "cert subj 2";
1930 vector<uint8_t> subject_der(make_name_from_str(subject));
1931 uint64_t serial_int = 0x1010;
1932 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1933 const AuthorizationSetBuilder base_builder =
1934 AuthorizationSetBuilder()
1935 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001936 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001937 .Digest(Digest::NONE)
1938 .AttestationChallenge(challenge)
1939 .AttestationApplicationId(app_id)
1940 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1941 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1942 .SetDefaultValidity();
1943
1944 // Various tags that map to fields in the attestation extension ASN.1 schema.
1945 auto extra_tags = AuthorizationSetBuilder()
1946 .Authorization(TAG_ROLLBACK_RESISTANCE)
1947 .Authorization(TAG_EARLY_BOOT_ONLY)
1948 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1949 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1950 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1951 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1952 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1953 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1954 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1955 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1956 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1957 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001958
David Drysdale37af4b32021-05-14 16:46:59 +01001959 for (const KeyParameter& tag : extra_tags) {
1960 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1961 vector<uint8_t> key_blob;
1962 vector<KeyCharacteristics> key_characteristics;
1963 AuthorizationSetBuilder builder = base_builder;
1964 builder.push_back(tag);
1965 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1966 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1967 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1968 continue;
1969 }
Seth Mooreb393b082021-07-12 14:18:28 -07001970 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1971 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001972 continue;
1973 }
subrahmanyaman05642492022-02-05 07:10:56 +00001974 // Strongbox may not support factory provisioned attestation key.
1975 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001976 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1977 result = GenerateKeyWithSelfSignedAttestKey(
1978 AuthorizationSetBuilder()
1979 .EcdsaKey(EcCurve::P_256)
1980 .AttestKey()
1981 .SetDefaultValidity(), /* attest key params */
1982 builder, &key_blob, &key_characteristics);
1983 }
subrahmanyaman05642492022-02-05 07:10:56 +00001984 }
David Drysdale37af4b32021-05-14 16:46:59 +01001985 ASSERT_EQ(result, ErrorCode::OK);
1986 ASSERT_GT(key_blob.size(), 0U);
1987
1988 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1989 ASSERT_GT(cert_chain_.size(), 0);
1990 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1991
1992 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1993 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001994 // Some tags are optional, so don't require them to be in the enforcements.
1995 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001996 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1997 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1998 }
1999
2000 // Verifying the attestation record will check for the specific tag because
2001 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002002 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2003 hw_enforced, SecLevel(),
2004 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002005
2006 CheckedDeleteKey(&key_blob);
2007 }
2008
David Drysdalec53b7d92021-10-11 12:35:58 +01002009 // Collection of invalid attestation ID tags.
2010 auto invalid_tags =
2011 AuthorizationSetBuilder()
2012 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
2013 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
2014 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
2015 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
2016 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
2017 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
2018 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
2019 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01002020 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01002021 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01002022 vector<uint8_t> key_blob;
2023 vector<KeyCharacteristics> key_characteristics;
2024 AuthorizationSetBuilder builder =
2025 AuthorizationSetBuilder()
2026 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002027 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01002028 .Digest(Digest::NONE)
2029 .AttestationChallenge(challenge)
2030 .AttestationApplicationId(app_id)
2031 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2032 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2033 .SetDefaultValidity();
2034 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002035
2036 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
2037 // Strongbox may not support factory provisioned attestation key.
2038 if (SecLevel() == SecurityLevel::STRONGBOX) {
2039 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2040 error = GenerateKeyWithSelfSignedAttestKey(
2041 AuthorizationSetBuilder()
2042 .EcdsaKey(EcCurve::P_256)
2043 .AttestKey()
2044 .SetDefaultValidity(), /* attest key params */
2045 builder, &key_blob, &key_characteristics);
2046 }
2047 }
2048 ASSERT_EQ(error, ErrorCode::CANNOT_ATTEST_IDS);
David Drysdale37af4b32021-05-14 16:46:59 +01002049 }
2050}
2051
2052/*
David Drysdalec53b7d92021-10-11 12:35:58 +01002053 * NewKeyGenerationTest.EcdsaAttestationIdTags
2054 *
2055 * Verifies that creation of an attested ECDSA key includes various ID tags in the
2056 * attestation extension.
2057 */
2058TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
David Drysdale555ba002022-05-03 18:48:57 +01002059 if (is_gsi_image()) {
2060 // GSI sets up a standard set of device identifiers that may not match
2061 // the device identifiers held by the device.
2062 GTEST_SKIP() << "Test not applicable under GSI";
2063 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002064 auto challenge = "hello";
2065 auto app_id = "foo";
2066 auto subject = "cert subj 2";
2067 vector<uint8_t> subject_der(make_name_from_str(subject));
2068 uint64_t serial_int = 0x1010;
2069 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2070 const AuthorizationSetBuilder base_builder =
2071 AuthorizationSetBuilder()
2072 .Authorization(TAG_NO_AUTH_REQUIRED)
2073 .EcdsaSigningKey(EcCurve::P_256)
2074 .Digest(Digest::NONE)
2075 .AttestationChallenge(challenge)
2076 .AttestationApplicationId(app_id)
2077 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2078 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2079 .SetDefaultValidity();
2080
2081 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
2082 auto extra_tags = AuthorizationSetBuilder();
2083 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
2084 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
2085 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
Tri Vo799e4352022-11-07 17:23:50 -08002086 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
David Drysdalec53b7d92021-10-11 12:35:58 +01002087 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
2088 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
2089
2090 for (const KeyParameter& tag : extra_tags) {
2091 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2092 vector<uint8_t> key_blob;
2093 vector<KeyCharacteristics> key_characteristics;
2094 AuthorizationSetBuilder builder = base_builder;
2095 builder.push_back(tag);
2096 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002097 // Strongbox may not support factory provisioned attestation key.
2098 if (SecLevel() == SecurityLevel::STRONGBOX) {
2099 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2100 }
Prashant Patil88ad1892022-03-15 16:31:02 +00002101 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2102 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01002103 continue;
2104 }
2105 ASSERT_EQ(result, ErrorCode::OK);
2106 ASSERT_GT(key_blob.size(), 0U);
2107
2108 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2109 ASSERT_GT(cert_chain_.size(), 0);
2110 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2111
2112 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2113 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2114
2115 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2116 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2117 // attestation extension should contain them, so make sure the extra tag is added.
2118 hw_enforced.push_back(tag);
2119
2120 // Verifying the attestation record will check for the specific tag because
2121 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002122 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2123 hw_enforced, SecLevel(),
2124 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002125
2126 CheckedDeleteKey(&key_blob);
2127 }
2128}
2129
2130/*
David Drysdale565ccc72021-10-11 12:49:50 +01002131 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2132 *
2133 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2134 */
2135TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2136 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002137 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002138 auto challenge = "hello";
2139 auto subject = "cert subj 2";
2140 vector<uint8_t> subject_der(make_name_from_str(subject));
2141 uint64_t serial_int = 0x1010;
2142 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002143 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002144 AuthorizationSetBuilder()
2145 .Authorization(TAG_NO_AUTH_REQUIRED)
2146 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2147 .EcdsaSigningKey(EcCurve::P_256)
2148 .Digest(Digest::NONE)
2149 .AttestationChallenge(challenge)
2150 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2151 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2152 .AttestationApplicationId(app_id)
2153 .Authorization(TAG_CREATION_DATETIME, datetime)
2154 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002155 if (reset) {
2156 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2157 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002158 auto result = GenerateKey(builder);
2159 if (SecLevel() == SecurityLevel::STRONGBOX) {
2160 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2161 result = GenerateKeyWithSelfSignedAttestKey(
2162 AuthorizationSetBuilder()
2163 .EcdsaKey(EcCurve::P_256)
2164 .AttestKey()
2165 .SetDefaultValidity(), /* attest key params */
2166 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2167 }
2168 }
2169 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002170 ASSERT_GT(key_blob_.size(), 0U);
2171
2172 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2173 ASSERT_GT(cert_chain_.size(), 0);
2174 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2175
2176 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2177 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2178
2179 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002180 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2181 hw_enforced, SecLevel(),
2182 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002183 EXPECT_GT(unique_id->size(), 0);
2184 CheckedDeleteKey();
2185 };
2186
2187 // Generate unique ID
2188 auto app_id = "foo";
2189 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2190 vector<uint8_t> unique_id;
2191 get_unique_id(app_id, cert_date, &unique_id);
2192
2193 // Generating a new key with the same parameters should give the same unique ID.
2194 vector<uint8_t> unique_id2;
2195 get_unique_id(app_id, cert_date, &unique_id2);
2196 EXPECT_EQ(unique_id, unique_id2);
2197
2198 // Generating a new key with a slightly different date should give the same unique ID.
2199 uint64_t rounded_date = cert_date / 2592000000LLU;
2200 uint64_t min_date = rounded_date * 2592000000LLU;
2201 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2202
2203 vector<uint8_t> unique_id3;
2204 get_unique_id(app_id, min_date, &unique_id3);
2205 EXPECT_EQ(unique_id, unique_id3);
2206
2207 vector<uint8_t> unique_id4;
2208 get_unique_id(app_id, max_date, &unique_id4);
2209 EXPECT_EQ(unique_id, unique_id4);
2210
2211 // A different attestation application ID should yield a different unique ID.
2212 auto app_id2 = "different_foo";
2213 vector<uint8_t> unique_id5;
2214 get_unique_id(app_id2, cert_date, &unique_id5);
2215 EXPECT_NE(unique_id, unique_id5);
2216
2217 // A radically different date should yield a different unique ID.
2218 vector<uint8_t> unique_id6;
2219 get_unique_id(app_id, 1611621648000, &unique_id6);
2220 EXPECT_NE(unique_id, unique_id6);
2221
2222 vector<uint8_t> unique_id7;
2223 get_unique_id(app_id, max_date + 1, &unique_id7);
2224 EXPECT_NE(unique_id, unique_id7);
2225
2226 vector<uint8_t> unique_id8;
2227 get_unique_id(app_id, min_date - 1, &unique_id8);
2228 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002229
2230 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2231 vector<uint8_t> unique_id9;
2232 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2233 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002234}
2235
2236/*
David Drysdale37af4b32021-05-14 16:46:59 +01002237 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2238 *
2239 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2240 */
2241TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2242 auto challenge = "hello";
2243 auto attest_app_id = "foo";
2244 auto subject = "cert subj 2";
2245 vector<uint8_t> subject_der(make_name_from_str(subject));
2246 uint64_t serial_int = 0x1010;
2247 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2248
2249 // Earlier versions of the attestation extension schema included a slot:
2250 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2251 // This should never have been included, and should never be filled in.
2252 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2253 // to confirm that this field never makes it into the attestation extension.
2254 vector<uint8_t> key_blob;
2255 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002256 auto builder = AuthorizationSetBuilder()
2257 .Authorization(TAG_NO_AUTH_REQUIRED)
2258 .EcdsaSigningKey(EcCurve::P_256)
2259 .Digest(Digest::NONE)
2260 .AttestationChallenge(challenge)
2261 .AttestationApplicationId(attest_app_id)
2262 .Authorization(TAG_APPLICATION_ID, "client_id")
2263 .Authorization(TAG_APPLICATION_DATA, "appdata")
2264 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2265 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2266 .SetDefaultValidity();
2267
2268 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002269 // Strongbox may not support factory provisioned attestation key.
2270 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002271 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2272 result = GenerateKeyWithSelfSignedAttestKey(
2273 AuthorizationSetBuilder()
2274 .EcdsaKey(EcCurve::P_256)
2275 .AttestKey()
2276 .SetDefaultValidity(), /* attest key params */
2277 builder, &key_blob, &key_characteristics);
2278 }
subrahmanyaman05642492022-02-05 07:10:56 +00002279 }
David Drysdale37af4b32021-05-14 16:46:59 +01002280 ASSERT_EQ(result, ErrorCode::OK);
2281 ASSERT_GT(key_blob.size(), 0U);
2282
2283 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2284 ASSERT_GT(cert_chain_.size(), 0);
2285 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2286
2287 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2288 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002289 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2290 hw_enforced, SecLevel(),
2291 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002292
2293 // Check that the app id is not in the cert.
2294 string app_id = "clientid";
2295 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2296 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2297 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2298 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2299 cert_chain_[0].encodedCertificate.end());
2300
2301 CheckedDeleteKey(&key_blob);
2302}
2303
2304/*
Selene Huang4f64c222021-04-13 19:54:36 -07002305 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2306 *
2307 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2308 * the key will generate a self signed attestation.
2309 */
2310TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002311 auto subject = "cert subj 2";
2312 vector<uint8_t> subject_der(make_name_from_str(subject));
2313
2314 uint64_t serial_int = 0x123456FFF1234;
2315 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2316
David Drysdaledf09e542021-06-08 15:46:11 +01002317 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002318 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002319 vector<uint8_t> key_blob;
2320 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002321 ASSERT_EQ(ErrorCode::OK,
2322 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002323 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002324 .Digest(Digest::NONE)
2325 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2326 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2327 .SetDefaultValidity(),
2328 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002329 ASSERT_GT(key_blob.size(), 0U);
2330 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002331 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002332
2333 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2334
2335 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002336 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002337
2338 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2339 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002340 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002341
2342 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2343 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2344
2345 CheckedDeleteKey(&key_blob);
2346 }
2347}
2348
2349/*
2350 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2351 *
2352 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2353 * app id must also be provided or else it will fail.
2354 */
2355TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2356 auto challenge = "hello";
2357 vector<uint8_t> key_blob;
2358 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002359 auto builder = AuthorizationSetBuilder()
2360 .EcdsaSigningKey(EcCurve::P_256)
2361 .Digest(Digest::NONE)
2362 .AttestationChallenge(challenge)
2363 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002364
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002365 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002366 // Strongbox may not support factory provisioned attestation key.
2367 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002368 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2369 result = GenerateKeyWithSelfSignedAttestKey(
2370 AuthorizationSetBuilder()
2371 .EcdsaKey(EcCurve::P_256)
2372 .AttestKey()
2373 .SetDefaultValidity(), /* attest key params */
2374 builder, &key_blob, &key_characteristics);
2375 }
subrahmanyaman05642492022-02-05 07:10:56 +00002376 }
2377 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002378}
2379
2380/*
2381 * NewKeyGenerationTest.EcdsaIgnoreAppId
2382 *
2383 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2384 * any appid will be ignored, and keymint will generate a self sign certificate.
2385 */
2386TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2387 auto app_id = "foo";
2388
David Drysdaledf09e542021-06-08 15:46:11 +01002389 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002390 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002391 vector<uint8_t> key_blob;
2392 vector<KeyCharacteristics> key_characteristics;
2393 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002394 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002395 .Digest(Digest::NONE)
2396 .AttestationApplicationId(app_id)
2397 .SetDefaultValidity(),
2398 &key_blob, &key_characteristics));
2399
2400 ASSERT_GT(key_blob.size(), 0U);
2401 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002402 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002403
2404 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2405
2406 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002407 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002408
2409 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2410 ASSERT_EQ(cert_chain_.size(), 1);
2411
2412 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2413 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2414
2415 CheckedDeleteKey(&key_blob);
2416 }
2417}
2418
2419/*
2420 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2421 *
2422 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2423 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2424 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2425 * to specify how many following bytes will be used to encode the length.
2426 */
2427TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2428 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002429 std::vector<uint32_t> app_id_lengths{143, 258};
2430
2431 for (uint32_t length : app_id_lengths) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002432 SCOPED_TRACE(testing::Message() << "app_id_len=" << length);
Selene Huang4f64c222021-04-13 19:54:36 -07002433 const string app_id(length, 'a');
2434 vector<uint8_t> key_blob;
2435 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002436 auto builder = AuthorizationSetBuilder()
2437 .Authorization(TAG_NO_AUTH_REQUIRED)
2438 .EcdsaSigningKey(EcCurve::P_256)
2439 .Digest(Digest::NONE)
2440 .AttestationChallenge(challenge)
2441 .AttestationApplicationId(app_id)
2442 .SetDefaultValidity();
2443
2444 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002445 // Strongbox may not support factory provisioned attestation key.
2446 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002447 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2448 result = GenerateKeyWithSelfSignedAttestKey(
2449 AuthorizationSetBuilder()
2450 .EcdsaKey(EcCurve::P_256)
2451 .AttestKey()
2452 .SetDefaultValidity(), /* attest key params */
2453 builder, &key_blob, &key_characteristics);
2454 }
subrahmanyaman05642492022-02-05 07:10:56 +00002455 }
2456 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002457 ASSERT_GT(key_blob.size(), 0U);
2458 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002459 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002460
2461 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2462
2463 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002464 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002465
2466 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2467 ASSERT_GT(cert_chain_.size(), 0);
2468
2469 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2470 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002471 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002472 sw_enforced, hw_enforced, SecLevel(),
2473 cert_chain_[0].encodedCertificate));
2474
2475 CheckedDeleteKey(&key_blob);
2476 }
2477}
2478
2479/*
Qi Wud22ec842020-11-26 13:27:53 +08002480 * NewKeyGenerationTest.LimitedUsageEcdsa
2481 *
2482 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2483 * resulting keys have correct characteristics.
2484 */
2485TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002486 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002487 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Qi Wud22ec842020-11-26 13:27:53 +08002488 vector<uint8_t> key_blob;
2489 vector<KeyCharacteristics> key_characteristics;
2490 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002491 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002492 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002493 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2494 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002495 &key_blob, &key_characteristics));
2496
2497 ASSERT_GT(key_blob.size(), 0U);
2498 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002499 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002500
2501 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2502
2503 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002504 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002505
2506 // Check the usage count limit tag appears in the authorizations.
2507 AuthorizationSet auths;
2508 for (auto& entry : key_characteristics) {
2509 auths.push_back(AuthorizationSet(entry.authorizations));
2510 }
2511 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2512 << "key usage count limit " << 1U << " missing";
2513
2514 CheckedDeleteKey(&key_blob);
2515 }
2516}
2517
2518/*
Selene Huang31ab4042020-04-29 04:22:39 -07002519 * NewKeyGenerationTest.EcdsaDefaultSize
2520 *
David Drysdaledf09e542021-06-08 15:46:11 +01002521 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002522 * UNSUPPORTED_KEY_SIZE.
2523 */
2524TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2525 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2526 GenerateKey(AuthorizationSetBuilder()
2527 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2528 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002529 .Digest(Digest::NONE)
2530 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002531}
2532
2533/*
David Drysdale42fe1892021-10-14 14:43:46 +01002534 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002535 *
David Drysdale42fe1892021-10-14 14:43:46 +01002536 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002537 * UNSUPPORTED_KEY_SIZE.
2538 */
David Drysdale42fe1892021-10-14 14:43:46 +01002539TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002540 for (auto curve : InvalidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002541 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07002542 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002543 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002544 auto result = GenerateKey(AuthorizationSetBuilder()
2545 .EcdsaSigningKey(curve)
2546 .Digest(Digest::NONE)
2547 .SetDefaultValidity(),
2548 &key_blob, &key_characteristics);
2549 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2550 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002551 }
2552
David Drysdaledf09e542021-06-08 15:46:11 +01002553 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2554 GenerateKey(AuthorizationSetBuilder()
2555 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2556 .Authorization(TAG_KEY_SIZE, 190)
2557 .SigningKey()
2558 .Digest(Digest::NONE)
2559 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002560}
2561
2562/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002563 * NewKeyGenerationTest.EcdsaMissingCurve
2564 *
2565 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
2566 */
2567TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2568 if (AidlVersion() < 2) {
2569 /*
2570 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2571 * However, this was not checked at the time so we can only be strict about checking this
2572 * for implementations of KeyMint version 2 and above.
2573 */
2574 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
2575 }
2576 /* If EC_CURVE not provided, generateKey
2577 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2578 */
2579 auto result = GenerateKey(
2580 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2581 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2582 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2583}
2584
2585/*
Selene Huang31ab4042020-04-29 04:22:39 -07002586 * NewKeyGenerationTest.EcdsaMismatchKeySize
2587 *
2588 * Verifies that specifying mismatched key size and curve for EC key generation returns
2589 * INVALID_ARGUMENT.
2590 */
2591TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002592 if (SecLevel() == SecurityLevel::STRONGBOX) {
2593 GTEST_SKIP() << "Test not applicable to StrongBox device";
2594 }
Selene Huang31ab4042020-04-29 04:22:39 -07002595
David Drysdaledf09e542021-06-08 15:46:11 +01002596 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002597 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002598 .Authorization(TAG_KEY_SIZE, 224)
2599 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002600 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002601 .Digest(Digest::NONE)
2602 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002603 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002604}
2605
2606/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002607 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002608 *
2609 * Verifies that keymint does not support any curve designated as unsupported.
2610 */
2611TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2612 Digest digest;
2613 if (SecLevel() == SecurityLevel::STRONGBOX) {
2614 digest = Digest::SHA_2_256;
2615 } else {
2616 digest = Digest::SHA_2_512;
2617 }
2618 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002619 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Janis Danisevskis164bb872021-02-09 11:30:25 -08002620 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2621 .EcdsaSigningKey(curve)
2622 .Digest(digest)
2623 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002624 << "Failed to generate key on curve: " << curve;
2625 CheckedDeleteKey();
2626 }
2627}
2628
2629/*
2630 * NewKeyGenerationTest.Hmac
2631 *
2632 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2633 * characteristics.
2634 */
2635TEST_P(NewKeyGenerationTest, Hmac) {
2636 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002637 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07002638 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002639 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002640 constexpr size_t key_size = 128;
2641 ASSERT_EQ(ErrorCode::OK,
2642 GenerateKey(
2643 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2644 TAG_MIN_MAC_LENGTH, 128),
2645 &key_blob, &key_characteristics));
2646
2647 ASSERT_GT(key_blob.size(), 0U);
2648 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002649 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002650
Shawn Willden7f424372021-01-10 18:06:50 -07002651 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2652 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2653 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2654 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002655
2656 CheckedDeleteKey(&key_blob);
2657 }
2658}
2659
2660/*
Selene Huang4f64c222021-04-13 19:54:36 -07002661 * NewKeyGenerationTest.HmacNoAttestation
2662 *
2663 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2664 * and app id are provided.
2665 */
2666TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2667 auto challenge = "hello";
2668 auto app_id = "foo";
2669
2670 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002671 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang4f64c222021-04-13 19:54:36 -07002672 vector<uint8_t> key_blob;
2673 vector<KeyCharacteristics> key_characteristics;
2674 constexpr size_t key_size = 128;
2675 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2676 .HmacKey(key_size)
2677 .Digest(digest)
2678 .AttestationChallenge(challenge)
2679 .AttestationApplicationId(app_id)
2680 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2681 &key_blob, &key_characteristics));
2682
2683 ASSERT_GT(key_blob.size(), 0U);
2684 ASSERT_EQ(cert_chain_.size(), 0);
2685 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002686 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002687
2688 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2689 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2690 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2691 << "Key size " << key_size << "missing";
2692
2693 CheckedDeleteKey(&key_blob);
2694 }
2695}
2696
2697/*
Qi Wud22ec842020-11-26 13:27:53 +08002698 * NewKeyGenerationTest.LimitedUsageHmac
2699 *
2700 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2701 * resulting keys have correct characteristics.
2702 */
2703TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2704 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002705 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Qi Wud22ec842020-11-26 13:27:53 +08002706 vector<uint8_t> key_blob;
2707 vector<KeyCharacteristics> key_characteristics;
2708 constexpr size_t key_size = 128;
2709 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2710 .HmacKey(key_size)
2711 .Digest(digest)
2712 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2713 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2714 &key_blob, &key_characteristics));
2715
2716 ASSERT_GT(key_blob.size(), 0U);
2717 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002718 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002719
2720 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2721 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2722 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2723 << "Key size " << key_size << "missing";
2724
2725 // Check the usage count limit tag appears in the authorizations.
2726 AuthorizationSet auths;
2727 for (auto& entry : key_characteristics) {
2728 auths.push_back(AuthorizationSet(entry.authorizations));
2729 }
2730 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2731 << "key usage count limit " << 1U << " missing";
2732
2733 CheckedDeleteKey(&key_blob);
2734 }
2735}
2736
2737/*
Selene Huang31ab4042020-04-29 04:22:39 -07002738 * NewKeyGenerationTest.HmacCheckKeySizes
2739 *
2740 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2741 */
2742TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2743 for (size_t key_size = 0; key_size <= 512; ++key_size) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002744 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002745 if (key_size < 64 || key_size % 8 != 0) {
2746 // To keep this test from being very slow, we only test a random fraction of
2747 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2748 // them, we expect to run ~40 of them in each run.
2749 if (key_size % 8 == 0 || random() % 10 == 0) {
2750 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2751 GenerateKey(AuthorizationSetBuilder()
2752 .HmacKey(key_size)
2753 .Digest(Digest::SHA_2_256)
2754 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2755 << "HMAC key size " << key_size << " invalid";
2756 }
2757 } else {
2758 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2759 .HmacKey(key_size)
2760 .Digest(Digest::SHA_2_256)
2761 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2762 << "Failed to generate HMAC key of size " << key_size;
2763 CheckedDeleteKey();
2764 }
2765 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002766 if (SecLevel() == SecurityLevel::STRONGBOX) {
2767 // STRONGBOX devices must not support keys larger than 512 bits.
2768 size_t key_size = 520;
2769 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2770 GenerateKey(AuthorizationSetBuilder()
2771 .HmacKey(key_size)
2772 .Digest(Digest::SHA_2_256)
2773 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2774 << "HMAC key size " << key_size << " unexpectedly valid";
2775 }
Selene Huang31ab4042020-04-29 04:22:39 -07002776}
2777
2778/*
2779 * NewKeyGenerationTest.HmacCheckMinMacLengths
2780 *
2781 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2782 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2783 * specific MAC length that failed, so reproducing a failed run will be easy.
2784 */
2785TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2786 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002787 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
Selene Huang31ab4042020-04-29 04:22:39 -07002788 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2789 // To keep this test from being very long, we only test a random fraction of
2790 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2791 // we expect to run ~17 of them in each run.
2792 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2793 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2794 GenerateKey(AuthorizationSetBuilder()
2795 .HmacKey(128)
2796 .Digest(Digest::SHA_2_256)
2797 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2798 << "HMAC min mac length " << min_mac_length << " invalid.";
2799 }
2800 } else {
2801 EXPECT_EQ(ErrorCode::OK,
2802 GenerateKey(AuthorizationSetBuilder()
2803 .HmacKey(128)
2804 .Digest(Digest::SHA_2_256)
2805 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2806 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2807 CheckedDeleteKey();
2808 }
2809 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002810
2811 // Minimum MAC length must be no more than 512 bits.
2812 size_t min_mac_length = 520;
2813 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2814 GenerateKey(AuthorizationSetBuilder()
2815 .HmacKey(128)
2816 .Digest(Digest::SHA_2_256)
2817 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2818 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002819}
2820
2821/*
2822 * NewKeyGenerationTest.HmacMultipleDigests
2823 *
2824 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2825 */
2826TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002827 if (SecLevel() == SecurityLevel::STRONGBOX) {
2828 GTEST_SKIP() << "Test not applicable to StrongBox device";
2829 }
Selene Huang31ab4042020-04-29 04:22:39 -07002830
2831 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2832 GenerateKey(AuthorizationSetBuilder()
2833 .HmacKey(128)
2834 .Digest(Digest::SHA1)
2835 .Digest(Digest::SHA_2_256)
2836 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2837}
2838
2839/*
2840 * NewKeyGenerationTest.HmacDigestNone
2841 *
2842 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2843 */
2844TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2845 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2846 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2847 128)));
2848
2849 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2850 GenerateKey(AuthorizationSetBuilder()
2851 .HmacKey(128)
2852 .Digest(Digest::NONE)
2853 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2854}
2855
Selene Huang4f64c222021-04-13 19:54:36 -07002856/*
2857 * NewKeyGenerationTest.AesNoAttestation
2858 *
2859 * Verifies that attestation parameters to AES keys are ignored and generateKey
2860 * will succeed.
2861 */
2862TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2863 auto challenge = "hello";
2864 auto app_id = "foo";
2865
2866 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2867 .Authorization(TAG_NO_AUTH_REQUIRED)
2868 .AesEncryptionKey(128)
2869 .EcbMode()
2870 .Padding(PaddingMode::PKCS7)
2871 .AttestationChallenge(challenge)
2872 .AttestationApplicationId(app_id)));
2873
2874 ASSERT_EQ(cert_chain_.size(), 0);
2875}
2876
2877/*
2878 * NewKeyGenerationTest.TripleDesNoAttestation
2879 *
2880 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2881 * will be successful. No attestation should be generated.
2882 */
2883TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2884 auto challenge = "hello";
2885 auto app_id = "foo";
2886
2887 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2888 .TripleDesEncryptionKey(168)
2889 .BlockMode(BlockMode::ECB)
2890 .Authorization(TAG_NO_AUTH_REQUIRED)
2891 .Padding(PaddingMode::NONE)
2892 .AttestationChallenge(challenge)
2893 .AttestationApplicationId(app_id)));
2894 ASSERT_EQ(cert_chain_.size(), 0);
2895}
2896
Selene Huang31ab4042020-04-29 04:22:39 -07002897INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2898
2899typedef KeyMintAidlTestBase SigningOperationsTest;
2900
2901/*
2902 * SigningOperationsTest.RsaSuccess
2903 *
2904 * Verifies that raw RSA signature operations succeed.
2905 */
2906TEST_P(SigningOperationsTest, RsaSuccess) {
2907 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2908 .RsaSigningKey(2048, 65537)
2909 .Digest(Digest::NONE)
2910 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002911 .Authorization(TAG_NO_AUTH_REQUIRED)
2912 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002913 string message = "12345678901234567890123456789012";
2914 string signature = SignMessage(
2915 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002916 LocalVerifyMessage(message, signature,
2917 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2918}
2919
2920/*
2921 * SigningOperationsTest.RsaAllPaddingsAndDigests
2922 *
2923 * Verifies RSA signature/verification for all padding modes and digests.
2924 */
2925TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2926 auto authorizations = AuthorizationSetBuilder()
2927 .Authorization(TAG_NO_AUTH_REQUIRED)
2928 .RsaSigningKey(2048, 65537)
2929 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2930 .Padding(PaddingMode::NONE)
2931 .Padding(PaddingMode::RSA_PSS)
2932 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2933 .SetDefaultValidity();
2934
2935 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2936
2937 string message(128, 'a');
2938 string corrupt_message(message);
2939 ++corrupt_message[corrupt_message.size() / 2];
2940
2941 for (auto padding :
2942 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2943 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002944 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002945 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2946 // Digesting only makes sense with padding.
2947 continue;
2948 }
2949
2950 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2951 // PSS requires digesting.
2952 continue;
2953 }
2954
2955 string signature =
2956 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2957 LocalVerifyMessage(message, signature,
2958 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2959 }
2960 }
Selene Huang31ab4042020-04-29 04:22:39 -07002961}
2962
2963/*
2964 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2965 *
Shawn Willden7f424372021-01-10 18:06:50 -07002966 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002967 */
2968TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2969 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2970 .Authorization(TAG_NO_AUTH_REQUIRED)
2971 .RsaSigningKey(2048, 65537)
2972 .Digest(Digest::NONE)
2973 .Padding(PaddingMode::NONE)
2974 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002975 .Authorization(TAG_APPLICATION_DATA, "appdata")
2976 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002977
2978 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2979
Selene Huang31ab4042020-04-29 04:22:39 -07002980 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2981 Begin(KeyPurpose::SIGN,
2982 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2983 AbortIfNeeded();
2984 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2985 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2986 .Digest(Digest::NONE)
2987 .Padding(PaddingMode::NONE)
2988 .Authorization(TAG_APPLICATION_ID, "clientid")));
2989 AbortIfNeeded();
2990 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2991 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2992 .Digest(Digest::NONE)
2993 .Padding(PaddingMode::NONE)
2994 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2995 AbortIfNeeded();
2996 EXPECT_EQ(ErrorCode::OK,
2997 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2998 .Digest(Digest::NONE)
2999 .Padding(PaddingMode::NONE)
3000 .Authorization(TAG_APPLICATION_DATA, "appdata")
3001 .Authorization(TAG_APPLICATION_ID, "clientid")));
3002 AbortIfNeeded();
3003}
3004
3005/*
3006 * SigningOperationsTest.RsaPssSha256Success
3007 *
3008 * Verifies that RSA-PSS signature operations succeed.
3009 */
3010TEST_P(SigningOperationsTest, RsaPssSha256Success) {
3011 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3012 .RsaSigningKey(2048, 65537)
3013 .Digest(Digest::SHA_2_256)
3014 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003015 .Authorization(TAG_NO_AUTH_REQUIRED)
3016 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003017 // Use large message, which won't work without digesting.
3018 string message(1024, 'a');
3019 string signature = SignMessage(
3020 message,
3021 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
3022}
3023
3024/*
3025 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
3026 *
3027 * Verifies that keymint rejects signature operations that specify a padding mode when the key
3028 * supports only unpadded operations.
3029 */
3030TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
3031 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3032 .RsaSigningKey(2048, 65537)
3033 .Digest(Digest::NONE)
3034 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003035 .Padding(PaddingMode::NONE)
3036 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003037 string message = "12345678901234567890123456789012";
3038 string signature;
3039
3040 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3041 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3042 .Digest(Digest::NONE)
3043 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3044}
3045
3046/*
3047 * SigningOperationsTest.NoUserConfirmation
3048 *
3049 * Verifies that keymint rejects signing operations for keys with
3050 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
3051 * presented.
3052 */
3053TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01003054 if (SecLevel() == SecurityLevel::STRONGBOX) {
3055 GTEST_SKIP() << "Test not applicable to StrongBox device";
3056 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08003057 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3058 .RsaSigningKey(1024, 65537)
3059 .Digest(Digest::NONE)
3060 .Padding(PaddingMode::NONE)
3061 .Authorization(TAG_NO_AUTH_REQUIRED)
3062 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
3063 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003064
3065 const string message = "12345678901234567890123456789012";
3066 EXPECT_EQ(ErrorCode::OK,
3067 Begin(KeyPurpose::SIGN,
3068 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3069 string signature;
3070 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
3071}
3072
3073/*
3074 * SigningOperationsTest.RsaPkcs1Sha256Success
3075 *
3076 * Verifies that digested RSA-PKCS1 signature operations succeed.
3077 */
3078TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
3079 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3080 .RsaSigningKey(2048, 65537)
3081 .Digest(Digest::SHA_2_256)
3082 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003083 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3084 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003085 string message(1024, 'a');
3086 string signature = SignMessage(message, AuthorizationSetBuilder()
3087 .Digest(Digest::SHA_2_256)
3088 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3089}
3090
3091/*
3092 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3093 *
3094 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3095 */
3096TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3097 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3098 .RsaSigningKey(2048, 65537)
3099 .Digest(Digest::NONE)
3100 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003101 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3102 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003103 string message(53, 'a');
3104 string signature = SignMessage(message, AuthorizationSetBuilder()
3105 .Digest(Digest::NONE)
3106 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3107}
3108
3109/*
3110 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3111 *
3112 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3113 * given a too-long message.
3114 */
3115TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3116 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3117 .RsaSigningKey(2048, 65537)
3118 .Digest(Digest::NONE)
3119 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003120 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3121 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003122 string message(257, 'a');
3123
3124 EXPECT_EQ(ErrorCode::OK,
3125 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3126 .Digest(Digest::NONE)
3127 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3128 string signature;
3129 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3130}
3131
3132/*
3133 * SigningOperationsTest.RsaPssSha512TooSmallKey
3134 *
3135 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3136 * used with a key that is too small for the message.
3137 *
3138 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3139 * keymint specification requires that salt_size == digest_size, so the message will be
3140 * digest_size * 2 +
3141 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3142 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3143 * for a 1024-bit key.
3144 */
3145TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003146 if (SecLevel() == SecurityLevel::STRONGBOX) {
3147 GTEST_SKIP() << "Test not applicable to StrongBox device";
3148 }
Selene Huang31ab4042020-04-29 04:22:39 -07003149 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3150 .RsaSigningKey(1024, 65537)
3151 .Digest(Digest::SHA_2_512)
3152 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003153 .Padding(PaddingMode::RSA_PSS)
3154 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003155 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3156 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3157 .Digest(Digest::SHA_2_512)
3158 .Padding(PaddingMode::RSA_PSS)));
3159}
3160
3161/*
3162 * SigningOperationsTest.RsaNoPaddingTooLong
3163 *
3164 * Verifies that raw RSA signature operations fail with the correct error code when
3165 * given a too-long message.
3166 */
3167TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3168 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3169 .RsaSigningKey(2048, 65537)
3170 .Digest(Digest::NONE)
3171 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003172 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3173 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003174 // One byte too long
3175 string message(2048 / 8 + 1, 'a');
3176 ASSERT_EQ(ErrorCode::OK,
3177 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3178 .Digest(Digest::NONE)
3179 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3180 string result;
3181 ErrorCode finish_error_code = Finish(message, &result);
3182 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3183 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3184
3185 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3186 message = string(128 * 1024, 'a');
3187 ASSERT_EQ(ErrorCode::OK,
3188 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3189 .Digest(Digest::NONE)
3190 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3191 finish_error_code = Finish(message, &result);
3192 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3193 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3194}
3195
3196/*
3197 * SigningOperationsTest.RsaAbort
3198 *
3199 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3200 * test, but the behavior should be algorithm and purpose-independent.
3201 */
3202TEST_P(SigningOperationsTest, RsaAbort) {
3203 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3204 .RsaSigningKey(2048, 65537)
3205 .Digest(Digest::NONE)
3206 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003207 .Padding(PaddingMode::NONE)
3208 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003209
3210 ASSERT_EQ(ErrorCode::OK,
3211 Begin(KeyPurpose::SIGN,
3212 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3213 EXPECT_EQ(ErrorCode::OK, Abort());
3214
3215 // Another abort should fail
3216 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3217
3218 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003219 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003220}
3221
3222/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003223 * SigningOperationsTest.RsaNonUniqueParams
3224 *
3225 * Verifies that an operation with multiple padding modes is rejected.
3226 */
3227TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3228 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3229 .RsaSigningKey(2048, 65537)
3230 .Digest(Digest::NONE)
3231 .Digest(Digest::SHA1)
3232 .Authorization(TAG_NO_AUTH_REQUIRED)
3233 .Padding(PaddingMode::NONE)
3234 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3235 .SetDefaultValidity()));
3236
3237 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3238 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3239 .Digest(Digest::NONE)
3240 .Padding(PaddingMode::NONE)
3241 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3242
Tommy Chiuc93c4392021-05-11 18:36:50 +08003243 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3244 .Digest(Digest::NONE)
3245 .Digest(Digest::SHA1)
3246 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3247 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003248
3249 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3250 Begin(KeyPurpose::SIGN,
3251 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3252}
3253
3254/*
Selene Huang31ab4042020-04-29 04:22:39 -07003255 * SigningOperationsTest.RsaUnsupportedPadding
3256 *
3257 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3258 * with a padding mode inappropriate for RSA.
3259 */
3260TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3261 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3262 .RsaSigningKey(2048, 65537)
3263 .Authorization(TAG_NO_AUTH_REQUIRED)
3264 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003265 .Padding(PaddingMode::PKCS7)
3266 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003267 ASSERT_EQ(
3268 ErrorCode::UNSUPPORTED_PADDING_MODE,
3269 Begin(KeyPurpose::SIGN,
3270 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003271 CheckedDeleteKey();
3272
3273 ASSERT_EQ(ErrorCode::OK,
3274 GenerateKey(
3275 AuthorizationSetBuilder()
3276 .RsaSigningKey(2048, 65537)
3277 .Authorization(TAG_NO_AUTH_REQUIRED)
3278 .Digest(Digest::SHA_2_256 /* supported digest */)
3279 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3280 .SetDefaultValidity()));
3281 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3282 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3283 .Digest(Digest::SHA_2_256)
3284 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003285}
3286
3287/*
3288 * SigningOperationsTest.RsaPssNoDigest
3289 *
3290 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3291 */
3292TEST_P(SigningOperationsTest, RsaNoDigest) {
3293 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3294 .RsaSigningKey(2048, 65537)
3295 .Authorization(TAG_NO_AUTH_REQUIRED)
3296 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003297 .Padding(PaddingMode::RSA_PSS)
3298 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003299 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3300 Begin(KeyPurpose::SIGN,
3301 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3302
3303 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3304 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3305}
3306
3307/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003308 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003309 *
3310 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3311 * supported in some cases (as validated in other tests), but a mode must be specified.
3312 */
3313TEST_P(SigningOperationsTest, RsaNoPadding) {
3314 // Padding must be specified
3315 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3316 .RsaKey(2048, 65537)
3317 .Authorization(TAG_NO_AUTH_REQUIRED)
3318 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003319 .Digest(Digest::NONE)
3320 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003321 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3322 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3323}
3324
3325/*
3326 * SigningOperationsTest.RsaShortMessage
3327 *
3328 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3329 */
3330TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3331 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3332 .Authorization(TAG_NO_AUTH_REQUIRED)
3333 .RsaSigningKey(2048, 65537)
3334 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003335 .Padding(PaddingMode::NONE)
3336 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003337
3338 // Barely shorter
3339 string message(2048 / 8 - 1, 'a');
3340 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3341
3342 // Much shorter
3343 message = "a";
3344 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3345}
3346
3347/*
3348 * SigningOperationsTest.RsaSignWithEncryptionKey
3349 *
3350 * Verifies that RSA encryption keys cannot be used to sign.
3351 */
3352TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3353 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3354 .Authorization(TAG_NO_AUTH_REQUIRED)
3355 .RsaEncryptionKey(2048, 65537)
3356 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003357 .Padding(PaddingMode::NONE)
3358 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003359 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3360 Begin(KeyPurpose::SIGN,
3361 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3362}
3363
3364/*
3365 * SigningOperationsTest.RsaSignTooLargeMessage
3366 *
3367 * Verifies that attempting a raw signature of a message which is the same length as the key,
3368 * but numerically larger than the public modulus, fails with the correct error.
3369 */
3370TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3371 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3372 .Authorization(TAG_NO_AUTH_REQUIRED)
3373 .RsaSigningKey(2048, 65537)
3374 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003375 .Padding(PaddingMode::NONE)
3376 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003377
3378 // Largest possible message will always be larger than the public modulus.
3379 string message(2048 / 8, static_cast<char>(0xff));
3380 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3381 .Authorization(TAG_NO_AUTH_REQUIRED)
3382 .Digest(Digest::NONE)
3383 .Padding(PaddingMode::NONE)));
3384 string signature;
3385 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3386}
3387
3388/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003389 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3390 *
David Drysdale42fe1892021-10-14 14:43:46 +01003391 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003392 */
3393TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003394
3395 string message = "1234567890";
3396 string corrupt_message = "2234567890";
3397 for (auto curve : ValidCurves()) {
3398 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003399 // Ed25519 only allows Digest::NONE.
3400 auto digests = (curve == EcCurve::CURVE_25519)
3401 ? std::vector<Digest>(1, Digest::NONE)
3402 : ValidDigests(true /* withNone */, false /* withMD5 */);
3403
David Drysdaledf8f52e2021-05-06 08:10:58 +01003404 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3405 .Authorization(TAG_NO_AUTH_REQUIRED)
3406 .EcdsaSigningKey(curve)
3407 .Digest(digests)
3408 .SetDefaultValidity());
3409 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3410 if (error != ErrorCode::OK) {
3411 continue;
3412 }
3413
3414 for (auto digest : digests) {
3415 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3416 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3417 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3418 }
3419
3420 auto rc = DeleteKey();
3421 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3422 }
3423}
3424
3425/*
Selene Huang31ab4042020-04-29 04:22:39 -07003426 * SigningOperationsTest.EcdsaAllCurves
3427 *
David Drysdale42fe1892021-10-14 14:43:46 +01003428 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003429 */
3430TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3431 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003432 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3433 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003434 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3435 .Authorization(TAG_NO_AUTH_REQUIRED)
3436 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003437 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003438 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003439 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3440 if (error != ErrorCode::OK) continue;
3441
3442 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003443 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003444 CheckedDeleteKey();
3445 }
3446}
3447
3448/*
David Drysdale42fe1892021-10-14 14:43:46 +01003449 * SigningOperationsTest.EcdsaCurve25519
3450 *
3451 * Verifies that ECDSA operations succeed with curve25519.
3452 */
3453TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3454 if (!Curve25519Supported()) {
3455 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3456 }
3457
3458 EcCurve curve = EcCurve::CURVE_25519;
3459 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3460 .Authorization(TAG_NO_AUTH_REQUIRED)
3461 .EcdsaSigningKey(curve)
3462 .Digest(Digest::NONE)
3463 .SetDefaultValidity());
3464 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3465
3466 string message(1024, 'a');
3467 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3468 CheckedDeleteKey();
3469}
3470
3471/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003472 * SigningOperationsTest.EcdsaCurve25519MaxSize
3473 *
3474 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3475 */
3476TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3477 if (!Curve25519Supported()) {
3478 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3479 }
3480
3481 EcCurve curve = EcCurve::CURVE_25519;
3482 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3483 .Authorization(TAG_NO_AUTH_REQUIRED)
3484 .EcdsaSigningKey(curve)
3485 .Digest(Digest::NONE)
3486 .SetDefaultValidity());
3487 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3488
3489 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3490
3491 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3492 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3493 string message(msg_size, 'a');
3494
3495 // Attempt to sign via Begin+Finish.
3496 AuthorizationSet out_params;
3497 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3498 EXPECT_TRUE(out_params.empty());
3499 string signature;
3500 auto result = Finish(message, &signature);
3501 EXPECT_EQ(result, ErrorCode::OK);
3502 LocalVerifyMessage(message, signature, params);
3503
3504 // Attempt to sign via Begin+Update+Finish
3505 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3506 EXPECT_TRUE(out_params.empty());
3507 string output;
3508 result = Update(message, &output);
3509 EXPECT_EQ(result, ErrorCode::OK);
3510 EXPECT_EQ(output.size(), 0);
3511 string signature2;
3512 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3513 LocalVerifyMessage(message, signature2, params);
3514 }
3515
3516 CheckedDeleteKey();
3517}
3518
3519/*
3520 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3521 *
3522 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3523 */
3524TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3525 if (!Curve25519Supported()) {
3526 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3527 }
3528
3529 EcCurve curve = EcCurve::CURVE_25519;
3530 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3531 .Authorization(TAG_NO_AUTH_REQUIRED)
3532 .EcdsaSigningKey(curve)
3533 .Digest(Digest::NONE)
3534 .SetDefaultValidity());
3535 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3536
3537 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3538
3539 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3540 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3541 string message(msg_size, 'a');
3542
3543 // Attempt to sign via Begin+Finish.
3544 AuthorizationSet out_params;
3545 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3546 EXPECT_TRUE(out_params.empty());
3547 string signature;
3548 auto result = Finish(message, &signature);
3549 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3550
3551 // Attempt to sign via Begin+Update (but never get to Finish)
3552 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3553 EXPECT_TRUE(out_params.empty());
3554 string output;
3555 result = Update(message, &output);
3556 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3557 }
3558
3559 CheckedDeleteKey();
3560}
3561
3562/*
Selene Huang31ab4042020-04-29 04:22:39 -07003563 * SigningOperationsTest.EcdsaNoDigestHugeData
3564 *
3565 * Verifies that ECDSA operations support very large messages, even without digesting. This
3566 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3567 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3568 * the framework.
3569 */
3570TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3571 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3572 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003573 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003574 .Digest(Digest::NONE)
3575 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003576 string message(1 * 1024, 'a');
3577 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3578}
3579
3580/*
3581 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3582 *
3583 * Verifies that using an EC key requires the correct app ID/data.
3584 */
3585TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3586 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3587 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003588 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003589 .Digest(Digest::NONE)
3590 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003591 .Authorization(TAG_APPLICATION_DATA, "appdata")
3592 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003593
3594 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3595
Selene Huang31ab4042020-04-29 04:22:39 -07003596 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3597 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3598 AbortIfNeeded();
3599 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3600 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3601 .Digest(Digest::NONE)
3602 .Authorization(TAG_APPLICATION_ID, "clientid")));
3603 AbortIfNeeded();
3604 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3605 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3606 .Digest(Digest::NONE)
3607 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3608 AbortIfNeeded();
3609 EXPECT_EQ(ErrorCode::OK,
3610 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3611 .Digest(Digest::NONE)
3612 .Authorization(TAG_APPLICATION_DATA, "appdata")
3613 .Authorization(TAG_APPLICATION_ID, "clientid")));
3614 AbortIfNeeded();
3615}
3616
3617/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003618 * SigningOperationsTest.EcdsaIncompatibleDigest
3619 *
3620 * Verifies that using an EC key requires compatible digest.
3621 */
3622TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3623 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3624 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003625 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003626 .Digest(Digest::NONE)
3627 .Digest(Digest::SHA1)
3628 .SetDefaultValidity()));
3629 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3630 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3631 AbortIfNeeded();
3632}
3633
3634/*
Selene Huang31ab4042020-04-29 04:22:39 -07003635 * SigningOperationsTest.AesEcbSign
3636 *
3637 * Verifies that attempts to use AES keys to sign fail in the correct way.
3638 */
3639TEST_P(SigningOperationsTest, AesEcbSign) {
3640 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3641 .Authorization(TAG_NO_AUTH_REQUIRED)
3642 .SigningKey()
3643 .AesEncryptionKey(128)
3644 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3645
3646 AuthorizationSet out_params;
3647 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3648 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3649 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3650 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3651}
3652
3653/*
3654 * SigningOperationsTest.HmacAllDigests
3655 *
3656 * Verifies that HMAC works with all digests.
3657 */
3658TEST_P(SigningOperationsTest, HmacAllDigests) {
3659 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003660 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003661 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3662 .Authorization(TAG_NO_AUTH_REQUIRED)
3663 .HmacKey(128)
3664 .Digest(digest)
3665 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3666 << "Failed to create HMAC key with digest " << digest;
3667 string message = "12345678901234567890123456789012";
3668 string signature = MacMessage(message, digest, 160);
3669 EXPECT_EQ(160U / 8U, signature.size())
3670 << "Failed to sign with HMAC key with digest " << digest;
3671 CheckedDeleteKey();
3672 }
3673}
3674
3675/*
3676 * SigningOperationsTest.HmacSha256TooLargeMacLength
3677 *
3678 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3679 * digest size.
3680 */
3681TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3682 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3683 .Authorization(TAG_NO_AUTH_REQUIRED)
3684 .HmacKey(128)
3685 .Digest(Digest::SHA_2_256)
3686 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3687 AuthorizationSet output_params;
3688 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3689 AuthorizationSetBuilder()
3690 .Digest(Digest::SHA_2_256)
3691 .Authorization(TAG_MAC_LENGTH, 264),
3692 &output_params));
3693}
3694
3695/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003696 * SigningOperationsTest.HmacSha256InvalidMacLength
3697 *
3698 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3699 * not a multiple of 8.
3700 */
3701TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3702 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3703 .Authorization(TAG_NO_AUTH_REQUIRED)
3704 .HmacKey(128)
3705 .Digest(Digest::SHA_2_256)
3706 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3707 AuthorizationSet output_params;
3708 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3709 AuthorizationSetBuilder()
3710 .Digest(Digest::SHA_2_256)
3711 .Authorization(TAG_MAC_LENGTH, 161),
3712 &output_params));
3713}
3714
3715/*
Selene Huang31ab4042020-04-29 04:22:39 -07003716 * SigningOperationsTest.HmacSha256TooSmallMacLength
3717 *
3718 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3719 * specified minimum MAC length.
3720 */
3721TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3722 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3723 .Authorization(TAG_NO_AUTH_REQUIRED)
3724 .HmacKey(128)
3725 .Digest(Digest::SHA_2_256)
3726 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3727 AuthorizationSet output_params;
3728 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3729 AuthorizationSetBuilder()
3730 .Digest(Digest::SHA_2_256)
3731 .Authorization(TAG_MAC_LENGTH, 120),
3732 &output_params));
3733}
3734
3735/*
3736 * SigningOperationsTest.HmacRfc4231TestCase3
3737 *
3738 * Validates against the test vectors from RFC 4231 test case 3.
3739 */
3740TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3741 string key(20, 0xaa);
3742 string message(50, 0xdd);
3743 uint8_t sha_224_expected[] = {
3744 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3745 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3746 };
3747 uint8_t sha_256_expected[] = {
3748 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3749 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3750 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3751 };
3752 uint8_t sha_384_expected[] = {
3753 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3754 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3755 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3756 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3757 };
3758 uint8_t sha_512_expected[] = {
3759 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3760 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3761 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3762 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3763 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3764 };
3765
3766 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3767 if (SecLevel() != SecurityLevel::STRONGBOX) {
3768 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3769 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3770 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3771 }
3772}
3773
3774/*
3775 * SigningOperationsTest.HmacRfc4231TestCase5
3776 *
3777 * Validates against the test vectors from RFC 4231 test case 5.
3778 */
3779TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3780 string key(20, 0x0c);
3781 string message = "Test With Truncation";
3782
3783 uint8_t sha_224_expected[] = {
3784 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3785 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3786 };
3787 uint8_t sha_256_expected[] = {
3788 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3789 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3790 };
3791 uint8_t sha_384_expected[] = {
3792 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3793 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3794 };
3795 uint8_t sha_512_expected[] = {
3796 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3797 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3798 };
3799
3800 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3801 if (SecLevel() != SecurityLevel::STRONGBOX) {
3802 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3803 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3804 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3805 }
3806}
3807
3808INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3809
3810typedef KeyMintAidlTestBase VerificationOperationsTest;
3811
3812/*
Selene Huang31ab4042020-04-29 04:22:39 -07003813 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3814 *
3815 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3816 */
3817TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3818 string key_material = "HelloThisIsAKey";
3819
3820 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003821 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003822 EXPECT_EQ(ErrorCode::OK,
3823 ImportKey(AuthorizationSetBuilder()
3824 .Authorization(TAG_NO_AUTH_REQUIRED)
3825 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3826 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3827 .Digest(Digest::SHA_2_256)
3828 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3829 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3830 EXPECT_EQ(ErrorCode::OK,
3831 ImportKey(AuthorizationSetBuilder()
3832 .Authorization(TAG_NO_AUTH_REQUIRED)
3833 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3834 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3835 .Digest(Digest::SHA_2_256)
3836 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3837 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3838
3839 string message = "This is a message.";
3840 string signature = SignMessage(
3841 signing_key, message,
3842 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3843
3844 // Signing key should not work.
3845 AuthorizationSet out_params;
3846 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3847 Begin(KeyPurpose::VERIFY, signing_key,
3848 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3849
3850 // Verification key should work.
3851 VerifyMessage(verification_key, message, signature,
3852 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3853
3854 CheckedDeleteKey(&signing_key);
3855 CheckedDeleteKey(&verification_key);
3856}
3857
Prashant Patildec9fdc2021-12-08 15:25:47 +00003858/*
3859 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3860 *
3861 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3862 */
3863TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3864 string key_material = "HelloThisIsAKey";
3865
3866 vector<uint8_t> signing_key, verification_key;
3867 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3868 EXPECT_EQ(ErrorCode::OK,
3869 ImportKey(AuthorizationSetBuilder()
3870 .Authorization(TAG_NO_AUTH_REQUIRED)
3871 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3872 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3873 .Digest(Digest::SHA_2_256)
3874 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3875 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3876 EXPECT_EQ(ErrorCode::OK,
3877 ImportKey(AuthorizationSetBuilder()
3878 .Authorization(TAG_NO_AUTH_REQUIRED)
3879 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3880 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3881 .Digest(Digest::SHA_2_256)
3882 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3883 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3884
3885 string message = "This is a message.";
3886 string signature = SignMessage(
3887 signing_key, message,
3888 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3889
3890 AuthorizationSet begin_out_params;
3891 ASSERT_EQ(ErrorCode::OK,
3892 Begin(KeyPurpose::VERIFY, verification_key,
3893 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3894
3895 string corruptMessage = "This is b message."; // Corrupted message
3896 string output;
3897 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3898
3899 ASSERT_EQ(ErrorCode::OK,
3900 Begin(KeyPurpose::VERIFY, verification_key,
3901 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3902
3903 signature[0] += 1; // Corrupt a signature
3904 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3905
3906 CheckedDeleteKey(&signing_key);
3907 CheckedDeleteKey(&verification_key);
3908}
3909
Selene Huang31ab4042020-04-29 04:22:39 -07003910INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3911
3912typedef KeyMintAidlTestBase ExportKeyTest;
3913
3914/*
3915 * ExportKeyTest.RsaUnsupportedKeyFormat
3916 *
3917 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3918 */
3919// TODO(seleneh) add ExportKey to GenerateKey
3920// check result
3921
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003922class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003923 public:
3924 template <TagType tag_type, Tag tag, typename ValueT>
3925 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3926 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003927 for (auto& entry : key_characteristics_) {
3928 if (entry.securityLevel == SecLevel()) {
3929 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3930 << "Tag " << tag << " with value " << expected
3931 << " not found at security level" << entry.securityLevel;
3932 } else {
3933 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3934 << "Tag " << tag << " found at security level " << entry.securityLevel;
3935 }
Selene Huang31ab4042020-04-29 04:22:39 -07003936 }
3937 }
3938
3939 void CheckOrigin() {
3940 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003941 // Origin isn't a crypto param, but it always lives with them.
3942 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003943 }
3944};
3945
3946/*
3947 * ImportKeyTest.RsaSuccess
3948 *
3949 * Verifies that importing and using an RSA key pair works correctly.
3950 */
3951TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003952 uint32_t key_size;
3953 string key;
3954
3955 if (SecLevel() == SecurityLevel::STRONGBOX) {
3956 key_size = 2048;
3957 key = rsa_2048_key;
3958 } else {
3959 key_size = 1024;
3960 key = rsa_key;
3961 }
3962
Selene Huang31ab4042020-04-29 04:22:39 -07003963 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3964 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003965 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003966 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003967 .Padding(PaddingMode::RSA_PSS)
3968 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003969 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003970
3971 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003972 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003973 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3974 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3975 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3976 CheckOrigin();
3977
3978 string message(1024 / 8, 'a');
3979 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3980 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003981 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003982}
3983
3984/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003985 * ImportKeyTest.RsaSuccessWithoutParams
3986 *
3987 * Verifies that importing and using an RSA key pair without specifying parameters
3988 * works correctly.
3989 */
3990TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3991 uint32_t key_size;
3992 string key;
3993
3994 if (SecLevel() == SecurityLevel::STRONGBOX) {
3995 key_size = 2048;
3996 key = rsa_2048_key;
3997 } else {
3998 key_size = 1024;
3999 key = rsa_key;
4000 }
4001
4002 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4003 .Authorization(TAG_NO_AUTH_REQUIRED)
4004 .SigningKey()
4005 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
4006 .Digest(Digest::SHA_2_256)
4007 .Padding(PaddingMode::RSA_PSS)
4008 .SetDefaultValidity(),
4009 KeyFormat::PKCS8, key));
4010
4011 // Key size and public exponent are determined from the imported key material.
4012 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4013 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4014
4015 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4016 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4017 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4018 CheckOrigin();
4019
4020 string message(1024 / 8, 'a');
4021 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4022 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004023 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004024}
4025
4026/*
Selene Huang31ab4042020-04-29 04:22:39 -07004027 * ImportKeyTest.RsaKeySizeMismatch
4028 *
4029 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
4030 * correct way.
4031 */
4032TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
4033 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4034 ImportKey(AuthorizationSetBuilder()
4035 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
4036 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004037 .Padding(PaddingMode::NONE)
4038 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004039 KeyFormat::PKCS8, rsa_key));
4040}
4041
4042/*
4043 * ImportKeyTest.RsaPublicExponentMismatch
4044 *
4045 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
4046 * fails in the correct way.
4047 */
4048TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
4049 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4050 ImportKey(AuthorizationSetBuilder()
4051 .RsaSigningKey(1024, 3 /* Doesn't match key */)
4052 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004053 .Padding(PaddingMode::NONE)
4054 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004055 KeyFormat::PKCS8, rsa_key));
4056}
4057
4058/*
David Drysdalee60248c2021-10-04 12:54:13 +01004059 * ImportKeyTest.RsaAttestMultiPurposeFail
4060 *
4061 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
4062 */
4063TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004064 if (AidlVersion() < 2) {
4065 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4066 // with other key purposes. However, this was not checked at the time
4067 // so we can only be strict about checking this for implementations of KeyMint
4068 // version 2 and above.
4069 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4070 }
David Drysdalee60248c2021-10-04 12:54:13 +01004071 uint32_t key_size = 2048;
4072 string key = rsa_2048_key;
4073
4074 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4075 ImportKey(AuthorizationSetBuilder()
4076 .Authorization(TAG_NO_AUTH_REQUIRED)
4077 .RsaSigningKey(key_size, 65537)
4078 .AttestKey()
4079 .Digest(Digest::SHA_2_256)
4080 .Padding(PaddingMode::RSA_PSS)
4081 .SetDefaultValidity(),
4082 KeyFormat::PKCS8, key));
4083}
4084
4085/*
Selene Huang31ab4042020-04-29 04:22:39 -07004086 * ImportKeyTest.EcdsaSuccess
4087 *
4088 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4089 */
4090TEST_P(ImportKeyTest, EcdsaSuccess) {
4091 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4092 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004093 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004094 .Digest(Digest::SHA_2_256)
4095 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004096 KeyFormat::PKCS8, ec_256_key));
4097
4098 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004099 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4100 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4101
4102 CheckOrigin();
4103
4104 string message(32, 'a');
4105 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4106 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004107 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004108}
4109
4110/*
4111 * ImportKeyTest.EcdsaP256RFC5915Success
4112 *
4113 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4114 * correctly.
4115 */
4116TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4117 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4118 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004119 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004120 .Digest(Digest::SHA_2_256)
4121 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004122 KeyFormat::PKCS8, ec_256_key_rfc5915));
4123
4124 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004125 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4126 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4127
4128 CheckOrigin();
4129
4130 string message(32, 'a');
4131 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4132 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004133 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004134}
4135
4136/*
4137 * ImportKeyTest.EcdsaP256SEC1Success
4138 *
4139 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4140 */
4141TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4142 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4143 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004144 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004145 .Digest(Digest::SHA_2_256)
4146 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004147 KeyFormat::PKCS8, ec_256_key_sec1));
4148
4149 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004150 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4151 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4152
4153 CheckOrigin();
4154
4155 string message(32, 'a');
4156 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4157 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004158 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004159}
4160
4161/*
4162 * ImportKeyTest.Ecdsa521Success
4163 *
4164 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4165 */
4166TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004167 if (SecLevel() == SecurityLevel::STRONGBOX) {
4168 GTEST_SKIP() << "Test not applicable to StrongBox device";
4169 }
Selene Huang31ab4042020-04-29 04:22:39 -07004170 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4171 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004172 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004173 .Digest(Digest::SHA_2_256)
4174 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004175 KeyFormat::PKCS8, ec_521_key));
4176
4177 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004178 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4179 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4180 CheckOrigin();
4181
4182 string message(32, 'a');
4183 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4184 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004185 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004186}
4187
4188/*
Selene Huang31ab4042020-04-29 04:22:39 -07004189 * ImportKeyTest.EcdsaCurveMismatch
4190 *
4191 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4192 * the correct way.
4193 */
4194TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4195 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4196 ImportKey(AuthorizationSetBuilder()
4197 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004198 .Digest(Digest::NONE)
4199 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004200 KeyFormat::PKCS8, ec_256_key));
4201}
4202
4203/*
David Drysdalee60248c2021-10-04 12:54:13 +01004204 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4205 *
4206 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4207 */
4208TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004209 if (AidlVersion() < 2) {
4210 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4211 // with other key purposes. However, this was not checked at the time
4212 // so we can only be strict about checking this for implementations of KeyMint
4213 // version 2 and above.
4214 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4215 }
David Drysdalee60248c2021-10-04 12:54:13 +01004216 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4217 ImportKey(AuthorizationSetBuilder()
4218 .Authorization(TAG_NO_AUTH_REQUIRED)
4219 .EcdsaSigningKey(EcCurve::P_256)
4220 .AttestKey()
4221 .Digest(Digest::SHA_2_256)
4222 .SetDefaultValidity(),
4223 KeyFormat::PKCS8, ec_256_key));
4224}
4225
4226/*
David Drysdale42fe1892021-10-14 14:43:46 +01004227 * ImportKeyTest.Ed25519RawSuccess
4228 *
4229 * Verifies that importing and using a raw Ed25519 private key works correctly.
4230 */
4231TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4232 if (!Curve25519Supported()) {
4233 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4234 }
4235
4236 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4237 .Authorization(TAG_NO_AUTH_REQUIRED)
4238 .EcdsaSigningKey(EcCurve::CURVE_25519)
4239 .Digest(Digest::NONE)
4240 .SetDefaultValidity(),
4241 KeyFormat::RAW, ed25519_key));
4242 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4243 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4244 CheckOrigin();
4245
4246 // The returned cert should hold the correct public key.
4247 ASSERT_GT(cert_chain_.size(), 0);
4248 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4249 ASSERT_NE(kmKeyCert, nullptr);
4250 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4251 ASSERT_NE(kmPubKey.get(), nullptr);
4252 size_t kmPubKeySize = 32;
4253 uint8_t kmPubKeyData[32];
4254 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4255 ASSERT_EQ(kmPubKeySize, 32);
4256 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4257
4258 string message(32, 'a');
4259 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4260 string signature = SignMessage(message, params);
4261 LocalVerifyMessage(message, signature, params);
4262}
4263
4264/*
4265 * ImportKeyTest.Ed25519Pkcs8Success
4266 *
4267 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4268 */
4269TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4270 if (!Curve25519Supported()) {
4271 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4272 }
4273
4274 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4275 .Authorization(TAG_NO_AUTH_REQUIRED)
4276 .EcdsaSigningKey(EcCurve::CURVE_25519)
4277 .Digest(Digest::NONE)
4278 .SetDefaultValidity(),
4279 KeyFormat::PKCS8, ed25519_pkcs8_key));
4280 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4281 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4282 CheckOrigin();
4283
4284 // The returned cert should hold the correct public key.
4285 ASSERT_GT(cert_chain_.size(), 0);
4286 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4287 ASSERT_NE(kmKeyCert, nullptr);
4288 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4289 ASSERT_NE(kmPubKey.get(), nullptr);
4290 size_t kmPubKeySize = 32;
4291 uint8_t kmPubKeyData[32];
4292 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4293 ASSERT_EQ(kmPubKeySize, 32);
4294 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4295
4296 string message(32, 'a');
4297 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4298 string signature = SignMessage(message, params);
4299 LocalVerifyMessage(message, signature, params);
4300}
4301
4302/*
4303 * ImportKeyTest.Ed25519CurveMismatch
4304 *
4305 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4306 * the correct way.
4307 */
4308TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4309 if (!Curve25519Supported()) {
4310 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4311 }
4312
4313 ASSERT_NE(ErrorCode::OK,
4314 ImportKey(AuthorizationSetBuilder()
4315 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4316 .Digest(Digest::NONE)
4317 .SetDefaultValidity(),
4318 KeyFormat::RAW, ed25519_key));
4319}
4320
4321/*
4322 * ImportKeyTest.Ed25519FormatMismatch
4323 *
4324 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4325 */
4326TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4327 if (!Curve25519Supported()) {
4328 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4329 }
4330
4331 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4332 .EcdsaSigningKey(EcCurve::CURVE_25519)
4333 .Digest(Digest::NONE)
4334 .SetDefaultValidity(),
4335 KeyFormat::PKCS8, ed25519_key));
4336 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4337 .EcdsaSigningKey(EcCurve::CURVE_25519)
4338 .Digest(Digest::NONE)
4339 .SetDefaultValidity(),
4340 KeyFormat::RAW, ed25519_pkcs8_key));
4341}
4342
4343/*
4344 * ImportKeyTest.Ed25519PurposeMismatch
4345 *
4346 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4347 */
4348TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4349 if (!Curve25519Supported()) {
4350 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4351 }
4352
4353 // Can't have both SIGN and ATTEST_KEY
4354 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4355 .EcdsaSigningKey(EcCurve::CURVE_25519)
4356 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4357 .Digest(Digest::NONE)
4358 .SetDefaultValidity(),
4359 KeyFormat::RAW, ed25519_key));
4360 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4361 // PKCS#8 format and so includes an OID).
4362 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4363 .EcdsaKey(EcCurve::CURVE_25519)
4364 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4365 .Digest(Digest::NONE)
4366 .SetDefaultValidity(),
4367 KeyFormat::PKCS8, ed25519_pkcs8_key));
4368}
4369
4370/*
4371 * ImportKeyTest.X25519RawSuccess
4372 *
4373 * Verifies that importing and using a raw X25519 private key works correctly.
4374 */
4375TEST_P(ImportKeyTest, X25519RawSuccess) {
4376 if (!Curve25519Supported()) {
4377 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4378 }
4379
4380 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4381 .Authorization(TAG_NO_AUTH_REQUIRED)
4382 .EcdsaKey(EcCurve::CURVE_25519)
4383 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4384 .SetDefaultValidity(),
4385 KeyFormat::RAW, x25519_key));
4386
4387 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4388 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4389 CheckOrigin();
4390}
4391
4392/*
4393 * ImportKeyTest.X25519Pkcs8Success
4394 *
4395 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4396 */
4397TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4398 if (!Curve25519Supported()) {
4399 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4400 }
4401
4402 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4403 .Authorization(TAG_NO_AUTH_REQUIRED)
4404 .EcdsaKey(EcCurve::CURVE_25519)
4405 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4406 .SetDefaultValidity(),
4407 KeyFormat::PKCS8, x25519_pkcs8_key));
4408
4409 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4410 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4411 CheckOrigin();
4412}
4413
4414/*
4415 * ImportKeyTest.X25519CurveMismatch
4416 *
4417 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4418 * the correct way.
4419 */
4420TEST_P(ImportKeyTest, X25519CurveMismatch) {
4421 if (!Curve25519Supported()) {
4422 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4423 }
4424
4425 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4426 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4427 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4428 .SetDefaultValidity(),
4429 KeyFormat::RAW, x25519_key));
4430}
4431
4432/*
4433 * ImportKeyTest.X25519FormatMismatch
4434 *
4435 * Verifies that importing an X25519 key with an invalid format fails.
4436 */
4437TEST_P(ImportKeyTest, X25519FormatMismatch) {
4438 if (!Curve25519Supported()) {
4439 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4440 }
4441
4442 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4443 .EcdsaKey(EcCurve::CURVE_25519)
4444 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4445 .SetDefaultValidity(),
4446 KeyFormat::PKCS8, x25519_key));
4447 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4448 .EcdsaKey(EcCurve::CURVE_25519)
4449 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4450 .SetDefaultValidity(),
4451 KeyFormat::RAW, x25519_pkcs8_key));
4452}
4453
4454/*
4455 * ImportKeyTest.X25519PurposeMismatch
4456 *
4457 * Verifies that importing an X25519 key pair with an invalid format fails.
4458 */
4459TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4460 if (!Curve25519Supported()) {
4461 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4462 }
4463
4464 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4465 .EcdsaKey(EcCurve::CURVE_25519)
4466 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4467 .SetDefaultValidity(),
4468 KeyFormat::PKCS8, x25519_pkcs8_key));
4469 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4470 .EcdsaSigningKey(EcCurve::CURVE_25519)
4471 .SetDefaultValidity(),
4472 KeyFormat::PKCS8, x25519_pkcs8_key));
4473}
4474
4475/*
Selene Huang31ab4042020-04-29 04:22:39 -07004476 * ImportKeyTest.AesSuccess
4477 *
4478 * Verifies that importing and using an AES key works.
4479 */
4480TEST_P(ImportKeyTest, AesSuccess) {
4481 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4482 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4483 .Authorization(TAG_NO_AUTH_REQUIRED)
4484 .AesEncryptionKey(key.size() * 8)
4485 .EcbMode()
4486 .Padding(PaddingMode::PKCS7),
4487 KeyFormat::RAW, key));
4488
4489 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4490 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4491 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4492 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4493 CheckOrigin();
4494
4495 string message = "Hello World!";
4496 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4497 string ciphertext = EncryptMessage(message, params);
4498 string plaintext = DecryptMessage(ciphertext, params);
4499 EXPECT_EQ(message, plaintext);
4500}
4501
4502/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004503 * ImportKeyTest.AesFailure
4504 *
4505 * Verifies that importing an invalid AES key fails.
4506 */
4507TEST_P(ImportKeyTest, AesFailure) {
4508 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4509 uint32_t bitlen = key.size() * 8;
4510 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004511 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004512 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004513 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004514 .Authorization(TAG_NO_AUTH_REQUIRED)
4515 .AesEncryptionKey(key_size)
4516 .EcbMode()
4517 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004518 KeyFormat::RAW, key);
4519 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004520 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4521 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004522 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004523
4524 // Explicit key size matches that of the provided key, but it's not a valid size.
4525 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4526 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4527 ImportKey(AuthorizationSetBuilder()
4528 .Authorization(TAG_NO_AUTH_REQUIRED)
4529 .AesEncryptionKey(long_key.size() * 8)
4530 .EcbMode()
4531 .Padding(PaddingMode::PKCS7),
4532 KeyFormat::RAW, long_key));
4533 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4534 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4535 ImportKey(AuthorizationSetBuilder()
4536 .Authorization(TAG_NO_AUTH_REQUIRED)
4537 .AesEncryptionKey(short_key.size() * 8)
4538 .EcbMode()
4539 .Padding(PaddingMode::PKCS7),
4540 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004541}
4542
4543/*
4544 * ImportKeyTest.TripleDesSuccess
4545 *
4546 * Verifies that importing and using a 3DES key works.
4547 */
4548TEST_P(ImportKeyTest, TripleDesSuccess) {
4549 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4550 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4551 .Authorization(TAG_NO_AUTH_REQUIRED)
4552 .TripleDesEncryptionKey(168)
4553 .EcbMode()
4554 .Padding(PaddingMode::PKCS7),
4555 KeyFormat::RAW, key));
4556
4557 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4558 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4559 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4560 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4561 CheckOrigin();
4562
4563 string message = "Hello World!";
4564 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4565 string ciphertext = EncryptMessage(message, params);
4566 string plaintext = DecryptMessage(ciphertext, params);
4567 EXPECT_EQ(message, plaintext);
4568}
4569
4570/*
4571 * ImportKeyTest.TripleDesFailure
4572 *
4573 * Verifies that importing an invalid 3DES key fails.
4574 */
4575TEST_P(ImportKeyTest, TripleDesFailure) {
4576 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004577 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004578 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004579 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004580 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004581 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004582 .Authorization(TAG_NO_AUTH_REQUIRED)
4583 .TripleDesEncryptionKey(key_size)
4584 .EcbMode()
4585 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004586 KeyFormat::RAW, key);
4587 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004588 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4589 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004590 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004591 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004592 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004593 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4594 ImportKey(AuthorizationSetBuilder()
4595 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004596 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004597 .EcbMode()
4598 .Padding(PaddingMode::PKCS7),
4599 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004600 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004601 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4602 ImportKey(AuthorizationSetBuilder()
4603 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004604 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004605 .EcbMode()
4606 .Padding(PaddingMode::PKCS7),
4607 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004608}
4609
4610/*
4611 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004612 *
4613 * Verifies that importing and using an HMAC key works.
4614 */
4615TEST_P(ImportKeyTest, HmacKeySuccess) {
4616 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4617 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4618 .Authorization(TAG_NO_AUTH_REQUIRED)
4619 .HmacKey(key.size() * 8)
4620 .Digest(Digest::SHA_2_256)
4621 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4622 KeyFormat::RAW, key));
4623
4624 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4625 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4626 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4627 CheckOrigin();
4628
4629 string message = "Hello World!";
4630 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4631 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4632}
4633
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004634/*
4635 * ImportKeyTest.GetKeyCharacteristics
4636 *
4637 * Verifies that imported keys have the correct characteristics.
4638 */
4639TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4640 vector<uint8_t> key_blob;
4641 vector<KeyCharacteristics> key_characteristics;
4642 auto base_builder = AuthorizationSetBuilder()
4643 .Padding(PaddingMode::NONE)
4644 .Authorization(TAG_NO_AUTH_REQUIRED)
4645 .SetDefaultValidity();
4646 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4647 Algorithm::TRIPLE_DES};
4648 ErrorCode result;
4649 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4650 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4651 for (auto alg : algorithms) {
4652 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4653 AuthorizationSetBuilder builder(base_builder);
4654 switch (alg) {
4655 case Algorithm::RSA:
4656 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4657
4658 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4659 &key_characteristics);
4660 break;
4661 case Algorithm::EC:
4662 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4663 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4664 &key_characteristics);
4665 break;
4666 case Algorithm::HMAC:
4667 builder.HmacKey(128)
4668 .Digest(Digest::SHA_2_256)
4669 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4670 result =
4671 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4672 break;
4673 case Algorithm::AES:
4674 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4675 result =
4676 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4677 break;
4678 case Algorithm::TRIPLE_DES:
4679 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4680 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4681 &key_characteristics);
4682 break;
4683 default:
4684 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4685 continue;
4686 }
4687 ASSERT_EQ(ErrorCode::OK, result);
4688 CheckCharacteristics(key_blob, key_characteristics);
4689 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4690 }
4691}
4692
Selene Huang31ab4042020-04-29 04:22:39 -07004693INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4694
4695auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004696 // IKeyMintDevice.aidl
4697 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4698 "020100" // INTEGER length 1 value 0x00 (version)
4699 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4700 "934bf94e2aa28a3f83c9f79297250262"
4701 "fbe3276b5a1c91159bbfa3ef8957aac8"
4702 "4b59b30b455a79c2973480823d8b3863"
4703 "c3deef4a8e243590268d80e18751a0e1"
4704 "30f67ce6a1ace9f79b95e097474febc9"
4705 "81195b1d13a69086c0863f66a7b7fdb4"
4706 "8792227b1ac5e2489febdf087ab54864"
4707 "83033a6f001ca5d1ec1e27f5c30f4cec"
4708 "2642074a39ae68aee552e196627a8e3d"
4709 "867e67a8c01b11e75f13cca0a97ab668"
4710 "b50cda07a8ecb7cd8e3dd7009c963653"
4711 "4f6f239cffe1fc8daa466f78b676c711"
4712 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4713 "99b801597d5220e307eaa5bee507fb94"
4714 "d1fa69f9e519b2de315bac92c36f2ea1"
4715 "fa1df4478c0ddedeae8c70e0233cd098"
4716 "040c" // OCTET STRING length 0x0c (initializationVector)
4717 "d796b02c370f1fa4cc0124f1"
4718 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4719 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4720 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4721 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4722 "3106" // SET length 0x06
4723 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4724 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4725 // } end SET
4726 // } end [1]
4727 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4728 "020120" // INTEGER length 1 value 0x20 (AES)
4729 // } end [2]
4730 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4731 "02020100" // INTEGER length 2 value 0x100
4732 // } end [3]
4733 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4734 "3103" // SET length 0x03 {
4735 "020101" // INTEGER length 1 value 0x01 (ECB)
4736 // } end SET
4737 // } end [4]
4738 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4739 "3103" // SET length 0x03 {
4740 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4741 // } end SET
4742 // } end [5]
4743 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4744 // (noAuthRequired)
4745 "0500" // NULL
4746 // } end [503]
4747 // } end SEQUENCE (AuthorizationList)
4748 // } end SEQUENCE (KeyDescription)
4749 "0420" // OCTET STRING length 0x20 (encryptedKey)
4750 "ccd540855f833a5e1480bfd2d36faf3a"
4751 "eee15df5beabe2691bc82dde2a7aa910"
4752 "0410" // OCTET STRING length 0x10 (tag)
4753 "64c9f689c60ff6223ab6e6999e0eb6e5"
4754 // } SEQUENCE (SecureKeyWrapper)
4755);
Selene Huang31ab4042020-04-29 04:22:39 -07004756
4757auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004758 // IKeyMintDevice.aidl
4759 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4760 "020100" // INTEGER length 1 value 0x00 (version)
4761 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4762 "aad93ed5924f283b4bb5526fbe7a1412"
4763 "f9d9749ec30db9062b29e574a8546f33"
4764 "c88732452f5b8e6a391ee76c39ed1712"
4765 "c61d8df6213dec1cffbc17a8c6d04c7b"
4766 "30893d8daa9b2015213e219468215532"
4767 "07f8f9931c4caba23ed3bee28b36947e"
4768 "47f10e0a5c3dc51c988a628daad3e5e1"
4769 "f4005e79c2d5a96c284b4b8d7e4948f3"
4770 "31e5b85dd5a236f85579f3ea1d1b8484"
4771 "87470bdb0ab4f81a12bee42c99fe0df4"
4772 "bee3759453e69ad1d68a809ce06b949f"
4773 "7694a990429b2fe81e066ff43e56a216"
4774 "02db70757922a4bcc23ab89f1e35da77"
4775 "586775f423e519c2ea394caf48a28d0c"
4776 "8020f1dcf6b3a68ec246f615ae96dae9"
4777 "a079b1f6eb959033c1af5c125fd94168"
4778 "040c" // OCTET STRING length 0x0c (initializationVector)
4779 "6d9721d08589581ab49204a3"
4780 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4781 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4782 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4783 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4784 "3106" // SET length 0x06
4785 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4786 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4787 // } end SET
4788 // } end [1]
4789 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4790 "020120" // INTEGER length 1 value 0x20 (AES)
4791 // } end [2]
4792 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4793 "02020100" // INTEGER length 2 value 0x100
4794 // } end [3]
4795 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4796 "3103" // SET length 0x03 {
4797 "020101" // INTEGER length 1 value 0x01 (ECB)
4798 // } end SET
4799 // } end [4]
4800 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4801 "3103" // SET length 0x03 {
4802 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4803 // } end SET
4804 // } end [5]
4805 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4806 // (noAuthRequired)
4807 "0500" // NULL
4808 // } end [503]
4809 // } end SEQUENCE (AuthorizationList)
4810 // } end SEQUENCE (KeyDescription)
4811 "0420" // OCTET STRING length 0x20 (encryptedKey)
4812 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4813 "c20d1f99a9a024a76f35c8e2cab9b68d"
4814 "0410" // OCTET STRING length 0x10 (tag)
4815 "2560c70109ae67c030f00b98b512a670"
4816 // } SEQUENCE (SecureKeyWrapper)
4817);
Selene Huang31ab4042020-04-29 04:22:39 -07004818
4819auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004820 // RFC 5208 s5
4821 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4822 "020100" // INTEGER length 1 value 0x00 (version)
4823 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4824 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4825 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4826 "0500" // NULL (parameters)
4827 // } SEQUENCE (AlgorithmIdentifier)
4828 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4829 // RFC 8017 A.1.2
4830 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4831 "020100" // INTEGER length 1 value 0x00 (version)
4832 "02820101" // INTEGER length 0x0101 (modulus) value...
4833 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4834 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4835 "7b06e673a837313d56b1c725150a3fef" // 0x30
4836 "86acbddc41bb759c2854eae32d35841e" // 0x40
4837 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4838 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4839 "312d7bd5921ffaea1347c157406fef71" // 0x70
4840 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4841 "f4645c11f5c1374c3886427411c44979" // 0x90
4842 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4843 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4844 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4845 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4846 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4847 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4848 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4849 "55" // 0x101
4850 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4851 "02820100" // INTEGER length 0x100 (privateExponent) value...
4852 "431447b6251908112b1ee76f99f3711a" // 0x10
4853 "52b6630960046c2de70de188d833f8b8" // 0x20
4854 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4855 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4856 "e710b630a03adc683b5d2c43080e52be" // 0x50
4857 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4858 "822bccff087d63c940ba8a45f670feb2" // 0x70
4859 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4860 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4861 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4862 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4863 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4864 "52659d5a5ba05b663737a8696281865b" // 0xd0
4865 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4866 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4867 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4868 "028181" // INTEGER length 0x81 (prime1) value...
4869 "00de392e18d682c829266cc3454e1d61" // 0x10
4870 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4871 "ff841be5bac82a164c5970007047b8c5" // 0x30
4872 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4873 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4874 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4875 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4876 "9e91346130748a6e3c124f9149d71c74" // 0x80
4877 "35"
4878 "028181" // INTEGER length 0x81 (prime2) value...
4879 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4880 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4881 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4882 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4883 "9ed39a2d934c880440aed8832f984316" // 0x50
4884 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4885 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4886 "b880677c068e1be936e81288815252a8" // 0x80
4887 "a1"
4888 "028180" // INTEGER length 0x80 (exponent1) value...
4889 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4890 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4891 "5a063212a4f105a3764743e53281988a" // 0x30
4892 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4893 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4894 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4895 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4896 "4719d6e2b9439823719cd08bcd031781" // 0x80
4897 "028181" // INTEGER length 0x81 (exponent2) value...
4898 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4899 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4900 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4901 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4902 "1254186af30b22c10582a8a43e34fe94" // 0x50
4903 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4904 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4905 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4906 "61"
4907 "028181" // INTEGER length 0x81 (coefficient) value...
4908 "00c931617c77829dfb1270502be9195c" // 0x10
4909 "8f2830885f57dba869536811e6864236" // 0x20
4910 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4911 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4912 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4913 "959356210723287b0affcc9f727044d4" // 0x60
4914 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4915 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4916 "22"
4917 // } SEQUENCE
4918 // } SEQUENCE ()
4919);
Selene Huang31ab4042020-04-29 04:22:39 -07004920
4921string zero_masking_key =
4922 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4923string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4924
4925class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4926
4927TEST_P(ImportWrappedKeyTest, Success) {
4928 auto wrapping_key_desc = AuthorizationSetBuilder()
4929 .RsaEncryptionKey(2048, 65537)
4930 .Digest(Digest::SHA_2_256)
4931 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004932 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4933 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004934
4935 ASSERT_EQ(ErrorCode::OK,
4936 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4937 AuthorizationSetBuilder()
4938 .Digest(Digest::SHA_2_256)
4939 .Padding(PaddingMode::RSA_OAEP)));
4940
4941 string message = "Hello World!";
4942 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4943 string ciphertext = EncryptMessage(message, params);
4944 string plaintext = DecryptMessage(ciphertext, params);
4945 EXPECT_EQ(message, plaintext);
4946}
4947
David Drysdaled2cc8c22021-04-15 13:29:45 +01004948/*
4949 * ImportWrappedKeyTest.SuccessSidsIgnored
4950 *
4951 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
4952 * include Tag:USER_SECURE_ID.
4953 */
4954TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
4955 auto wrapping_key_desc = AuthorizationSetBuilder()
4956 .RsaEncryptionKey(2048, 65537)
4957 .Digest(Digest::SHA_2_256)
4958 .Padding(PaddingMode::RSA_OAEP)
4959 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4960 .SetDefaultValidity();
4961
4962 int64_t password_sid = 42;
4963 int64_t biometric_sid = 24;
4964 ASSERT_EQ(ErrorCode::OK,
4965 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4966 AuthorizationSetBuilder()
4967 .Digest(Digest::SHA_2_256)
4968 .Padding(PaddingMode::RSA_OAEP),
4969 password_sid, biometric_sid));
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
Selene Huang31ab4042020-04-29 04:22:39 -07004978TEST_P(ImportWrappedKeyTest, SuccessMasked) {
4979 auto wrapping_key_desc = AuthorizationSetBuilder()
4980 .RsaEncryptionKey(2048, 65537)
4981 .Digest(Digest::SHA_2_256)
4982 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004983 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4984 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004985
4986 ASSERT_EQ(ErrorCode::OK,
4987 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
4988 AuthorizationSetBuilder()
4989 .Digest(Digest::SHA_2_256)
4990 .Padding(PaddingMode::RSA_OAEP)));
4991}
4992
4993TEST_P(ImportWrappedKeyTest, WrongMask) {
4994 auto wrapping_key_desc = AuthorizationSetBuilder()
4995 .RsaEncryptionKey(2048, 65537)
4996 .Digest(Digest::SHA_2_256)
4997 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004998 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4999 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005000
5001 ASSERT_EQ(
5002 ErrorCode::VERIFICATION_FAILED,
5003 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5004 AuthorizationSetBuilder()
5005 .Digest(Digest::SHA_2_256)
5006 .Padding(PaddingMode::RSA_OAEP)));
5007}
5008
5009TEST_P(ImportWrappedKeyTest, WrongPurpose) {
5010 auto wrapping_key_desc = AuthorizationSetBuilder()
5011 .RsaEncryptionKey(2048, 65537)
5012 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005013 .Padding(PaddingMode::RSA_OAEP)
5014 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005015
5016 ASSERT_EQ(
5017 ErrorCode::INCOMPATIBLE_PURPOSE,
5018 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5019 AuthorizationSetBuilder()
5020 .Digest(Digest::SHA_2_256)
5021 .Padding(PaddingMode::RSA_OAEP)));
5022}
5023
David Drysdaled2cc8c22021-04-15 13:29:45 +01005024TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
5025 auto wrapping_key_desc = AuthorizationSetBuilder()
5026 .RsaEncryptionKey(2048, 65537)
5027 .Digest(Digest::SHA_2_256)
5028 .Padding(PaddingMode::RSA_PSS)
5029 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5030 .SetDefaultValidity();
5031
5032 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
5033 ImportWrappedKey(wrapped_key, 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, WrongDigest) {
5040 auto wrapping_key_desc = AuthorizationSetBuilder()
5041 .RsaEncryptionKey(2048, 65537)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005042 .Padding(PaddingMode::RSA_OAEP)
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005043 .Digest(Digest::SHA_2_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005044 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5045 .SetDefaultValidity();
5046
5047 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
5048 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5049 AuthorizationSetBuilder()
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005050 .Digest(Digest::SHA_2_512)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005051 .Padding(PaddingMode::RSA_OAEP)));
5052}
5053
Selene Huang31ab4042020-04-29 04:22:39 -07005054INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
5055
5056typedef KeyMintAidlTestBase EncryptionOperationsTest;
5057
5058/*
5059 * EncryptionOperationsTest.RsaNoPaddingSuccess
5060 *
David Drysdale59cae642021-05-12 13:52:03 +01005061 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07005062 */
5063TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00005064 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005065 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005066 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5067 .Authorization(TAG_NO_AUTH_REQUIRED)
5068 .RsaEncryptionKey(2048, exponent)
5069 .Padding(PaddingMode::NONE)
5070 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005071
David Drysdaled2cc8c22021-04-15 13:29:45 +01005072 string message = string(2048 / 8, 'a');
5073 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005074 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005075 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005076
David Drysdale59cae642021-05-12 13:52:03 +01005077 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005078 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005079
David Drysdaled2cc8c22021-04-15 13:29:45 +01005080 // Unpadded RSA is deterministic
5081 EXPECT_EQ(ciphertext1, ciphertext2);
5082
5083 CheckedDeleteKey();
5084 }
Selene Huang31ab4042020-04-29 04:22:39 -07005085}
5086
5087/*
5088 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5089 *
David Drysdale59cae642021-05-12 13:52:03 +01005090 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07005091 */
5092TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5093 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5094 .Authorization(TAG_NO_AUTH_REQUIRED)
5095 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005096 .Padding(PaddingMode::NONE)
5097 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005098
5099 string message = "1";
5100 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5101
David Drysdale59cae642021-05-12 13:52:03 +01005102 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005103 EXPECT_EQ(2048U / 8, ciphertext.size());
5104
5105 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5106 string plaintext = DecryptMessage(ciphertext, params);
5107
5108 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005109}
5110
5111/*
Selene Huang31ab4042020-04-29 04:22:39 -07005112 * EncryptionOperationsTest.RsaOaepSuccess
5113 *
David Drysdale59cae642021-05-12 13:52:03 +01005114 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005115 */
5116TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5117 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5118
5119 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01005120 ASSERT_EQ(ErrorCode::OK,
5121 GenerateKey(AuthorizationSetBuilder()
5122 .Authorization(TAG_NO_AUTH_REQUIRED)
5123 .RsaEncryptionKey(key_size, 65537)
5124 .Padding(PaddingMode::RSA_OAEP)
5125 .Digest(digests)
5126 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
5127 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005128
5129 string message = "Hello";
5130
5131 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005132 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5133
5134 auto params = AuthorizationSetBuilder()
5135 .Digest(digest)
5136 .Padding(PaddingMode::RSA_OAEP)
5137 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5138 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005139 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5140 EXPECT_EQ(key_size / 8, ciphertext1.size());
5141
David Drysdale59cae642021-05-12 13:52:03 +01005142 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005143 EXPECT_EQ(key_size / 8, ciphertext2.size());
5144
5145 // OAEP randomizes padding so every result should be different (with astronomically high
5146 // probability).
5147 EXPECT_NE(ciphertext1, ciphertext2);
5148
5149 string plaintext1 = DecryptMessage(ciphertext1, params);
5150 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5151 string plaintext2 = DecryptMessage(ciphertext2, params);
5152 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5153
5154 // Decrypting corrupted ciphertext should fail.
5155 size_t offset_to_corrupt = random() % ciphertext1.size();
5156 char corrupt_byte;
5157 do {
5158 corrupt_byte = static_cast<char>(random() % 256);
5159 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5160 ciphertext1[offset_to_corrupt] = corrupt_byte;
5161
5162 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5163 string result;
5164 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5165 EXPECT_EQ(0U, result.size());
5166 }
5167}
5168
5169/*
5170 * EncryptionOperationsTest.RsaOaepInvalidDigest
5171 *
David Drysdale59cae642021-05-12 13:52:03 +01005172 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005173 * without a digest.
5174 */
5175TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5176 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5177 .Authorization(TAG_NO_AUTH_REQUIRED)
5178 .RsaEncryptionKey(2048, 65537)
5179 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005180 .Digest(Digest::NONE)
5181 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005182
5183 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005184 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005185}
5186
5187/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005188 * EncryptionOperationsTest.RsaOaepInvalidPadding
5189 *
David Drysdale59cae642021-05-12 13:52:03 +01005190 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005191 * with a padding value that is only suitable for signing/verifying.
5192 */
5193TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5194 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5195 .Authorization(TAG_NO_AUTH_REQUIRED)
5196 .RsaEncryptionKey(2048, 65537)
5197 .Padding(PaddingMode::RSA_PSS)
5198 .Digest(Digest::NONE)
5199 .SetDefaultValidity()));
5200
5201 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005202 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005203}
5204
5205/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005206 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005207 *
David Drysdale59cae642021-05-12 13:52:03 +01005208 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005209 * with a different digest than was used to encrypt.
5210 */
5211TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005212 if (SecLevel() == SecurityLevel::STRONGBOX) {
5213 GTEST_SKIP() << "Test not applicable to StrongBox device";
5214 }
Selene Huang31ab4042020-04-29 04:22:39 -07005215
5216 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5217 .Authorization(TAG_NO_AUTH_REQUIRED)
5218 .RsaEncryptionKey(1024, 65537)
5219 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005220 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5221 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005222 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005223 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005224 message,
5225 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5226
5227 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5228 .Digest(Digest::SHA_2_256)
5229 .Padding(PaddingMode::RSA_OAEP)));
5230 string result;
5231 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5232 EXPECT_EQ(0U, result.size());
5233}
5234
5235/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005236 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5237 *
David Drysdale59cae642021-05-12 13:52:03 +01005238 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005239 * digests.
5240 */
5241TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5242 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5243
5244 size_t key_size = 2048; // Need largish key for SHA-512 test.
5245 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5246 .OaepMGFDigest(digests)
5247 .Authorization(TAG_NO_AUTH_REQUIRED)
5248 .RsaEncryptionKey(key_size, 65537)
5249 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005250 .Digest(Digest::SHA_2_256)
5251 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005252
5253 string message = "Hello";
5254
5255 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005256 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005257 auto params = AuthorizationSetBuilder()
5258 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5259 .Digest(Digest::SHA_2_256)
5260 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005261 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005262 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5263 EXPECT_EQ(key_size / 8, ciphertext1.size());
5264
David Drysdale59cae642021-05-12 13:52:03 +01005265 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005266 EXPECT_EQ(key_size / 8, ciphertext2.size());
5267
5268 // OAEP randomizes padding so every result should be different (with astronomically high
5269 // probability).
5270 EXPECT_NE(ciphertext1, ciphertext2);
5271
5272 string plaintext1 = DecryptMessage(ciphertext1, params);
5273 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5274 string plaintext2 = DecryptMessage(ciphertext2, params);
5275 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5276
5277 // Decrypting corrupted ciphertext should fail.
5278 size_t offset_to_corrupt = random() % ciphertext1.size();
5279 char corrupt_byte;
5280 do {
5281 corrupt_byte = static_cast<char>(random() % 256);
5282 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5283 ciphertext1[offset_to_corrupt] = corrupt_byte;
5284
5285 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5286 string result;
5287 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5288 EXPECT_EQ(0U, result.size());
5289 }
5290}
5291
5292/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005293 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5294 *
5295 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5296 * specified, defaulting to SHA-1.
5297 */
5298TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5299 size_t key_size = 2048;
5300 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5301 .Authorization(TAG_NO_AUTH_REQUIRED)
5302 .RsaEncryptionKey(key_size, 65537)
5303 .Padding(PaddingMode::RSA_OAEP)
5304 .Digest(Digest::SHA_2_256)
5305 .SetDefaultValidity()));
5306
5307 // Do local RSA encryption using the default MGF digest of SHA-1.
5308 string message = "Hello";
5309 auto params =
5310 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5311 string ciphertext = LocalRsaEncryptMessage(message, params);
5312 EXPECT_EQ(key_size / 8, ciphertext.size());
5313
5314 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5315 string plaintext = DecryptMessage(ciphertext, params);
5316 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5317
5318 // Decrypting corrupted ciphertext should fail.
5319 size_t offset_to_corrupt = random() % ciphertext.size();
5320 char corrupt_byte;
5321 do {
5322 corrupt_byte = static_cast<char>(random() % 256);
5323 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5324 ciphertext[offset_to_corrupt] = corrupt_byte;
5325
5326 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5327 string result;
5328 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5329 EXPECT_EQ(0U, result.size());
5330}
5331
5332/*
5333 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5334 *
5335 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5336 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5337 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5338 */
5339TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5340 size_t key_size = 2048;
5341 ASSERT_EQ(ErrorCode::OK,
5342 GenerateKey(AuthorizationSetBuilder()
5343 .Authorization(TAG_NO_AUTH_REQUIRED)
5344 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5345 .RsaEncryptionKey(key_size, 65537)
5346 .Padding(PaddingMode::RSA_OAEP)
5347 .Digest(Digest::SHA_2_256)
5348 .SetDefaultValidity()));
5349
5350 // Do local RSA encryption using the default MGF digest of SHA-1.
5351 string message = "Hello";
5352 auto params =
5353 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5354 string ciphertext = LocalRsaEncryptMessage(message, params);
5355 EXPECT_EQ(key_size / 8, ciphertext.size());
5356
5357 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5358 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5359 // is checked against those values, and found absent.
5360 auto result = Begin(KeyPurpose::DECRYPT, params);
5361 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5362 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5363}
5364
5365/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005366 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5367 *
David Drysdale59cae642021-05-12 13:52:03 +01005368 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005369 * with incompatible MGF digest.
5370 */
5371TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5372 ASSERT_EQ(ErrorCode::OK,
5373 GenerateKey(AuthorizationSetBuilder()
5374 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5375 .Authorization(TAG_NO_AUTH_REQUIRED)
5376 .RsaEncryptionKey(2048, 65537)
5377 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005378 .Digest(Digest::SHA_2_256)
5379 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005380 string message = "Hello World!";
5381
5382 auto params = AuthorizationSetBuilder()
5383 .Padding(PaddingMode::RSA_OAEP)
5384 .Digest(Digest::SHA_2_256)
5385 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005386 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005387}
5388
5389/*
5390 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5391 *
5392 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5393 * with unsupported MGF digest.
5394 */
5395TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5396 ASSERT_EQ(ErrorCode::OK,
5397 GenerateKey(AuthorizationSetBuilder()
5398 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5399 .Authorization(TAG_NO_AUTH_REQUIRED)
5400 .RsaEncryptionKey(2048, 65537)
5401 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005402 .Digest(Digest::SHA_2_256)
5403 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005404 string message = "Hello World!";
5405
5406 auto params = AuthorizationSetBuilder()
5407 .Padding(PaddingMode::RSA_OAEP)
5408 .Digest(Digest::SHA_2_256)
5409 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005410 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005411}
5412
5413/*
Selene Huang31ab4042020-04-29 04:22:39 -07005414 * EncryptionOperationsTest.RsaPkcs1Success
5415 *
5416 * Verifies that RSA PKCS encryption/decrypts works.
5417 */
5418TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5419 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5420 .Authorization(TAG_NO_AUTH_REQUIRED)
5421 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005422 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5423 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005424
5425 string message = "Hello World!";
5426 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005427 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005428 EXPECT_EQ(2048U / 8, ciphertext1.size());
5429
David Drysdale59cae642021-05-12 13:52:03 +01005430 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005431 EXPECT_EQ(2048U / 8, ciphertext2.size());
5432
5433 // PKCS1 v1.5 randomizes padding so every result should be different.
5434 EXPECT_NE(ciphertext1, ciphertext2);
5435
5436 string plaintext = DecryptMessage(ciphertext1, params);
5437 EXPECT_EQ(message, plaintext);
5438
5439 // Decrypting corrupted ciphertext should fail.
5440 size_t offset_to_corrupt = random() % ciphertext1.size();
5441 char corrupt_byte;
5442 do {
5443 corrupt_byte = static_cast<char>(random() % 256);
5444 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5445 ciphertext1[offset_to_corrupt] = corrupt_byte;
5446
5447 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5448 string result;
5449 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5450 EXPECT_EQ(0U, result.size());
5451}
5452
5453/*
Selene Huang31ab4042020-04-29 04:22:39 -07005454 * EncryptionOperationsTest.EcdsaEncrypt
5455 *
5456 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5457 */
5458TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5459 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5460 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005461 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005462 .Digest(Digest::NONE)
5463 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005464 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5465 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5466 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5467}
5468
5469/*
5470 * EncryptionOperationsTest.HmacEncrypt
5471 *
5472 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5473 */
5474TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5475 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5476 .Authorization(TAG_NO_AUTH_REQUIRED)
5477 .HmacKey(128)
5478 .Digest(Digest::SHA_2_256)
5479 .Padding(PaddingMode::NONE)
5480 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5481 auto params = AuthorizationSetBuilder()
5482 .Digest(Digest::SHA_2_256)
5483 .Padding(PaddingMode::NONE)
5484 .Authorization(TAG_MAC_LENGTH, 128);
5485 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5486 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5487}
5488
5489/*
5490 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5491 *
5492 * Verifies that AES ECB mode works.
5493 */
5494TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5495 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5496 .Authorization(TAG_NO_AUTH_REQUIRED)
5497 .AesEncryptionKey(128)
5498 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5499 .Padding(PaddingMode::NONE)));
5500
5501 ASSERT_GT(key_blob_.size(), 0U);
5502 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5503
5504 // Two-block message.
5505 string message = "12345678901234567890123456789012";
5506 string ciphertext1 = EncryptMessage(message, params);
5507 EXPECT_EQ(message.size(), ciphertext1.size());
5508
5509 string ciphertext2 = EncryptMessage(string(message), params);
5510 EXPECT_EQ(message.size(), ciphertext2.size());
5511
5512 // ECB is deterministic.
5513 EXPECT_EQ(ciphertext1, ciphertext2);
5514
5515 string plaintext = DecryptMessage(ciphertext1, params);
5516 EXPECT_EQ(message, plaintext);
5517}
5518
5519/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005520 * EncryptionOperationsTest.AesEcbUnknownTag
5521 *
5522 * Verifies that AES ECB operations ignore unknown tags.
5523 */
5524TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5525 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5526 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5527 KeyParameter unknown_param;
5528 unknown_param.tag = unknown_tag;
5529
5530 vector<KeyCharacteristics> key_characteristics;
5531 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5532 .Authorization(TAG_NO_AUTH_REQUIRED)
5533 .AesEncryptionKey(128)
5534 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5535 .Padding(PaddingMode::NONE)
5536 .Authorization(unknown_param),
5537 &key_blob_, &key_characteristics));
5538 ASSERT_GT(key_blob_.size(), 0U);
5539
5540 // Unknown tags should not be returned in key characteristics.
5541 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5542 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5543 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5544 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5545
5546 // Encrypt without mentioning the unknown parameter.
5547 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5548 string message = "12345678901234567890123456789012";
5549 string ciphertext = EncryptMessage(message, params);
5550 EXPECT_EQ(message.size(), ciphertext.size());
5551
5552 // Decrypt including the unknown parameter.
5553 auto decrypt_params = AuthorizationSetBuilder()
5554 .BlockMode(BlockMode::ECB)
5555 .Padding(PaddingMode::NONE)
5556 .Authorization(unknown_param);
5557 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5558 EXPECT_EQ(message, plaintext);
5559}
5560
5561/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005562 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005563 *
5564 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5565 */
5566TEST_P(EncryptionOperationsTest, AesWrongMode) {
5567 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5568 .Authorization(TAG_NO_AUTH_REQUIRED)
5569 .AesEncryptionKey(128)
5570 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5571 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005572 ASSERT_GT(key_blob_.size(), 0U);
5573
Selene Huang31ab4042020-04-29 04:22:39 -07005574 EXPECT_EQ(
5575 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5576 Begin(KeyPurpose::ENCRYPT,
5577 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5578}
5579
5580/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005581 * EncryptionOperationsTest.AesWrongPadding
5582 *
5583 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5584 */
5585TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5586 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5587 .Authorization(TAG_NO_AUTH_REQUIRED)
5588 .AesEncryptionKey(128)
5589 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5590 .Padding(PaddingMode::NONE)));
5591 ASSERT_GT(key_blob_.size(), 0U);
5592
5593 EXPECT_EQ(
5594 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5595 Begin(KeyPurpose::ENCRYPT,
5596 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5597}
5598
5599/*
5600 * EncryptionOperationsTest.AesInvalidParams
5601 *
5602 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5603 */
5604TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5605 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5606 .Authorization(TAG_NO_AUTH_REQUIRED)
5607 .AesEncryptionKey(128)
5608 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5609 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5610 .Padding(PaddingMode::NONE)
5611 .Padding(PaddingMode::PKCS7)));
5612 ASSERT_GT(key_blob_.size(), 0U);
5613
5614 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5615 .BlockMode(BlockMode::CBC)
5616 .BlockMode(BlockMode::ECB)
5617 .Padding(PaddingMode::NONE));
5618 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5619 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5620
5621 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5622 .BlockMode(BlockMode::ECB)
5623 .Padding(PaddingMode::NONE)
5624 .Padding(PaddingMode::PKCS7));
5625 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5626 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5627}
5628
5629/*
Selene Huang31ab4042020-04-29 04:22:39 -07005630 * EncryptionOperationsTest.AesWrongPurpose
5631 *
5632 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5633 * specified.
5634 */
5635TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5636 auto err = GenerateKey(AuthorizationSetBuilder()
5637 .Authorization(TAG_NO_AUTH_REQUIRED)
5638 .AesKey(128)
5639 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5640 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5641 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5642 .Padding(PaddingMode::NONE));
5643 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5644 ASSERT_GT(key_blob_.size(), 0U);
5645
5646 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5647 .BlockMode(BlockMode::GCM)
5648 .Padding(PaddingMode::NONE)
5649 .Authorization(TAG_MAC_LENGTH, 128));
5650 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5651
5652 CheckedDeleteKey();
5653
5654 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5655 .Authorization(TAG_NO_AUTH_REQUIRED)
5656 .AesKey(128)
5657 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5658 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5659 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5660 .Padding(PaddingMode::NONE)));
5661
5662 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5663 .BlockMode(BlockMode::GCM)
5664 .Padding(PaddingMode::NONE)
5665 .Authorization(TAG_MAC_LENGTH, 128));
5666 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5667}
5668
5669/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005670 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005671 *
5672 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5673 * multiple of the block size and no padding is specified.
5674 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005675TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5676 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005677 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005678 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5679 .Authorization(TAG_NO_AUTH_REQUIRED)
5680 .AesEncryptionKey(128)
5681 .Authorization(TAG_BLOCK_MODE, blockMode)
5682 .Padding(PaddingMode::NONE)));
5683 // Message is slightly shorter than two blocks.
5684 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005685
David Drysdaled2cc8c22021-04-15 13:29:45 +01005686 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5687 AuthorizationSet out_params;
5688 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5689 string ciphertext;
5690 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5691 EXPECT_EQ(0U, ciphertext.size());
5692
5693 CheckedDeleteKey();
5694 }
Selene Huang31ab4042020-04-29 04:22:39 -07005695}
5696
5697/*
5698 * EncryptionOperationsTest.AesEcbPkcs7Padding
5699 *
5700 * Verifies that AES PKCS7 padding works for any message length.
5701 */
5702TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5703 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5704 .Authorization(TAG_NO_AUTH_REQUIRED)
5705 .AesEncryptionKey(128)
5706 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5707 .Padding(PaddingMode::PKCS7)));
5708
5709 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5710
5711 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005712 for (size_t i = 0; i <= 48; i++) {
5713 SCOPED_TRACE(testing::Message() << "i = " << i);
5714 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5715 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005716 string ciphertext = EncryptMessage(message, params);
5717 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5718 string plaintext = DecryptMessage(ciphertext, params);
5719 EXPECT_EQ(message, plaintext);
5720 }
5721}
5722
5723/*
5724 * EncryptionOperationsTest.AesEcbWrongPadding
5725 *
5726 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5727 * specified.
5728 */
5729TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5730 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5731 .Authorization(TAG_NO_AUTH_REQUIRED)
5732 .AesEncryptionKey(128)
5733 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5734 .Padding(PaddingMode::NONE)));
5735
5736 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5737
5738 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005739 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005740 string message(i, 'a');
5741 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5742 }
5743}
5744
5745/*
5746 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5747 *
5748 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5749 */
5750TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5751 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5752 .Authorization(TAG_NO_AUTH_REQUIRED)
5753 .AesEncryptionKey(128)
5754 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5755 .Padding(PaddingMode::PKCS7)));
5756
5757 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5758
5759 string message = "a";
5760 string ciphertext = EncryptMessage(message, params);
5761 EXPECT_EQ(16U, ciphertext.size());
5762 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005763
Seth Moore7a55ae32021-06-23 14:28:11 -07005764 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5765 ++ciphertext[ciphertext.size() / 2];
5766
5767 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5768 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005769 ErrorCode error = Finish(ciphertext, &plaintext);
5770 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005771 // This is the expected error, we can exit the test now.
5772 return;
5773 } else {
5774 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005775 ASSERT_EQ(error, ErrorCode::OK)
5776 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005777 }
5778 }
5779 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005780}
5781
David Drysdaleb8093292022-04-08 12:22:35 +01005782/*
5783 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5784 *
5785 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5786 */
5787TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5788 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5789 .Authorization(TAG_NO_AUTH_REQUIRED)
5790 .AesEncryptionKey(128)
5791 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5792 .Padding(PaddingMode::PKCS7)));
5793
5794 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5795
5796 string message = "a";
5797 string ciphertext = EncryptMessage(message, params);
5798 EXPECT_EQ(16U, ciphertext.size());
5799 EXPECT_NE(ciphertext, message);
5800
5801 // Shorten the ciphertext.
5802 ciphertext.resize(ciphertext.size() - 1);
5803 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5804 string plaintext;
5805 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5806}
5807
Selene Huang31ab4042020-04-29 04:22:39 -07005808vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5809 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005810 EXPECT_TRUE(iv);
5811 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005812}
5813
5814/*
5815 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5816 *
5817 * Verifies that AES CTR mode works.
5818 */
5819TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5820 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5821 .Authorization(TAG_NO_AUTH_REQUIRED)
5822 .AesEncryptionKey(128)
5823 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5824 .Padding(PaddingMode::NONE)));
5825
5826 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5827
5828 string message = "123";
5829 AuthorizationSet out_params;
5830 string ciphertext1 = EncryptMessage(message, params, &out_params);
5831 vector<uint8_t> iv1 = CopyIv(out_params);
5832 EXPECT_EQ(16U, iv1.size());
5833
5834 EXPECT_EQ(message.size(), ciphertext1.size());
5835
5836 out_params.Clear();
5837 string ciphertext2 = EncryptMessage(message, params, &out_params);
5838 vector<uint8_t> iv2 = CopyIv(out_params);
5839 EXPECT_EQ(16U, iv2.size());
5840
5841 // IVs should be random, so ciphertexts should differ.
5842 EXPECT_NE(ciphertext1, ciphertext2);
5843
5844 auto params_iv1 =
5845 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5846 auto params_iv2 =
5847 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5848
5849 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5850 EXPECT_EQ(message, plaintext);
5851 plaintext = DecryptMessage(ciphertext2, params_iv2);
5852 EXPECT_EQ(message, plaintext);
5853
5854 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5855 plaintext = DecryptMessage(ciphertext1, params_iv2);
5856 EXPECT_NE(message, plaintext);
5857 plaintext = DecryptMessage(ciphertext2, params_iv1);
5858 EXPECT_NE(message, plaintext);
5859}
5860
5861/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305862 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07005863 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305864 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07005865 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305866TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5867 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5868}
Selene Huang31ab4042020-04-29 04:22:39 -07005869
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305870/*
5871 * EncryptionOperationsTest.AesCbcIncremental
5872 *
5873 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5874 */
5875TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5876 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5877}
Selene Huang31ab4042020-04-29 04:22:39 -07005878
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305879/*
5880 * EncryptionOperationsTest.AesCtrIncremental
5881 *
5882 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5883 */
5884TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5885 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5886}
Selene Huang31ab4042020-04-29 04:22:39 -07005887
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305888/*
5889 * EncryptionOperationsTest.AesGcmIncremental
5890 *
5891 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5892 */
5893TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5894 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07005895}
5896
Prashant Patildd5f7f02022-07-06 18:58:07 +00005897/*
5898 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
5899 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5900 */
5901TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
5902 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
5903 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
5904 string kat_plaintext =
5905 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
5906 "809FFF37081C22EF278F896AB213A2A631");
5907 string kat_ciphertext =
5908 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
5909 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
5910 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5911 kat_ciphertext);
5912}
5913
5914/*
5915 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
5916 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5917 */
5918TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
5919 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
5920 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
5921 string kat_plaintext =
5922 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
5923 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
5924 string kat_ciphertext =
5925 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
5926 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
5927 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
5928 kat_plaintext, kat_ciphertext);
5929}
5930
5931/*
5932 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
5933 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
5934 */
5935TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
5936 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
5937 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
5938 string kat_plaintext =
5939 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
5940 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
5941 string kat_ciphertext =
5942 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
5943 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
5944 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
5945 kat_ciphertext);
5946}
5947
5948/*
5949 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
5950 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
5951 */
5952TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
5953 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
5954 string kat_plaintext =
5955 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
5956 "7B6168A9A27BCE554BEA94EF26E6C742A0");
5957 string kat_ciphertext =
5958 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
5959 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
5960 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
5961 kat_ciphertext);
5962}
5963
5964/*
5965 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
5966 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
5967 */
5968TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
5969 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
5970 string kat_plaintext =
5971 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
5972 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
5973 string kat_ciphertext =
5974 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
5975 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
5976 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
5977 kat_ciphertext);
5978}
5979
5980/*
5981 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
5982 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
5983 */
5984TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
5985 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
5986 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
5987 string kat_plaintext =
5988 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
5989 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
5990 string kat_ciphertext =
5991 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
5992 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
5993 "bdfcc0cba0");
5994
5995 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
5996 kat_ciphertext);
5997}
5998
5999/*
6000 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
6001 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6002 */
6003TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
6004 if (SecLevel() == SecurityLevel::STRONGBOX) {
6005 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6006 }
6007 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
6008 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
6009 string kat_plaintext =
6010 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
6011 "167f2497c994bd496eb80bfb2ba2c9d5af");
6012 string kat_ciphertext =
6013 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
6014 "72c134552f3a138e726fbe493b3a839598");
6015 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6016 kat_ciphertext);
6017}
6018
6019/*
6020 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
6021 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6022 */
6023TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
6024 if (SecLevel() == SecurityLevel::STRONGBOX) {
6025 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6026 }
6027 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
6028 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
6029 string kat_plaintext =
6030 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
6031 "b170");
6032 string kat_ciphertext =
6033 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
6034 "4e3884138ff403a41fd99818708ada301c");
6035 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6036 kat_plaintext, kat_ciphertext);
6037}
6038
6039/*
6040 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
6041 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6042 */
6043TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
6044 if (SecLevel() == SecurityLevel::STRONGBOX) {
6045 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6046 }
6047 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
6048 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
6049 string kat_plaintext =
6050 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
6051 "28091e09cdbbd3b42b");
6052 string kat_ciphertext =
6053 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
6054 "2ae0f90f0c19f42b4a");
6055 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6056 kat_ciphertext);
6057}
6058
6059/*
6060 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
6061 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6062 */
6063TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
6064 if (SecLevel() == SecurityLevel::STRONGBOX) {
6065 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6066 }
6067 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
6068 string kat_plaintext =
6069 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
6070 "44ab");
6071 string kat_ciphertext =
6072 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
6073 "2453");
6074 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6075 kat_ciphertext);
6076}
6077
6078/*
6079 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6080 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6081 */
6082TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6083 if (SecLevel() == SecurityLevel::STRONGBOX) {
6084 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6085 }
6086 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6087 string kat_plaintext =
6088 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6089 "e2c7");
6090 string kat_ciphertext =
6091 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6092 "bb7e3a889dd4a9589098b44acf1056e7aa");
6093 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6094 kat_ciphertext);
6095}
6096
6097/*
6098 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6099 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6100 */
6101TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6102 if (SecLevel() == SecurityLevel::STRONGBOX) {
6103 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6104 }
6105 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6106 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6107 string kat_plaintext =
6108 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6109 "ff52");
6110 string kat_ciphertext =
6111 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6112 "1413ad70fb0e1970669095ad77ebb5974ae8");
6113
6114 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6115 kat_ciphertext);
6116}
6117
6118/*
6119 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6120 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6121 */
6122TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6123 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6124 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6125 string kat_plaintext =
6126 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6127 "494cb53caca353e4b637ba05687be20f8d");
6128 string kat_ciphertext =
6129 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6130 "6047da1e4fd7c4e1cf2656097f75ae8685");
6131 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6132 kat_ciphertext);
6133}
6134
6135/*
6136 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6137 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6138 */
6139TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6140 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6141 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6142 string kat_plaintext =
6143 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6144 "2545a82b73c48078b9dae62261c65909");
6145 string kat_ciphertext =
6146 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6147 "9403a71987b95124073d69f2a3cb95b0ab");
6148 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6149 kat_plaintext, kat_ciphertext);
6150}
6151
6152/*
6153 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6154 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6155 */
6156TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6157 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6158 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6159 string kat_plaintext =
6160 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6161 "1f6db3c884");
6162 string kat_ciphertext =
6163 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6164 "a7be30d4c3");
6165 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6166 kat_ciphertext);
6167}
6168
6169/*
6170 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6171 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6172 */
6173TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6174 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6175 string kat_plaintext =
6176 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6177 "31a476d6806b8116089c6ec50bb543200f");
6178 string kat_ciphertext =
6179 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6180 "c83e377faf246288931136bef2a07c0be4");
6181 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6182 kat_ciphertext);
6183}
6184
6185/*
6186 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6187 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6188 */
6189TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6190 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6191 string kat_plaintext =
6192 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6193 "6f");
6194 string kat_ciphertext =
6195 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6196 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6197 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6198 kat_ciphertext);
6199}
6200
6201/*
6202 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6203 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6204 */
6205TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6206 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6207 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6208 string kat_plaintext =
6209 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6210 "f0");
6211 string kat_ciphertext =
6212 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6213 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6214
6215 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6216 kat_ciphertext);
6217}
6218
Selene Huang31ab4042020-04-29 04:22:39 -07006219struct AesCtrSp80038aTestVector {
6220 const char* key;
6221 const char* nonce;
6222 const char* plaintext;
6223 const char* ciphertext;
6224};
6225
6226// These test vectors are taken from
6227// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6228static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6229 // AES-128
6230 {
6231 "2b7e151628aed2a6abf7158809cf4f3c",
6232 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6233 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6234 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6235 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6236 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6237 },
6238 // AES-192
6239 {
6240 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6241 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6242 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6243 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6244 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6245 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6246 },
6247 // AES-256
6248 {
6249 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6250 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6251 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6252 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6253 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6254 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6255 },
6256};
6257
6258/*
6259 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6260 *
6261 * Verifies AES CTR implementation against SP800-38A test vectors.
6262 */
6263TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6264 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6265 for (size_t i = 0; i < 3; i++) {
6266 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6267 const string key = hex2str(test.key);
6268 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6269 InvalidSizes.end())
6270 continue;
6271 const string nonce = hex2str(test.nonce);
6272 const string plaintext = hex2str(test.plaintext);
6273 const string ciphertext = hex2str(test.ciphertext);
6274 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6275 }
6276}
6277
6278/*
6279 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6280 *
6281 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6282 */
6283TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6284 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6285 .Authorization(TAG_NO_AUTH_REQUIRED)
6286 .AesEncryptionKey(128)
6287 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6288 .Padding(PaddingMode::PKCS7)));
6289 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6290 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6291}
6292
6293/*
6294 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6295 *
6296 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6297 */
6298TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6299 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6300 .Authorization(TAG_NO_AUTH_REQUIRED)
6301 .AesEncryptionKey(128)
6302 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6303 .Authorization(TAG_CALLER_NONCE)
6304 .Padding(PaddingMode::NONE)));
6305
6306 auto params = AuthorizationSetBuilder()
6307 .BlockMode(BlockMode::CTR)
6308 .Padding(PaddingMode::NONE)
6309 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6310 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6311
6312 params = AuthorizationSetBuilder()
6313 .BlockMode(BlockMode::CTR)
6314 .Padding(PaddingMode::NONE)
6315 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6316 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6317
6318 params = AuthorizationSetBuilder()
6319 .BlockMode(BlockMode::CTR)
6320 .Padding(PaddingMode::NONE)
6321 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6322 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6323}
6324
6325/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006326 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006327 *
6328 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6329 */
6330TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6331 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6332 .Authorization(TAG_NO_AUTH_REQUIRED)
6333 .AesEncryptionKey(128)
6334 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6335 .Padding(PaddingMode::NONE)));
6336 // Two-block message.
6337 string message = "12345678901234567890123456789012";
6338 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6339 AuthorizationSet out_params;
6340 string ciphertext1 = EncryptMessage(message, params, &out_params);
6341 vector<uint8_t> iv1 = CopyIv(out_params);
6342 EXPECT_EQ(message.size(), ciphertext1.size());
6343
6344 out_params.Clear();
6345
6346 string ciphertext2 = EncryptMessage(message, params, &out_params);
6347 vector<uint8_t> iv2 = CopyIv(out_params);
6348 EXPECT_EQ(message.size(), ciphertext2.size());
6349
6350 // IVs should be random, so ciphertexts should differ.
6351 EXPECT_NE(ciphertext1, ciphertext2);
6352
6353 params.push_back(TAG_NONCE, iv1);
6354 string plaintext = DecryptMessage(ciphertext1, params);
6355 EXPECT_EQ(message, plaintext);
6356}
6357
6358/*
Tommy Chiuee705692021-09-23 20:09:13 +08006359 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6360 *
6361 * Verifies that keymaster generates correct output on zero-input with
6362 * NonePadding mode
6363 */
6364TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6365 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6366 .Authorization(TAG_NO_AUTH_REQUIRED)
6367 .AesEncryptionKey(128)
6368 .BlockMode(BlockMode::CBC)
6369 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6370
6371 // Zero input message
6372 string message = "";
6373 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006374 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006375 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6376 AuthorizationSet out_params;
6377 string ciphertext1 = EncryptMessage(message, params, &out_params);
6378 vector<uint8_t> iv1 = CopyIv(out_params);
6379 if (padding == PaddingMode::NONE)
6380 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6381 else
6382 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6383
6384 out_params.Clear();
6385
6386 string ciphertext2 = EncryptMessage(message, params, &out_params);
6387 vector<uint8_t> iv2 = CopyIv(out_params);
6388 if (padding == PaddingMode::NONE)
6389 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6390 else
6391 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6392
6393 // IVs should be random
6394 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6395
6396 params.push_back(TAG_NONCE, iv1);
6397 string plaintext = DecryptMessage(ciphertext1, params);
6398 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6399 }
6400}
6401
6402/*
Selene Huang31ab4042020-04-29 04:22:39 -07006403 * EncryptionOperationsTest.AesCallerNonce
6404 *
6405 * Verifies that AES caller-provided nonces work correctly.
6406 */
6407TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6408 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6409 .Authorization(TAG_NO_AUTH_REQUIRED)
6410 .AesEncryptionKey(128)
6411 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6412 .Authorization(TAG_CALLER_NONCE)
6413 .Padding(PaddingMode::NONE)));
6414
6415 string message = "12345678901234567890123456789012";
6416
6417 // Don't specify nonce, should get a random one.
6418 AuthorizationSetBuilder params =
6419 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6420 AuthorizationSet out_params;
6421 string ciphertext = EncryptMessage(message, params, &out_params);
6422 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006423 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006424
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006425 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006426 string plaintext = DecryptMessage(ciphertext, params);
6427 EXPECT_EQ(message, plaintext);
6428
6429 // Now specify a nonce, should also work.
6430 params = AuthorizationSetBuilder()
6431 .BlockMode(BlockMode::CBC)
6432 .Padding(PaddingMode::NONE)
6433 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6434 out_params.Clear();
6435 ciphertext = EncryptMessage(message, params, &out_params);
6436
6437 // Decrypt with correct nonce.
6438 plaintext = DecryptMessage(ciphertext, params);
6439 EXPECT_EQ(message, plaintext);
6440
6441 // Try with wrong nonce.
6442 params = AuthorizationSetBuilder()
6443 .BlockMode(BlockMode::CBC)
6444 .Padding(PaddingMode::NONE)
6445 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6446 plaintext = DecryptMessage(ciphertext, params);
6447 EXPECT_NE(message, plaintext);
6448}
6449
6450/*
6451 * EncryptionOperationsTest.AesCallerNonceProhibited
6452 *
6453 * Verifies that caller-provided nonces are not permitted when not specified in the key
6454 * authorizations.
6455 */
6456TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6457 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6458 .Authorization(TAG_NO_AUTH_REQUIRED)
6459 .AesEncryptionKey(128)
6460 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6461 .Padding(PaddingMode::NONE)));
6462
6463 string message = "12345678901234567890123456789012";
6464
6465 // Don't specify nonce, should get a random one.
6466 AuthorizationSetBuilder params =
6467 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6468 AuthorizationSet out_params;
6469 string ciphertext = EncryptMessage(message, params, &out_params);
6470 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006471 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006472
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006473 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006474 string plaintext = DecryptMessage(ciphertext, params);
6475 EXPECT_EQ(message, plaintext);
6476
6477 // Now specify a nonce, should fail
6478 params = AuthorizationSetBuilder()
6479 .BlockMode(BlockMode::CBC)
6480 .Padding(PaddingMode::NONE)
6481 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6482 out_params.Clear();
6483 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6484}
6485
6486/*
6487 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6488 *
6489 * Verifies that AES GCM mode works.
6490 */
6491TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6492 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6493 .Authorization(TAG_NO_AUTH_REQUIRED)
6494 .AesEncryptionKey(128)
6495 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6496 .Padding(PaddingMode::NONE)
6497 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6498
6499 string aad = "foobar";
6500 string message = "123456789012345678901234567890123456";
6501
6502 auto begin_params = AuthorizationSetBuilder()
6503 .BlockMode(BlockMode::GCM)
6504 .Padding(PaddingMode::NONE)
6505 .Authorization(TAG_MAC_LENGTH, 128);
6506
Selene Huang31ab4042020-04-29 04:22:39 -07006507 // Encrypt
6508 AuthorizationSet begin_out_params;
6509 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6510 << "Begin encrypt";
6511 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006512 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6513 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006514 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6515
6516 // Grab nonce
6517 begin_params.push_back(begin_out_params);
6518
6519 // Decrypt.
6520 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006521 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006522 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006523 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006524 EXPECT_EQ(message.length(), plaintext.length());
6525 EXPECT_EQ(message, plaintext);
6526}
6527
6528/*
6529 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6530 *
6531 * Verifies that AES GCM mode works, even when there's a long delay
6532 * between operations.
6533 */
6534TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6535 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6536 .Authorization(TAG_NO_AUTH_REQUIRED)
6537 .AesEncryptionKey(128)
6538 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6539 .Padding(PaddingMode::NONE)
6540 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6541
6542 string aad = "foobar";
6543 string message = "123456789012345678901234567890123456";
6544
6545 auto begin_params = AuthorizationSetBuilder()
6546 .BlockMode(BlockMode::GCM)
6547 .Padding(PaddingMode::NONE)
6548 .Authorization(TAG_MAC_LENGTH, 128);
6549
Selene Huang31ab4042020-04-29 04:22:39 -07006550 // Encrypt
6551 AuthorizationSet begin_out_params;
6552 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6553 << "Begin encrypt";
6554 string ciphertext;
6555 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006556 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006557 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006558 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006559
6560 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6561
6562 // Grab nonce
6563 begin_params.push_back(begin_out_params);
6564
6565 // Decrypt.
6566 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6567 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006568 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006569 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006570 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006571 sleep(5);
6572 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6573 EXPECT_EQ(message.length(), plaintext.length());
6574 EXPECT_EQ(message, plaintext);
6575}
6576
6577/*
6578 * EncryptionOperationsTest.AesGcmDifferentNonces
6579 *
6580 * Verifies that encrypting the same data with different nonces produces different outputs.
6581 */
6582TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6583 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6584 .Authorization(TAG_NO_AUTH_REQUIRED)
6585 .AesEncryptionKey(128)
6586 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6587 .Padding(PaddingMode::NONE)
6588 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6589 .Authorization(TAG_CALLER_NONCE)));
6590
6591 string aad = "foobar";
6592 string message = "123456789012345678901234567890123456";
6593 string nonce1 = "000000000000";
6594 string nonce2 = "111111111111";
6595 string nonce3 = "222222222222";
6596
6597 string ciphertext1 =
6598 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6599 string ciphertext2 =
6600 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6601 string ciphertext3 =
6602 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6603
6604 ASSERT_NE(ciphertext1, ciphertext2);
6605 ASSERT_NE(ciphertext1, ciphertext3);
6606 ASSERT_NE(ciphertext2, ciphertext3);
6607}
6608
6609/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006610 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6611 *
6612 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6613 */
6614TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6615 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6616 .Authorization(TAG_NO_AUTH_REQUIRED)
6617 .AesEncryptionKey(128)
6618 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6619 .Padding(PaddingMode::NONE)
6620 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6621
6622 string aad = "foobar";
6623 string message = "123456789012345678901234567890123456";
6624
6625 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6626 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6627 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6628
6629 ASSERT_NE(ciphertext1, ciphertext2);
6630 ASSERT_NE(ciphertext1, ciphertext3);
6631 ASSERT_NE(ciphertext2, ciphertext3);
6632}
6633
6634/*
Selene Huang31ab4042020-04-29 04:22:39 -07006635 * EncryptionOperationsTest.AesGcmTooShortTag
6636 *
6637 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6638 */
6639TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6640 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6641 .Authorization(TAG_NO_AUTH_REQUIRED)
6642 .AesEncryptionKey(128)
6643 .BlockMode(BlockMode::GCM)
6644 .Padding(PaddingMode::NONE)
6645 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6646 string message = "123456789012345678901234567890123456";
6647 auto params = AuthorizationSetBuilder()
6648 .BlockMode(BlockMode::GCM)
6649 .Padding(PaddingMode::NONE)
6650 .Authorization(TAG_MAC_LENGTH, 96);
6651
6652 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6653}
6654
6655/*
6656 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6657 *
6658 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6659 */
6660TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6661 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6662 .Authorization(TAG_NO_AUTH_REQUIRED)
6663 .AesEncryptionKey(128)
6664 .BlockMode(BlockMode::GCM)
6665 .Padding(PaddingMode::NONE)
6666 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6667 string aad = "foobar";
6668 string message = "123456789012345678901234567890123456";
6669 auto params = AuthorizationSetBuilder()
6670 .BlockMode(BlockMode::GCM)
6671 .Padding(PaddingMode::NONE)
6672 .Authorization(TAG_MAC_LENGTH, 128);
6673
Selene Huang31ab4042020-04-29 04:22:39 -07006674 // Encrypt
6675 AuthorizationSet begin_out_params;
6676 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6677 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006678 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006679
6680 AuthorizationSet finish_out_params;
6681 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006682 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6683 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006684
6685 params = AuthorizationSetBuilder()
6686 .Authorizations(begin_out_params)
6687 .BlockMode(BlockMode::GCM)
6688 .Padding(PaddingMode::NONE)
6689 .Authorization(TAG_MAC_LENGTH, 96);
6690
6691 // Decrypt.
6692 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6693}
6694
6695/*
6696 * EncryptionOperationsTest.AesGcmCorruptKey
6697 *
6698 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6699 */
6700TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6701 const uint8_t nonce_bytes[] = {
6702 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6703 };
6704 string nonce = make_string(nonce_bytes);
6705 const uint8_t ciphertext_bytes[] = {
6706 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6707 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6708 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6709 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6710 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6711 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6712 };
6713 string ciphertext = make_string(ciphertext_bytes);
6714
6715 auto params = AuthorizationSetBuilder()
6716 .BlockMode(BlockMode::GCM)
6717 .Padding(PaddingMode::NONE)
6718 .Authorization(TAG_MAC_LENGTH, 128)
6719 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6720
6721 auto import_params = AuthorizationSetBuilder()
6722 .Authorization(TAG_NO_AUTH_REQUIRED)
6723 .AesEncryptionKey(128)
6724 .BlockMode(BlockMode::GCM)
6725 .Padding(PaddingMode::NONE)
6726 .Authorization(TAG_CALLER_NONCE)
6727 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6728
6729 // Import correct key and decrypt
6730 const uint8_t key_bytes[] = {
6731 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6732 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6733 };
6734 string key = make_string(key_bytes);
6735 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6736 string plaintext = DecryptMessage(ciphertext, params);
6737 CheckedDeleteKey();
6738
6739 // Corrupt key and attempt to decrypt
6740 key[0] = 0;
6741 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6742 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6743 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6744 CheckedDeleteKey();
6745}
6746
6747/*
6748 * EncryptionOperationsTest.AesGcmAadNoData
6749 *
6750 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6751 * encrypt.
6752 */
6753TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6754 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6755 .Authorization(TAG_NO_AUTH_REQUIRED)
6756 .AesEncryptionKey(128)
6757 .BlockMode(BlockMode::GCM)
6758 .Padding(PaddingMode::NONE)
6759 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6760
6761 string aad = "1234567890123456";
6762 auto params = AuthorizationSetBuilder()
6763 .BlockMode(BlockMode::GCM)
6764 .Padding(PaddingMode::NONE)
6765 .Authorization(TAG_MAC_LENGTH, 128);
6766
Selene Huang31ab4042020-04-29 04:22:39 -07006767 // Encrypt
6768 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006769 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006770 string ciphertext;
6771 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006772 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6773 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006774 EXPECT_TRUE(finish_out_params.empty());
6775
6776 // Grab nonce
6777 params.push_back(begin_out_params);
6778
6779 // Decrypt.
6780 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006781 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006782 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006783 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006784
6785 EXPECT_TRUE(finish_out_params.empty());
6786
6787 EXPECT_EQ("", plaintext);
6788}
6789
6790/*
6791 * EncryptionOperationsTest.AesGcmMultiPartAad
6792 *
6793 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6794 * chunks.
6795 */
6796TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6797 const size_t tag_bits = 128;
6798 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6799 .Authorization(TAG_NO_AUTH_REQUIRED)
6800 .AesEncryptionKey(128)
6801 .BlockMode(BlockMode::GCM)
6802 .Padding(PaddingMode::NONE)
6803 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6804
6805 string message = "123456789012345678901234567890123456";
6806 auto begin_params = AuthorizationSetBuilder()
6807 .BlockMode(BlockMode::GCM)
6808 .Padding(PaddingMode::NONE)
6809 .Authorization(TAG_MAC_LENGTH, tag_bits);
6810 AuthorizationSet begin_out_params;
6811
David Drysdale7fc26b92022-05-13 09:54:24 +01006812 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006813
6814 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006815 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6816 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006817 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006818 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6819 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006820
Selene Huang31ab4042020-04-29 04:22:39 -07006821 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006822 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006823
6824 // Grab nonce.
6825 begin_params.push_back(begin_out_params);
6826
6827 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01006828 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006829 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006830 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006831 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006832 EXPECT_EQ(message, plaintext);
6833}
6834
6835/*
6836 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6837 *
6838 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6839 */
6840TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6841 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6842 .Authorization(TAG_NO_AUTH_REQUIRED)
6843 .AesEncryptionKey(128)
6844 .BlockMode(BlockMode::GCM)
6845 .Padding(PaddingMode::NONE)
6846 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6847
6848 string message = "123456789012345678901234567890123456";
6849 auto begin_params = AuthorizationSetBuilder()
6850 .BlockMode(BlockMode::GCM)
6851 .Padding(PaddingMode::NONE)
6852 .Authorization(TAG_MAC_LENGTH, 128);
6853 AuthorizationSet begin_out_params;
6854
David Drysdale7fc26b92022-05-13 09:54:24 +01006855 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006856
Shawn Willden92d79c02021-02-19 07:31:55 -07006857 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006858 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006859 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6860 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006861
David Drysdaled2cc8c22021-04-15 13:29:45 +01006862 // The failure should have already cancelled the operation.
6863 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6864
Shawn Willden92d79c02021-02-19 07:31:55 -07006865 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006866}
6867
6868/*
6869 * EncryptionOperationsTest.AesGcmBadAad
6870 *
6871 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6872 */
6873TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6874 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6875 .Authorization(TAG_NO_AUTH_REQUIRED)
6876 .AesEncryptionKey(128)
6877 .BlockMode(BlockMode::GCM)
6878 .Padding(PaddingMode::NONE)
6879 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6880
6881 string message = "12345678901234567890123456789012";
6882 auto begin_params = AuthorizationSetBuilder()
6883 .BlockMode(BlockMode::GCM)
6884 .Padding(PaddingMode::NONE)
6885 .Authorization(TAG_MAC_LENGTH, 128);
6886
Selene Huang31ab4042020-04-29 04:22:39 -07006887 // Encrypt
6888 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006889 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006890 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006891 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006892 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006893
6894 // Grab nonce
6895 begin_params.push_back(begin_out_params);
6896
Selene Huang31ab4042020-04-29 04:22:39 -07006897 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006898 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006899 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006900 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006901 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006902}
6903
6904/*
6905 * EncryptionOperationsTest.AesGcmWrongNonce
6906 *
6907 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6908 */
6909TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6910 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6911 .Authorization(TAG_NO_AUTH_REQUIRED)
6912 .AesEncryptionKey(128)
6913 .BlockMode(BlockMode::GCM)
6914 .Padding(PaddingMode::NONE)
6915 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6916
6917 string message = "12345678901234567890123456789012";
6918 auto begin_params = AuthorizationSetBuilder()
6919 .BlockMode(BlockMode::GCM)
6920 .Padding(PaddingMode::NONE)
6921 .Authorization(TAG_MAC_LENGTH, 128);
6922
Selene Huang31ab4042020-04-29 04:22:39 -07006923 // Encrypt
6924 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006925 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006926 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006927 string ciphertext;
6928 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006929 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006930
6931 // Wrong nonce
6932 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6933
6934 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006935 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006936 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006937 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006938 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006939
6940 // With wrong nonce, should have gotten garbage plaintext (or none).
6941 EXPECT_NE(message, plaintext);
6942}
6943
6944/*
6945 * EncryptionOperationsTest.AesGcmCorruptTag
6946 *
6947 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6948 */
6949TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6950 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6951 .Authorization(TAG_NO_AUTH_REQUIRED)
6952 .AesEncryptionKey(128)
6953 .BlockMode(BlockMode::GCM)
6954 .Padding(PaddingMode::NONE)
6955 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6956
6957 string aad = "1234567890123456";
6958 string message = "123456789012345678901234567890123456";
6959
6960 auto params = AuthorizationSetBuilder()
6961 .BlockMode(BlockMode::GCM)
6962 .Padding(PaddingMode::NONE)
6963 .Authorization(TAG_MAC_LENGTH, 128);
6964
Selene Huang31ab4042020-04-29 04:22:39 -07006965 // Encrypt
6966 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006967 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006968 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006969 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006970 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006971
6972 // Corrupt tag
6973 ++(*ciphertext.rbegin());
6974
6975 // Grab nonce
6976 params.push_back(begin_out_params);
6977
6978 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006979 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006980 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006981 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006982 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006983}
6984
6985/*
6986 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
6987 *
6988 * Verifies that 3DES is basically functional.
6989 */
6990TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
6991 auto auths = AuthorizationSetBuilder()
6992 .TripleDesEncryptionKey(168)
6993 .BlockMode(BlockMode::ECB)
6994 .Authorization(TAG_NO_AUTH_REQUIRED)
6995 .Padding(PaddingMode::NONE);
6996
6997 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
6998 // Two-block message.
6999 string message = "1234567890123456";
7000 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7001 string ciphertext1 = EncryptMessage(message, inParams);
7002 EXPECT_EQ(message.size(), ciphertext1.size());
7003
7004 string ciphertext2 = EncryptMessage(string(message), inParams);
7005 EXPECT_EQ(message.size(), ciphertext2.size());
7006
7007 // ECB is deterministic.
7008 EXPECT_EQ(ciphertext1, ciphertext2);
7009
7010 string plaintext = DecryptMessage(ciphertext1, inParams);
7011 EXPECT_EQ(message, plaintext);
7012}
7013
7014/*
7015 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
7016 *
7017 * Verifies that CBC keys reject ECB usage.
7018 */
7019TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
7020 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7021 .TripleDesEncryptionKey(168)
7022 .BlockMode(BlockMode::CBC)
7023 .Authorization(TAG_NO_AUTH_REQUIRED)
7024 .Padding(PaddingMode::NONE)));
7025
7026 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7027 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7028}
7029
7030/*
7031 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
7032 *
7033 * Tests ECB mode with PKCS#7 padding, various message sizes.
7034 */
7035TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
7036 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7037 .TripleDesEncryptionKey(168)
7038 .BlockMode(BlockMode::ECB)
7039 .Authorization(TAG_NO_AUTH_REQUIRED)
7040 .Padding(PaddingMode::PKCS7)));
7041
7042 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007043 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007044 string message(i, 'a');
7045 auto inParams =
7046 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7047 string ciphertext = EncryptMessage(message, inParams);
7048 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7049 string plaintext = DecryptMessage(ciphertext, inParams);
7050 EXPECT_EQ(message, plaintext);
7051 }
7052}
7053
7054/*
7055 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
7056 *
7057 * Verifies that keys configured for no padding reject PKCS7 padding
7058 */
7059TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
7060 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7061 .TripleDesEncryptionKey(168)
7062 .BlockMode(BlockMode::ECB)
7063 .Authorization(TAG_NO_AUTH_REQUIRED)
7064 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00007065 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7066 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07007067}
7068
7069/*
7070 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
7071 *
7072 * Verifies that corrupted padding is detected.
7073 */
7074TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
7075 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7076 .TripleDesEncryptionKey(168)
7077 .BlockMode(BlockMode::ECB)
7078 .Authorization(TAG_NO_AUTH_REQUIRED)
7079 .Padding(PaddingMode::PKCS7)));
7080
7081 string message = "a";
7082 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7083 EXPECT_EQ(8U, ciphertext.size());
7084 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007085
7086 AuthorizationSetBuilder begin_params;
7087 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7088 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07007089
7090 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7091 ++ciphertext[ciphertext.size() / 2];
7092
David Drysdale7fc26b92022-05-13 09:54:24 +01007093 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007094 string plaintext;
7095 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7096 ErrorCode error = Finish(&plaintext);
7097 if (error == ErrorCode::INVALID_ARGUMENT) {
7098 // This is the expected error, we can exit the test now.
7099 return;
7100 } else {
7101 // Very small chance we got valid decryption, so try again.
7102 ASSERT_EQ(error, ErrorCode::OK);
7103 }
7104 }
7105 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007106}
7107
7108struct TripleDesTestVector {
7109 const char* name;
7110 const KeyPurpose purpose;
7111 const BlockMode block_mode;
7112 const PaddingMode padding_mode;
7113 const char* key;
7114 const char* iv;
7115 const char* input;
7116 const char* output;
7117};
7118
7119// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7120// of the NIST vectors are multiples of the block size.
7121static const TripleDesTestVector kTripleDesTestVectors[] = {
7122 {
7123 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7124 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7125 "", // IV
7126 "329d86bdf1bc5af4", // input
7127 "d946c2756d78633f", // output
7128 },
7129 {
7130 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7131 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7132 "", // IV
7133 "6b1540781b01ce1997adae102dbf3c5b", // input
7134 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7135 },
7136 {
7137 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7138 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7139 "", // IV
7140 "6daad94ce08acfe7", // input
7141 "660e7d32dcc90e79", // output
7142 },
7143 {
7144 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7145 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7146 "", // IV
7147 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7148 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7149 },
7150 {
7151 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7152 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7153 "43f791134c5647ba", // IV
7154 "dcc153cef81d6f24", // input
7155 "92538bd8af18d3ba", // output
7156 },
7157 {
7158 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7159 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7160 "c2e999cb6249023c", // IV
7161 "c689aee38a301bb316da75db36f110b5", // input
7162 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7163 },
7164 {
7165 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7166 PaddingMode::PKCS7,
7167 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7168 "c2e999cb6249023c", // IV
7169 "c689aee38a301bb316da75db36f110b500", // input
7170 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7171 },
7172 {
7173 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7174 PaddingMode::PKCS7,
7175 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7176 "c2e999cb6249023c", // IV
7177 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7178 "c689aee38a301bb316da75db36f110b500", // output
7179 },
7180 {
7181 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7182 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7183 "41746c7e442d3681", // IV
7184 "c53a7b0ec40600fe", // input
7185 "d4f00eb455de1034", // output
7186 },
7187 {
7188 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7189 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7190 "3982bc02c3727d45", // IV
7191 "6006f10adef52991fcc777a1238bbb65", // input
7192 "edae09288e9e3bc05746d872b48e3b29", // output
7193 },
7194};
7195
7196/*
7197 * EncryptionOperationsTest.TripleDesTestVector
7198 *
7199 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7200 */
7201TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7202 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7203 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7204 SCOPED_TRACE(test->name);
7205 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7206 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7207 hex2str(test->output));
7208 }
7209}
7210
7211/*
7212 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7213 *
7214 * Validates CBC mode functionality.
7215 */
7216TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7217 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7218 .TripleDesEncryptionKey(168)
7219 .BlockMode(BlockMode::CBC)
7220 .Authorization(TAG_NO_AUTH_REQUIRED)
7221 .Padding(PaddingMode::NONE)));
7222
7223 ASSERT_GT(key_blob_.size(), 0U);
7224
Brian J Murray734c8412022-01-13 14:55:30 -08007225 // Four-block message.
7226 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007227 vector<uint8_t> iv1;
7228 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7229 EXPECT_EQ(message.size(), ciphertext1.size());
7230
7231 vector<uint8_t> iv2;
7232 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7233 EXPECT_EQ(message.size(), ciphertext2.size());
7234
7235 // IVs should be random, so ciphertexts should differ.
7236 EXPECT_NE(iv1, iv2);
7237 EXPECT_NE(ciphertext1, ciphertext2);
7238
7239 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7240 EXPECT_EQ(message, plaintext);
7241}
7242
7243/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007244 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7245 *
7246 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7247 */
7248TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7249 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7250 .TripleDesEncryptionKey(168)
7251 .BlockMode(BlockMode::CBC)
7252 .Authorization(TAG_NO_AUTH_REQUIRED)
7253 .Authorization(TAG_CALLER_NONCE)
7254 .Padding(PaddingMode::NONE)));
7255 auto params = AuthorizationSetBuilder()
7256 .BlockMode(BlockMode::CBC)
7257 .Padding(PaddingMode::NONE)
7258 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7259 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7260}
7261
7262/*
Selene Huang31ab4042020-04-29 04:22:39 -07007263 * EncryptionOperationsTest.TripleDesCallerIv
7264 *
7265 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7266 */
7267TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7268 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7269 .TripleDesEncryptionKey(168)
7270 .BlockMode(BlockMode::CBC)
7271 .Authorization(TAG_NO_AUTH_REQUIRED)
7272 .Authorization(TAG_CALLER_NONCE)
7273 .Padding(PaddingMode::NONE)));
7274 string message = "1234567890123456";
7275 vector<uint8_t> iv;
7276 // Don't specify IV, should get a random one.
7277 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7278 EXPECT_EQ(message.size(), ciphertext1.size());
7279 EXPECT_EQ(8U, iv.size());
7280
7281 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7282 EXPECT_EQ(message, plaintext);
7283
7284 // Now specify an IV, should also work.
7285 iv = AidlBuf("abcdefgh");
7286 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7287
7288 // Decrypt with correct IV.
7289 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7290 EXPECT_EQ(message, plaintext);
7291
7292 // Now try with wrong IV.
7293 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7294 EXPECT_NE(message, plaintext);
7295}
7296
7297/*
7298 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7299 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007300 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007301 */
7302TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7303 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7304 .TripleDesEncryptionKey(168)
7305 .BlockMode(BlockMode::CBC)
7306 .Authorization(TAG_NO_AUTH_REQUIRED)
7307 .Padding(PaddingMode::NONE)));
7308
7309 string message = "12345678901234567890123456789012";
7310 vector<uint8_t> iv;
7311 // Don't specify nonce, should get a random one.
7312 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7313 EXPECT_EQ(message.size(), ciphertext1.size());
7314 EXPECT_EQ(8U, iv.size());
7315
7316 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7317 EXPECT_EQ(message, plaintext);
7318
7319 // Now specify a nonce, should fail.
7320 auto input_params = AuthorizationSetBuilder()
7321 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7322 .BlockMode(BlockMode::CBC)
7323 .Padding(PaddingMode::NONE);
7324 AuthorizationSet output_params;
7325 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7326 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7327}
7328
7329/*
7330 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7331 *
7332 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7333 */
7334TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7335 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7336 .TripleDesEncryptionKey(168)
7337 .BlockMode(BlockMode::ECB)
7338 .Authorization(TAG_NO_AUTH_REQUIRED)
7339 .Padding(PaddingMode::NONE)));
7340 // Two-block message.
7341 string message = "1234567890123456";
7342 auto begin_params =
7343 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7344 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7345}
7346
7347/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007348 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007349 *
7350 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7351 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007352TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7353 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007354 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007355 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7356 .TripleDesEncryptionKey(168)
7357 .BlockMode(blockMode)
7358 .Authorization(TAG_NO_AUTH_REQUIRED)
7359 .Padding(PaddingMode::NONE)));
7360 // Message is slightly shorter than two blocks.
7361 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007362
David Drysdaled2cc8c22021-04-15 13:29:45 +01007363 auto begin_params =
7364 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7365 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007366 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007367 string ciphertext;
7368 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7369
7370 CheckedDeleteKey();
7371 }
Selene Huang31ab4042020-04-29 04:22:39 -07007372}
7373
7374/*
7375 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7376 *
7377 * Verifies that PKCS7 padding works correctly in CBC mode.
7378 */
7379TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7380 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7381 .TripleDesEncryptionKey(168)
7382 .BlockMode(BlockMode::CBC)
7383 .Authorization(TAG_NO_AUTH_REQUIRED)
7384 .Padding(PaddingMode::PKCS7)));
7385
7386 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007387 for (size_t i = 0; i <= 32; i++) {
7388 SCOPED_TRACE(testing::Message() << "i = " << i);
7389 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7390 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007391 vector<uint8_t> iv;
7392 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7393 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7394 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7395 EXPECT_EQ(message, plaintext);
7396 }
7397}
7398
7399/*
7400 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7401 *
7402 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7403 */
7404TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7405 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7406 .TripleDesEncryptionKey(168)
7407 .BlockMode(BlockMode::CBC)
7408 .Authorization(TAG_NO_AUTH_REQUIRED)
7409 .Padding(PaddingMode::NONE)));
7410
7411 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007412 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007413 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007414 auto begin_params =
7415 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7416 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7417 }
7418}
7419
7420/*
7421 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7422 *
7423 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7424 */
7425TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7426 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7427 .TripleDesEncryptionKey(168)
7428 .BlockMode(BlockMode::CBC)
7429 .Authorization(TAG_NO_AUTH_REQUIRED)
7430 .Padding(PaddingMode::PKCS7)));
7431
7432 string message = "a";
7433 vector<uint8_t> iv;
7434 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7435 EXPECT_EQ(8U, ciphertext.size());
7436 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007437
7438 auto begin_params = AuthorizationSetBuilder()
7439 .BlockMode(BlockMode::CBC)
7440 .Padding(PaddingMode::PKCS7)
7441 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007442
7443 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007444 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007445 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007446 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007447 string plaintext;
7448 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7449 ErrorCode error = Finish(&plaintext);
7450 if (error == ErrorCode::INVALID_ARGUMENT) {
7451 // This is the expected error, we can exit the test now.
7452 return;
7453 } else {
7454 // Very small chance we got valid decryption, so try again.
7455 ASSERT_EQ(error, ErrorCode::OK);
7456 }
7457 }
7458 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007459}
7460
7461/*
7462 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7463 *
7464 * Verifies that 3DES CBC works with many different input sizes.
7465 */
7466TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7467 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7468 .TripleDesEncryptionKey(168)
7469 .BlockMode(BlockMode::CBC)
7470 .Authorization(TAG_NO_AUTH_REQUIRED)
7471 .Padding(PaddingMode::NONE)));
7472
7473 int increment = 7;
7474 string message(240, 'a');
7475 AuthorizationSet input_params =
7476 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7477 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007478 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007479
7480 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007481 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007482 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007483 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7484 EXPECT_EQ(message.size(), ciphertext.size());
7485
7486 // Move TAG_NONCE into input_params
7487 input_params = output_params;
7488 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7489 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7490 output_params.Clear();
7491
David Drysdale7fc26b92022-05-13 09:54:24 +01007492 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007493 string plaintext;
7494 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007495 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007496 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7497 EXPECT_EQ(ciphertext.size(), plaintext.size());
7498 EXPECT_EQ(message, plaintext);
7499}
7500
7501INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7502
7503typedef KeyMintAidlTestBase MaxOperationsTest;
7504
7505/*
7506 * MaxOperationsTest.TestLimitAes
7507 *
7508 * Verifies that the max uses per boot tag works correctly with AES keys.
7509 */
7510TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007511 if (SecLevel() == SecurityLevel::STRONGBOX) {
7512 GTEST_SKIP() << "Test not applicable to StrongBox device";
7513 }
Selene Huang31ab4042020-04-29 04:22:39 -07007514
7515 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7516 .Authorization(TAG_NO_AUTH_REQUIRED)
7517 .AesEncryptionKey(128)
7518 .EcbMode()
7519 .Padding(PaddingMode::NONE)
7520 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7521
7522 string message = "1234567890123456";
7523
7524 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7525
7526 EncryptMessage(message, params);
7527 EncryptMessage(message, params);
7528 EncryptMessage(message, params);
7529
7530 // Fourth time should fail.
7531 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7532}
7533
7534/*
Qi Wud22ec842020-11-26 13:27:53 +08007535 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007536 *
7537 * Verifies that the max uses per boot tag works correctly with RSA keys.
7538 */
7539TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007540 if (SecLevel() == SecurityLevel::STRONGBOX) {
7541 GTEST_SKIP() << "Test not applicable to StrongBox device";
7542 }
Selene Huang31ab4042020-04-29 04:22:39 -07007543
7544 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7545 .Authorization(TAG_NO_AUTH_REQUIRED)
7546 .RsaSigningKey(1024, 65537)
7547 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007548 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7549 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007550
7551 string message = "1234567890123456";
7552
7553 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7554
7555 SignMessage(message, params);
7556 SignMessage(message, params);
7557 SignMessage(message, params);
7558
7559 // Fourth time should fail.
7560 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7561}
7562
7563INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7564
Qi Wud22ec842020-11-26 13:27:53 +08007565typedef KeyMintAidlTestBase UsageCountLimitTest;
7566
7567/*
Qi Wubeefae42021-01-28 23:16:37 +08007568 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007569 *
Qi Wubeefae42021-01-28 23:16:37 +08007570 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007571 */
Qi Wubeefae42021-01-28 23:16:37 +08007572TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007573 if (SecLevel() == SecurityLevel::STRONGBOX) {
7574 GTEST_SKIP() << "Test not applicable to StrongBox device";
7575 }
Qi Wud22ec842020-11-26 13:27:53 +08007576
7577 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7578 .Authorization(TAG_NO_AUTH_REQUIRED)
7579 .AesEncryptionKey(128)
7580 .EcbMode()
7581 .Padding(PaddingMode::NONE)
7582 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7583
7584 // Check the usage count limit tag appears in the authorizations.
7585 AuthorizationSet auths;
7586 for (auto& entry : key_characteristics_) {
7587 auths.push_back(AuthorizationSet(entry.authorizations));
7588 }
7589 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7590 << "key usage count limit " << 1U << " missing";
7591
7592 string message = "1234567890123456";
7593 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7594
Qi Wubeefae42021-01-28 23:16:37 +08007595 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7596 AuthorizationSet keystore_auths =
7597 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7598
Qi Wud22ec842020-11-26 13:27:53 +08007599 // First usage of AES key should work.
7600 EncryptMessage(message, params);
7601
Qi Wud22ec842020-11-26 13:27:53 +08007602 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7603 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7604 // must be invalidated from secure storage (such as RPMB partition).
7605 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7606 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007607 // Usage count limit tag is enforced by keystore, keymint does nothing.
7608 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007609 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007610 }
7611}
7612
7613/*
Qi Wubeefae42021-01-28 23:16:37 +08007614 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007615 *
Qi Wubeefae42021-01-28 23:16:37 +08007616 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007617 */
Qi Wubeefae42021-01-28 23:16:37 +08007618TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007619 if (SecLevel() == SecurityLevel::STRONGBOX) {
7620 GTEST_SKIP() << "Test not applicable to StrongBox device";
7621 }
Qi Wubeefae42021-01-28 23:16:37 +08007622
7623 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7624 .Authorization(TAG_NO_AUTH_REQUIRED)
7625 .AesEncryptionKey(128)
7626 .EcbMode()
7627 .Padding(PaddingMode::NONE)
7628 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7629
7630 // Check the usage count limit tag appears in the authorizations.
7631 AuthorizationSet auths;
7632 for (auto& entry : key_characteristics_) {
7633 auths.push_back(AuthorizationSet(entry.authorizations));
7634 }
7635 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7636 << "key usage count limit " << 3U << " missing";
7637
7638 string message = "1234567890123456";
7639 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7640
7641 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7642 AuthorizationSet keystore_auths =
7643 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7644
7645 EncryptMessage(message, params);
7646 EncryptMessage(message, params);
7647 EncryptMessage(message, params);
7648
7649 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7650 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7651 // must be invalidated from secure storage (such as RPMB partition).
7652 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7653 } else {
7654 // Usage count limit tag is enforced by keystore, keymint does nothing.
7655 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007656 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007657 }
7658}
7659
7660/*
7661 * UsageCountLimitTest.TestSingleUseRsa
7662 *
7663 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7664 */
7665TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007666 if (SecLevel() == SecurityLevel::STRONGBOX) {
7667 GTEST_SKIP() << "Test not applicable to StrongBox device";
7668 }
Qi Wud22ec842020-11-26 13:27:53 +08007669
7670 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7671 .Authorization(TAG_NO_AUTH_REQUIRED)
7672 .RsaSigningKey(1024, 65537)
7673 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007674 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7675 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007676
7677 // Check the usage count limit tag appears in the authorizations.
7678 AuthorizationSet auths;
7679 for (auto& entry : key_characteristics_) {
7680 auths.push_back(AuthorizationSet(entry.authorizations));
7681 }
7682 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7683 << "key usage count limit " << 1U << " missing";
7684
7685 string message = "1234567890123456";
7686 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7687
Qi Wubeefae42021-01-28 23:16:37 +08007688 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7689 AuthorizationSet keystore_auths =
7690 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7691
Qi Wud22ec842020-11-26 13:27:53 +08007692 // First usage of RSA key should work.
7693 SignMessage(message, params);
7694
Qi Wud22ec842020-11-26 13:27:53 +08007695 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7696 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7697 // must be invalidated from secure storage (such as RPMB partition).
7698 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7699 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007700 // Usage count limit tag is enforced by keystore, keymint does nothing.
7701 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007702 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007703 }
7704}
7705
7706/*
7707 * UsageCountLimitTest.TestLimitUseRsa
7708 *
7709 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7710 */
7711TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007712 if (SecLevel() == SecurityLevel::STRONGBOX) {
7713 GTEST_SKIP() << "Test not applicable to StrongBox device";
7714 }
Qi Wubeefae42021-01-28 23:16:37 +08007715
7716 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7717 .Authorization(TAG_NO_AUTH_REQUIRED)
7718 .RsaSigningKey(1024, 65537)
7719 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007720 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7721 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007722
7723 // Check the usage count limit tag appears in the authorizations.
7724 AuthorizationSet auths;
7725 for (auto& entry : key_characteristics_) {
7726 auths.push_back(AuthorizationSet(entry.authorizations));
7727 }
7728 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7729 << "key usage count limit " << 3U << " missing";
7730
7731 string message = "1234567890123456";
7732 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7733
7734 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7735 AuthorizationSet keystore_auths =
7736 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7737
7738 SignMessage(message, params);
7739 SignMessage(message, params);
7740 SignMessage(message, params);
7741
7742 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7743 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7744 // must be invalidated from secure storage (such as RPMB partition).
7745 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7746 } else {
7747 // Usage count limit tag is enforced by keystore, keymint does nothing.
7748 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007749 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007750 }
7751}
7752
Qi Wu8e727f72021-02-11 02:49:33 +08007753/*
7754 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7755 *
7756 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7757 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7758 * in hardware.
7759 */
7760TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01007761 if (SecLevel() == SecurityLevel::STRONGBOX) {
7762 GTEST_SKIP() << "Test not applicable to StrongBox device";
7763 }
Qi Wu8e727f72021-02-11 02:49:33 +08007764
7765 auto error = GenerateKey(AuthorizationSetBuilder()
7766 .RsaSigningKey(2048, 65537)
7767 .Digest(Digest::NONE)
7768 .Padding(PaddingMode::NONE)
7769 .Authorization(TAG_NO_AUTH_REQUIRED)
7770 .Authorization(TAG_ROLLBACK_RESISTANCE)
7771 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007772 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7773 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007774 }
David Drysdale513bf122021-10-06 11:53:13 +01007775
7776 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7777 ASSERT_EQ(ErrorCode::OK, error);
7778 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7779 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7780 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7781
7782 // The KeyMint should also enforce single use key in hardware when it supports rollback
7783 // resistance.
7784 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7785 .Authorization(TAG_NO_AUTH_REQUIRED)
7786 .RsaSigningKey(1024, 65537)
7787 .NoDigestOrPadding()
7788 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7789 .SetDefaultValidity()));
7790
7791 // Check the usage count limit tag appears in the hardware authorizations.
7792 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7793 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7794 << "key usage count limit " << 1U << " missing";
7795
7796 string message = "1234567890123456";
7797 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7798
7799 // First usage of RSA key should work.
7800 SignMessage(message, params);
7801
7802 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7803 // must be invalidated from secure storage (such as RPMB partition).
7804 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007805}
7806
Qi Wud22ec842020-11-26 13:27:53 +08007807INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7808
David Drysdale7de9feb2021-03-05 14:56:19 +00007809typedef KeyMintAidlTestBase GetHardwareInfoTest;
7810
7811TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7812 // Retrieving hardware info should give the same result each time.
7813 KeyMintHardwareInfo info;
7814 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7815 KeyMintHardwareInfo info2;
7816 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7817 EXPECT_EQ(info, info2);
7818}
7819
7820INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7821
Selene Huang31ab4042020-04-29 04:22:39 -07007822typedef KeyMintAidlTestBase AddEntropyTest;
7823
7824/*
7825 * AddEntropyTest.AddEntropy
7826 *
7827 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7828 * is actually added.
7829 */
7830TEST_P(AddEntropyTest, AddEntropy) {
7831 string data = "foo";
7832 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7833}
7834
7835/*
7836 * AddEntropyTest.AddEmptyEntropy
7837 *
7838 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7839 */
7840TEST_P(AddEntropyTest, AddEmptyEntropy) {
7841 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7842}
7843
7844/*
7845 * AddEntropyTest.AddLargeEntropy
7846 *
7847 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7848 */
7849TEST_P(AddEntropyTest, AddLargeEntropy) {
7850 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7851}
7852
David Drysdalebb3d85e2021-04-13 11:15:51 +01007853/*
7854 * AddEntropyTest.AddTooLargeEntropy
7855 *
7856 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7857 */
7858TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7859 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7860 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7861}
7862
Selene Huang31ab4042020-04-29 04:22:39 -07007863INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7864
Selene Huang31ab4042020-04-29 04:22:39 -07007865typedef KeyMintAidlTestBase KeyDeletionTest;
7866
7867/**
7868 * KeyDeletionTest.DeleteKey
7869 *
7870 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7871 * valid key blob.
7872 */
7873TEST_P(KeyDeletionTest, DeleteKey) {
7874 auto error = GenerateKey(AuthorizationSetBuilder()
7875 .RsaSigningKey(2048, 65537)
7876 .Digest(Digest::NONE)
7877 .Padding(PaddingMode::NONE)
7878 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007879 .Authorization(TAG_ROLLBACK_RESISTANCE)
7880 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007881 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7882 GTEST_SKIP() << "Rollback resistance not supported";
7883 }
Selene Huang31ab4042020-04-29 04:22:39 -07007884
7885 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007886 ASSERT_EQ(ErrorCode::OK, error);
7887 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7888 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007889
David Drysdale513bf122021-10-06 11:53:13 +01007890 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007891
David Drysdale513bf122021-10-06 11:53:13 +01007892 string message = "12345678901234567890123456789012";
7893 AuthorizationSet begin_out_params;
7894 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7895 Begin(KeyPurpose::SIGN, key_blob_,
7896 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7897 &begin_out_params));
7898 AbortIfNeeded();
7899 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007900}
7901
7902/**
7903 * KeyDeletionTest.DeleteInvalidKey
7904 *
7905 * This test checks that the HAL excepts invalid key blobs..
7906 */
7907TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7908 // Generate key just to check if rollback protection is implemented
7909 auto error = GenerateKey(AuthorizationSetBuilder()
7910 .RsaSigningKey(2048, 65537)
7911 .Digest(Digest::NONE)
7912 .Padding(PaddingMode::NONE)
7913 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007914 .Authorization(TAG_ROLLBACK_RESISTANCE)
7915 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007916 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7917 GTEST_SKIP() << "Rollback resistance not supported";
7918 }
Selene Huang31ab4042020-04-29 04:22:39 -07007919
7920 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007921 ASSERT_EQ(ErrorCode::OK, error);
7922 AuthorizationSet enforced(SecLevelAuthorizations());
7923 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007924
David Drysdale513bf122021-10-06 11:53:13 +01007925 // Delete the key we don't care about the result at this point.
7926 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007927
David Drysdale513bf122021-10-06 11:53:13 +01007928 // Now create an invalid key blob and delete it.
7929 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007930
David Drysdale513bf122021-10-06 11:53:13 +01007931 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007932}
7933
7934/**
7935 * KeyDeletionTest.DeleteAllKeys
7936 *
7937 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7938 *
7939 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7940 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7941 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7942 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7943 * credentials stored in Keystore/Keymint.
7944 */
7945TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007946 if (!arm_deleteAllKeys) {
7947 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7948 return;
7949 }
Selene Huang31ab4042020-04-29 04:22:39 -07007950 auto error = GenerateKey(AuthorizationSetBuilder()
7951 .RsaSigningKey(2048, 65537)
7952 .Digest(Digest::NONE)
7953 .Padding(PaddingMode::NONE)
7954 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007955 .Authorization(TAG_ROLLBACK_RESISTANCE)
7956 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007957 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7958 GTEST_SKIP() << "Rollback resistance not supported";
7959 }
Selene Huang31ab4042020-04-29 04:22:39 -07007960
7961 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007962 ASSERT_EQ(ErrorCode::OK, error);
7963 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7964 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007965
David Drysdale513bf122021-10-06 11:53:13 +01007966 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007967
David Drysdale513bf122021-10-06 11:53:13 +01007968 string message = "12345678901234567890123456789012";
7969 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07007970
David Drysdale513bf122021-10-06 11:53:13 +01007971 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7972 Begin(KeyPurpose::SIGN, key_blob_,
7973 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7974 &begin_out_params));
7975 AbortIfNeeded();
7976 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007977}
7978
7979INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
7980
David Drysdaled2cc8c22021-04-15 13:29:45 +01007981typedef KeyMintAidlTestBase KeyUpgradeTest;
7982
7983/**
7984 * KeyUpgradeTest.UpgradeInvalidKey
7985 *
7986 * This test checks that the HAL excepts invalid key blobs..
7987 */
7988TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
7989 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
7990
7991 std::vector<uint8_t> new_blob;
7992 Status result = keymint_->upgradeKey(key_blob,
7993 AuthorizationSetBuilder()
7994 .Authorization(TAG_APPLICATION_ID, "clientid")
7995 .Authorization(TAG_APPLICATION_DATA, "appdata")
7996 .vector_data(),
7997 &new_blob);
7998 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
7999}
8000
8001INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
8002
Selene Huang31ab4042020-04-29 04:22:39 -07008003using UpgradeKeyTest = KeyMintAidlTestBase;
8004
8005/*
8006 * UpgradeKeyTest.UpgradeKey
8007 *
8008 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
8009 */
8010TEST_P(UpgradeKeyTest, UpgradeKey) {
8011 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8012 .AesEncryptionKey(128)
8013 .Padding(PaddingMode::NONE)
8014 .Authorization(TAG_NO_AUTH_REQUIRED)));
8015
8016 auto result = UpgradeKey(key_blob_);
8017
8018 // Key doesn't need upgrading. Should get okay, but no new key blob.
8019 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
8020}
8021
8022INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
8023
8024using ClearOperationsTest = KeyMintAidlTestBase;
8025
8026/*
8027 * ClearSlotsTest.TooManyOperations
8028 *
8029 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
8030 * operations are started without being finished or aborted. Also verifies
8031 * that aborting the operations clears the operations.
8032 *
8033 */
8034TEST_P(ClearOperationsTest, TooManyOperations) {
8035 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8036 .Authorization(TAG_NO_AUTH_REQUIRED)
8037 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08008038 .Padding(PaddingMode::NONE)
8039 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07008040
8041 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
8042 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08008043 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07008044 AuthorizationSet out_params;
8045 ErrorCode result;
8046 size_t i;
8047
8048 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00008049 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07008050 if (ErrorCode::OK != result) {
8051 break;
8052 }
8053 }
8054 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
8055 // Try again just in case there's a weird overflow bug
8056 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00008057 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008058 for (size_t j = 0; j < i; j++) {
8059 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
8060 << "Aboort failed for i = " << j << std::endl;
8061 }
David Drysdale7fc26b92022-05-13 09:54:24 +01008062 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008063 AbortIfNeeded();
8064}
8065
8066INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
8067
8068typedef KeyMintAidlTestBase TransportLimitTest;
8069
8070/*
David Drysdale7de9feb2021-03-05 14:56:19 +00008071 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07008072 *
8073 * Verifies that passing input data to finish succeeds as expected.
8074 */
8075TEST_P(TransportLimitTest, LargeFinishInput) {
8076 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8077 .Authorization(TAG_NO_AUTH_REQUIRED)
8078 .AesEncryptionKey(128)
8079 .BlockMode(BlockMode::ECB)
8080 .Padding(PaddingMode::NONE)));
8081
8082 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008083 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07008084 auto cipher_params =
8085 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8086
8087 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01008088 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008089
8090 string plain_message = std::string(1 << msg_size, 'x');
8091 string encrypted_message;
8092 auto rc = Finish(plain_message, &encrypted_message);
8093
8094 EXPECT_EQ(ErrorCode::OK, rc);
8095 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8096 << "Encrypt finish returned OK, but did not consume all of the given input";
8097 cipher_params.push_back(out_params);
8098
David Drysdale7fc26b92022-05-13 09:54:24 +01008099 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008100
8101 string decrypted_message;
8102 rc = Finish(encrypted_message, &decrypted_message);
8103 EXPECT_EQ(ErrorCode::OK, rc);
8104 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8105 << "Decrypt finish returned OK, did not consume all of the given input";
8106 }
8107}
8108
8109INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8110
Seth Moored79a0ec2021-12-13 20:03:33 +00008111static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008112 switch (curve) {
8113 case EcCurve::P_224:
8114 return NID_secp224r1;
8115 case EcCurve::P_256:
8116 return NID_X9_62_prime256v1;
8117 case EcCurve::P_384:
8118 return NID_secp384r1;
8119 case EcCurve::P_521:
8120 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008121 case EcCurve::CURVE_25519:
8122 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008123 }
8124}
8125
David Drysdale42fe1892021-10-14 14:43:46 +01008126class KeyAgreementTest : public KeyMintAidlTestBase {
8127 protected:
8128 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8129 std::vector<uint8_t>* localPublicKey) {
8130 // Generate EC key locally (with access to private key material)
8131 if (localCurve == EcCurve::CURVE_25519) {
8132 uint8_t privKeyData[32];
8133 uint8_t pubKeyData[32];
8134 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008135 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8136 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8137 } else {
8138 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8139 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8140 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8141 ASSERT_NE(group, nullptr);
8142 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8143 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8144 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8145 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008146 }
David Drysdalea410b772022-05-09 16:44:13 +01008147
8148 // Get encoded form of the public part of the locally generated key...
8149 unsigned char* p = nullptr;
8150 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8151 ASSERT_GT(localPublicKeySize, 0);
8152 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8153 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8154 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008155 }
8156
8157 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8158 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008159 auto builder = AuthorizationSetBuilder()
8160 .Authorization(TAG_NO_AUTH_REQUIRED)
8161 .Authorization(TAG_EC_CURVE, curve)
8162 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8163 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8164 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8165 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8166 .SetDefaultValidity();
8167 ErrorCode result = GenerateKey(builder);
8168
8169 if (SecLevel() == SecurityLevel::STRONGBOX) {
8170 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8171 result = GenerateKeyWithSelfSignedAttestKey(
8172 AuthorizationSetBuilder()
8173 .EcdsaKey(EcCurve::P_256)
8174 .AttestKey()
8175 .SetDefaultValidity(), /* attest key params */
8176 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8177 }
8178 }
David Drysdale42fe1892021-10-14 14:43:46 +01008179 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8180 ASSERT_GT(cert_chain_.size(), 0);
8181 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8182 ASSERT_NE(kmKeyCert, nullptr);
8183 // Check that keyAgreement (bit 4) is set in KeyUsage
8184 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8185 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8186 ASSERT_NE(*kmPubKey, nullptr);
8187 if (dump_Attestations) {
8188 for (size_t n = 0; n < cert_chain_.size(); n++) {
8189 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8190 }
8191 }
8192 }
8193
8194 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8195 const std::vector<uint8_t>& localPublicKey) {
8196 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8197 string ZabFromKeyMintStr;
8198 ASSERT_EQ(ErrorCode::OK,
8199 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8200 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8201 vector<uint8_t> ZabFromTest;
8202
8203 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8204 size_t kmPubKeySize = 32;
8205 uint8_t kmPubKeyData[32];
8206 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8207 ASSERT_EQ(kmPubKeySize, 32);
8208
8209 uint8_t localPrivKeyData[32];
8210 size_t localPrivKeySize = 32;
8211 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8212 &localPrivKeySize));
8213 ASSERT_EQ(localPrivKeySize, 32);
8214
8215 uint8_t sharedKey[32];
8216 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8217 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8218 } else {
8219 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8220 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8221 ASSERT_NE(ctx, nullptr);
8222 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8223 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8224 size_t ZabFromTestLen = 0;
8225 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8226 ZabFromTest.resize(ZabFromTestLen);
8227 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8228 }
8229 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8230 }
8231};
8232
David Zeuthene0c40892021-01-08 12:54:11 -05008233/*
8234 * KeyAgreementTest.Ecdh
8235 *
David Drysdale42fe1892021-10-14 14:43:46 +01008236 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008237 */
8238TEST_P(KeyAgreementTest, Ecdh) {
8239 // Because it's possible to use this API with keys on different curves, we
8240 // check all N^2 combinations where N is the number of supported
8241 // curves.
8242 //
8243 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8244 // lot more curves we can be smart about things and just pick |otherCurve| so
8245 // it's not |curve| and that way we end up with only 2*N runs
8246 //
8247 for (auto curve : ValidCurves()) {
8248 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008249 SCOPED_TRACE(testing::Message()
8250 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8251
David Zeuthene0c40892021-01-08 12:54:11 -05008252 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008253 EVP_PKEY_Ptr localPrivKey;
8254 vector<uint8_t> localPublicKey;
8255 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008256
8257 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008258 EVP_PKEY_Ptr kmPubKey;
8259 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008260
8261 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8262 if (curve != localCurve) {
8263 // If the keys are using different curves KeyMint should fail with
8264 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008265 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008266 string ZabFromKeyMintStr;
8267 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008268 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008269 &ZabFromKeyMintStr));
8270
8271 } else {
8272 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008273 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008274 }
8275
8276 CheckedDeleteKey();
8277 }
8278 }
8279}
8280
David Drysdale42fe1892021-10-14 14:43:46 +01008281/*
8282 * KeyAgreementTest.EcdhCurve25519
8283 *
8284 * Verifies that ECDH works for curve25519. This is also covered by the general
8285 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8286 * KeyMint 1.0.
8287 */
8288TEST_P(KeyAgreementTest, EcdhCurve25519) {
8289 if (!Curve25519Supported()) {
8290 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8291 }
8292
8293 // Generate EC key in KeyMint (only access to public key material)
8294 EcCurve curve = EcCurve::CURVE_25519;
8295 EVP_PKEY_Ptr kmPubKey = nullptr;
8296 GenerateKeyMintEcKey(curve, &kmPubKey);
8297
8298 // Generate EC key on same curve locally (with access to private key material).
8299 EVP_PKEY_Ptr privKey;
8300 vector<uint8_t> encodedPublicKey;
8301 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8302
8303 // Agree on a key between local and KeyMint and check it.
8304 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8305
8306 CheckedDeleteKey();
8307}
8308
8309/*
8310 * KeyAgreementTest.EcdhCurve25519Imported
8311 *
8312 * Verifies that ECDH works for an imported curve25519 key.
8313 */
8314TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8315 if (!Curve25519Supported()) {
8316 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8317 }
8318
8319 // Import x25519 key into KeyMint.
8320 EcCurve curve = EcCurve::CURVE_25519;
8321 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8322 .Authorization(TAG_NO_AUTH_REQUIRED)
8323 .EcdsaKey(EcCurve::CURVE_25519)
8324 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8325 .SetDefaultValidity(),
8326 KeyFormat::PKCS8, x25519_pkcs8_key));
8327 ASSERT_GT(cert_chain_.size(), 0);
8328 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8329 ASSERT_NE(kmKeyCert, nullptr);
8330 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8331 ASSERT_NE(kmPubKey.get(), nullptr);
8332
8333 // Expect the import to emit corresponding public key data.
8334 size_t kmPubKeySize = 32;
8335 uint8_t kmPubKeyData[32];
8336 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8337 ASSERT_EQ(kmPubKeySize, 32);
8338 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8339 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8340
8341 // Generate EC key on same curve locally (with access to private key material).
8342 EVP_PKEY_Ptr privKey;
8343 vector<uint8_t> encodedPublicKey;
8344 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8345
8346 // Agree on a key between local and KeyMint and check it.
8347 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8348
8349 CheckedDeleteKey();
8350}
8351
8352/*
8353 * KeyAgreementTest.EcdhCurve25519InvalidSize
8354 *
8355 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8356 */
8357TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8358 if (!Curve25519Supported()) {
8359 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8360 }
8361
8362 // Generate EC key in KeyMint (only access to public key material)
8363 EcCurve curve = EcCurve::CURVE_25519;
8364 EVP_PKEY_Ptr kmPubKey = nullptr;
8365 GenerateKeyMintEcKey(curve, &kmPubKey);
8366
8367 // Generate EC key on same curve locally (with access to private key material).
8368 EVP_PKEY_Ptr privKey;
8369 vector<uint8_t> encodedPublicKey;
8370 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8371
8372 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8373 string ZabFromKeyMintStr;
8374 // Send in an incomplete public key.
8375 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8376 &ZabFromKeyMintStr));
8377
8378 CheckedDeleteKey();
8379}
8380
8381/*
8382 * KeyAgreementTest.EcdhCurve25519Mismatch
8383 *
8384 * Verifies that ECDH fails between curve25519 and other curves.
8385 */
8386TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8387 if (!Curve25519Supported()) {
8388 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8389 }
8390
8391 // Generate EC key in KeyMint (only access to public key material)
8392 EcCurve curve = EcCurve::CURVE_25519;
8393 EVP_PKEY_Ptr kmPubKey = nullptr;
8394 GenerateKeyMintEcKey(curve, &kmPubKey);
8395
8396 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008397 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008398 if (localCurve == curve) {
8399 continue;
8400 }
8401 // Generate EC key on a different curve locally (with access to private key material).
8402 EVP_PKEY_Ptr privKey;
8403 vector<uint8_t> encodedPublicKey;
8404 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8405
David Drysdale7fc26b92022-05-13 09:54:24 +01008406 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008407 string ZabFromKeyMintStr;
8408 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8409 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8410 &ZabFromKeyMintStr));
8411 }
8412
8413 CheckedDeleteKey();
8414}
8415
David Zeuthene0c40892021-01-08 12:54:11 -05008416INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8417
David Drysdaled2cc8c22021-04-15 13:29:45 +01008418using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8419
8420// This is a problematic test, as it can render the device under test permanently unusable.
8421// Re-enable and run at your own risk.
8422TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8423 auto result = DestroyAttestationIds();
8424 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8425}
8426
8427INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8428
Shawn Willdend659c7c2021-02-19 14:51:51 -07008429using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008430
David Drysdaledb0dcf52021-05-18 11:43:31 +01008431/*
8432 * EarlyBootKeyTest.CreateEarlyBootKeys
8433 *
8434 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8435 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008436TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008437 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008438 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8439 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8440
David Drysdaleadfe6112021-05-27 12:00:53 +01008441 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8442 ASSERT_GT(keyData.blob.size(), 0U);
8443 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8444 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8445 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008446 CheckedDeleteKey(&aesKeyData.blob);
8447 CheckedDeleteKey(&hmacKeyData.blob);
8448 CheckedDeleteKey(&rsaKeyData.blob);
8449 CheckedDeleteKey(&ecdsaKeyData.blob);
8450}
8451
David Drysdaledb0dcf52021-05-18 11:43:31 +01008452/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008453 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8454 *
8455 * Verifies that creating an early boot key with attestation succeeds.
8456 */
8457TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8458 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8459 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8460 builder->AttestationChallenge("challenge");
8461 builder->AttestationApplicationId("app_id");
8462 });
8463
8464 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008465 // Strongbox may not support factory attestation. Key creation might fail with
8466 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8467 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8468 continue;
8469 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008470 ASSERT_GT(keyData.blob.size(), 0U);
8471 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8472 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8473 }
8474 CheckedDeleteKey(&aesKeyData.blob);
8475 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00008476 if (rsaKeyData.blob.size() != 0U) {
8477 CheckedDeleteKey(&rsaKeyData.blob);
8478 }
8479 if (ecdsaKeyData.blob.size() != 0U) {
8480 CheckedDeleteKey(&ecdsaKeyData.blob);
8481 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008482}
8483
8484/*
8485 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008486 *
8487 * Verifies that using early boot keys at a later stage fails.
8488 */
8489TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8490 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8491 .Authorization(TAG_NO_AUTH_REQUIRED)
8492 .Authorization(TAG_EARLY_BOOT_ONLY)
8493 .HmacKey(128)
8494 .Digest(Digest::SHA_2_256)
8495 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8496 AuthorizationSet output_params;
8497 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8498 AuthorizationSetBuilder()
8499 .Digest(Digest::SHA_2_256)
8500 .Authorization(TAG_MAC_LENGTH, 256),
8501 &output_params));
8502}
8503
8504/*
8505 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8506 *
8507 * Verifies that importing early boot keys fails.
8508 */
8509TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8510 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8511 .Authorization(TAG_NO_AUTH_REQUIRED)
8512 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008513 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008514 .Digest(Digest::SHA_2_256)
8515 .SetDefaultValidity(),
8516 KeyFormat::PKCS8, ec_256_key));
8517}
8518
David Drysdaled2cc8c22021-04-15 13:29:45 +01008519// 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 +00008520// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8521// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8522// early boot, so you'll have to reboot between runs.
8523TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8524 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8525 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8526 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8527 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8528 EXPECT_TRUE(
8529 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8530 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8531 EXPECT_TRUE(
8532 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8533
8534 // Should be able to use keys, since early boot has not ended
8535 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8536 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8537 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8538 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8539
8540 // End early boot
8541 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8542 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8543
8544 // Should not be able to use already-created keys.
8545 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8546 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8547 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8548 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8549
8550 CheckedDeleteKey(&aesKeyData.blob);
8551 CheckedDeleteKey(&hmacKeyData.blob);
8552 CheckedDeleteKey(&rsaKeyData.blob);
8553 CheckedDeleteKey(&ecdsaKeyData.blob);
8554
8555 // Should not be able to create new keys
8556 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
8557 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
8558
8559 CheckedDeleteKey(&aesKeyData.blob);
8560 CheckedDeleteKey(&hmacKeyData.blob);
8561 CheckedDeleteKey(&rsaKeyData.blob);
8562 CheckedDeleteKey(&ecdsaKeyData.blob);
8563}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008564
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008565INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8566
Shawn Willdend659c7c2021-02-19 14:51:51 -07008567using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008568
8569// This may be a problematic test. It can't be run repeatedly without unlocking the device in
8570// between runs... and on most test devices there are no enrolled credentials so it can't be
8571// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8572// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8573// a manual test process, which includes unlocking between runs, which is why it's included here.
8574// Well, that and the fact that it's the only test we can do without also making calls into the
8575// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8576// implications might be, so that may or may not be a solution.
8577TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8578 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8579 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
8580
8581 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8582 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8583 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8584 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8585
8586 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008587 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008588 ASSERT_EQ(ErrorCode::OK, rc);
8589 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8590 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8591 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8592 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
8593
8594 CheckedDeleteKey(&aesKeyData.blob);
8595 CheckedDeleteKey(&hmacKeyData.blob);
8596 CheckedDeleteKey(&rsaKeyData.blob);
8597 CheckedDeleteKey(&ecdsaKeyData.blob);
8598}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008599
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008600INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8601
Shawn Willden22fb9c12022-06-02 14:04:33 -06008602using VsrRequirementTest = KeyMintAidlTestBase;
8603
8604TEST_P(VsrRequirementTest, Vsr13Test) {
8605 int vsr_api_level = get_vsr_api_level();
8606 if (vsr_api_level < 33) {
8607 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8608 }
8609 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8610}
8611
Eran Messerib9346f52022-12-15 14:58:34 +00008612TEST_P(VsrRequirementTest, Vsr14Test) {
8613 int vsr_api_level = get_vsr_api_level();
8614 if (vsr_api_level < 34) {
8615 GTEST_SKIP() << "Applies only to VSR API level 34, this device is: " << vsr_api_level;
8616 }
8617 EXPECT_GE(AidlVersion(), 3) << "VSR 14+ requires KeyMint version 3";
8618}
8619
Shawn Willden22fb9c12022-06-02 14:04:33 -06008620INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8621
Janis Danisevskis24c04702020-12-16 18:28:39 -08008622} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008623
8624int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008625 std::cout << "Testing ";
8626 auto halInstances =
8627 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8628 std::cout << "HAL instances:\n";
8629 for (auto& entry : halInstances) {
8630 std::cout << " " << entry << '\n';
8631 }
8632
Selene Huang31ab4042020-04-29 04:22:39 -07008633 ::testing::InitGoogleTest(&argc, argv);
8634 for (int i = 1; i < argc; ++i) {
8635 if (argv[i][0] == '-') {
8636 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008637 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8638 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008639 }
8640 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008641 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8642 dump_Attestations = true;
8643 } else {
8644 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008645 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008646 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8647 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8648 // be run in emulated environments that don't have the normal bootloader
8649 // interactions.
8650 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8651 }
Selene Huang31ab4042020-04-29 04:22:39 -07008652 }
8653 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008654 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008655}