blob: 371b58992daf941dc3f88e3968ef80b3ce9b6c26 [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
David Drysdale37af4b32021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Drysdale42fe1892021-10-14 14:43:46 +010025#include <openssl/curve25519.h>
David Zeuthene0c40892021-01-08 12:54:11 -050026#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070027#include <openssl/evp.h>
28#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050029#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070030
31#include <cutils/properties.h>
32
David Drysdale4dc01072021-04-01 12:17:35 +010033#include <android/binder_manager.h>
34
35#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080036#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070037
Shawn Willden08a7e432020-12-11 13:05:27 +000038#include <keymint_support/key_param_output.h>
39#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070040
41#include "KeyMintAidlTestBase.h"
42
Janis Danisevskis24c04702020-12-16 18:28:39 -080043using aidl::android::hardware::security::keymint::AuthorizationSet;
44using aidl::android::hardware::security::keymint::KeyCharacteristics;
45using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070046
Selene Huang31ab4042020-04-29 04:22:39 -070047namespace std {
48
Janis Danisevskis24c04702020-12-16 18:28:39 -080049using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070050
51template <>
52struct std::equal_to<KeyCharacteristics> {
53 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070054 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070055
Shawn Willden7f424372021-01-10 18:06:50 -070056 // this isn't very efficient. Oh, well.
57 AuthorizationSet a_auths(a.authorizations);
58 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070059
Shawn Willden7f424372021-01-10 18:06:50 -070060 a_auths.Sort();
61 b_auths.Sort();
62
63 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070064 }
65};
66
67} // namespace std
68
Janis Danisevskis24c04702020-12-16 18:28:39 -080069namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000070
Selene Huang31ab4042020-04-29 04:22:39 -070071namespace {
72
David Drysdalefeab5d92022-01-06 15:46:23 +000073// Maximum supported Ed25519 message size.
74const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
75
David Drysdaledbbbe2e2021-12-02 07:44:23 +000076// Whether to check that BOOT_PATCHLEVEL is populated.
77bool check_boot_pl = true;
78
Seth Moore7a55ae32021-06-23 14:28:11 -070079// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000080// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070081// is a small (roughly 1/256) chance that corrupting ciphertext still results
82// in valid PKCS7 padding.
83constexpr size_t kMaxPaddingCorruptionRetries = 8;
84
Selene Huang31ab4042020-04-29 04:22:39 -070085template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000086bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
87 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070088 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080089 if (auto p = authorizationValue(ttag, param)) {
90 return *p == expected_value;
91 }
92 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070093 });
94 return (it != set.end());
95}
96
97template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000098bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070099 auto it = std::find_if(set.begin(), set.end(),
100 [&](const KeyParameter& param) { return param.tag == tag; });
101 return (it != set.end());
102}
103
104constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
108 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
110 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
111 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
114 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
115 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
117 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
120
121string hex2str(string a) {
122 string b;
123 size_t num = a.size() / 2;
124 b.resize(num);
125 for (size_t i = 0; i < num; i++) {
126 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
127 }
128 return b;
129}
130
David Drysdaled2cc8c22021-04-15 13:29:45 +0100131string rsa_key = hex2str(
132 // RFC 5208 s5
133 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
134 "020100" // INTEGER length 1 value 0x00 (version)
135 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
136 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
137 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
138 "0500" // NULL (parameters)
139 // } end SEQUENCE (AlgorithmIdentifier)
140 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
141 // RFC 8017 A.1.2
142 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
143 "020100" // INTEGER length 1 value 0x00 (version)
144 "028181" // INTEGER length 0x81 value (modulus) ...
145 "00c6095409047d8634812d5a218176e4"
146 "5c41d60a75b13901f234226cffe77652"
147 "1c5a77b9e389417b71c0b6a44d13afe4"
148 "e4a2805d46c9da2935adb1ff0c1f24ea"
149 "06e62b20d776430a4d435157233c6f91"
150 "6783c30e310fcbd89b85c2d567711697"
151 "85ac12bca244abda72bfb19fc44d27c8"
152 "1e1d92de284f4061edfd99280745ea6d"
153 "25"
154 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
155 "028180" // INTEGER length 0x80 (privateExponent) value...
156 "1be0f04d9cae3718691f035338308e91"
157 "564b55899ffb5084d2460e6630257e05"
158 "b3ceab02972dfabcd6ce5f6ee2589eb6"
159 "7911ed0fac16e43a444b8c861e544a05"
160 "93365772f8baf6b22fc9e3c5f1024b06"
161 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
162 "ace7240290bef16c0b3f7f3cdd64ce3a"
163 "b5912cf6e32f39ab188358afcccd8081"
164 "0241" // INTEGER length 0x41 (prime1)
165 "00e4b49ef50f765d3b24dde01aceaaf1"
166 "30f2c76670a91a61ae08af497b4a82be"
167 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
168 "8c92bfab137fba2285227b83c342ff7c"
169 "55"
170 "0241" // INTEGER length 0x41 (prime2)
171 "00ddabb5839c4c7f6bf3d4183231f005"
172 "b31aa58affdda5c79e4cce217f6bc930"
173 "dbe563d480706c24e9ebfcab28a6cdef"
174 "d324b77e1bf7251b709092c24ff501fd"
175 "91"
176 "0240" // INTEGER length 0x40 (exponent1)
177 "23d4340eda3445d8cd26c14411da6fdc"
178 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
179 "842c1d280405bc2f6c1bea214a1d742a"
180 "b996b35b63a82a5e470fa88dbf823cdd"
181 "0240" // INTEGER length 0x40 (exponent2)
182 "1b7b57449ad30d1518249a5f56bb9829"
183 "4d4b6ac12ffc86940497a5a5837a6cf9"
184 "46262b494526d328c11e1126380fde04"
185 "c24f916dec250892db09a6d77cdba351"
186 "0240" // INTEGER length 0x40 (coefficient)
187 "7762cd8f4d050da56bd591adb515d24d"
188 "7ccd32cca0d05f866d583514bd7324d5"
189 "f33645e8ed8b4a1cb3cc4a1d67987399"
190 "f2a09f5b3fb68c88d5e5d90ac33492d6"
191 // } end SEQUENCE (PrivateKey)
192 // } end SEQUENCE (PrivateKeyInfo)
193);
Selene Huang31ab4042020-04-29 04:22:39 -0700194
Selene Huange5727e62021-04-13 22:41:20 -0700195/*
196 * DER-encoded PKCS#8 format RSA key. Generated using:
197 *
198 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
199 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100200string rsa_2048_key = hex2str(
201 // RFC 5208 s5
202 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
203 "020100" // INTEGER length 1 value 0x00 (version)
204 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
205 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
206 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
207 "0500" // NULL (parameters)
208 // } end SEQUENCE (AlgorithmIdentifier)
209 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
210 // RFC 8017 A.1.2
211 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
212 "020100" // INTEGER length 1 value 0x00 (version)
213 "02820101" // INTEGER length 0x101 value (modulus) ...
214 "00BEBC342B56D443B1299F9A6A7056E8"
215 "0A897E318476A5A18029E63B2ED739A6"
216 "1791D339F58DC763D9D14911F2EDEC38"
217 "3DEE11F6319B44510E7A3ECD9B79B973"
218 "82E49500ACF8117DC89CAF0E621F7775"
219 "6554A2FD4664BFE7AB8B59AB48340DBF"
220 "A27B93B5A81F6ECDEB02D0759307128D"
221 "F3E3BAD4055C8B840216DFAA5700670E"
222 "6C5126F0962FCB70FF308F25049164CC"
223 "F76CC2DA66A7DD9A81A714C2809D6918"
224 "6133D29D84568E892B6FFBF3199BDB14"
225 "383EE224407F190358F111A949552ABA"
226 "6714227D1BD7F6B20DD0CB88F9467B71"
227 "9339F33BFF35B3870B3F62204E4286B0"
228 "948EA348B524544B5F9838F29EE643B0"
229 "79EEF8A713B220D7806924CDF7295070"
230 "C5"
231 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
232 "02820100" // INTEGER length 0x100 (privateExponent) value...
233 "69F377F35F2F584EF075353CCD1CA997"
234 "38DB3DBC7C7FF35F9366CE176DFD1B13"
235 "5AB10030344ABF5FBECF1D4659FDEF1C"
236 "0FC430834BE1BE3911951377BB3D563A"
237 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
238 "2686C7B4B3C09A7B8354133E6F93F790"
239 "D59EAEB92E84C9A4339302CCE28FDF04"
240 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
241 "6AB706645BF074A4E4090D06FB163124"
242 "365FD5EE7A20D350E9958CC30D91326E"
243 "1B292E9EF5DB408EC42DAF737D201497"
244 "04D0A678A0FB5B5446863B099228A352"
245 "D604BA8091A164D01D5AB05397C71EAD"
246 "20BE2A08FC528FE442817809C787FEE4"
247 "AB97F97B9130D022153EDC6EB6CBE7B0"
248 "F8E3473F2E901209B5DB10F93604DB01"
249 "028181" // INTEGER length 0x81 (prime1)
250 "00E83C0998214941EA4F9293F1B77E2E"
251 "99E6CF305FAF358238E126124FEAF2EB"
252 "9724B2EA7B78E6032343821A80E55D1D"
253 "88FB12D220C3F41A56142FEC85796D19"
254 "17F1E8C774F142B67D3D6E7B7E6B4383"
255 "E94DB5929089DBB346D5BDAB40CC2D96"
256 "EE0409475E175C63BF78CFD744136740"
257 "838127EA723FF3FE7FA368C1311B4A4E"
258 "05"
259 "028181" // INTEGER length 0x81 (prime2)
260 "00D240FCC0F5D7715CDE21CB2DC86EA1"
261 "46132EA3B06F61FF2AF54BF38473F59D"
262 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
263 "B1B58C39F95E4798CCBB43E83D0119AC"
264 "F532F359CA743C85199F0286610E2009"
265 "97D7312917179AC9B67558773212EC96"
266 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
267 "94D94E066A0900B7B70E82A44FB30053"
268 "C1"
269 "028181" // INTEGER length 0x81 (exponent1)
270 "00AD15DA1CBD6A492B66851BA8C316D3"
271 "8AB700E2CFDDD926A658003513C54BAA"
272 "152B30021D667D20078F500F8AD3E7F3"
273 "945D74A891ED1A28EAD0FEEAEC8C14A8"
274 "E834CF46A13D1378C99D18940823CFDD"
275 "27EC5810D59339E0C34198AC638E09C8"
276 "7CBB1B634A9864AE9F4D5EB2D53514F6"
277 "7B4CAEC048C8AB849A02E397618F3271"
278 "35"
279 "028180" // INTEGER length 0x80 (exponent2)
280 "1FA2C1A5331880A92D8F3E281C617108"
281 "BF38244F16E352E69ED417C7153F9EC3"
282 "18F211839C643DCF8B4DD67CE2AC312E"
283 "95178D5D952F06B1BF779F4916924B70"
284 "F582A23F11304E02A5E7565AE22A35E7"
285 "4FECC8B6FDC93F92A1A37703E4CF0E63"
286 "783BD02EB716A7ECBBFA606B10B74D01"
287 "579522E7EF84D91FC522292108D902C1"
288 "028180" // INTEGER length 0x80 (coefficient)
289 "796FE3825F9DCC85DF22D58690065D93"
290 "898ACD65C087BEA8DA3A63BF4549B795"
291 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
292 "0D74F40DED8E1102C52152A31B6165F8"
293 "3A6722AECFCC35A493D7634664B888A0"
294 "8D3EB034F12EA28BFEE346E205D33482"
295 "7F778B16ED40872BD29FCB36536B6E93"
296 "FFB06778696B4A9D81BB0A9423E63DE5"
297 // } end SEQUENCE (PrivateKey)
298 // } end SEQUENCE (PrivateKeyInfo)
299);
Selene Huange5727e62021-04-13 22:41:20 -0700300
David Drysdaled2cc8c22021-04-15 13:29:45 +0100301string ec_256_key = hex2str(
302 // RFC 5208 s5
303 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
304 "020100" // INTEGER length 1 value 0 (version)
305 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
306 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
307 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
308 "0608" // OBJECT IDENTIFIER length 8 (param)
309 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
310 // } end SEQUENCE (AlgorithmIdentifier)
311 "046d" // OCTET STRING length 0x6d (privateKey) holding...
312 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
313 "020101" // INTEGER length 1 value 1 (version)
314 "0420" // OCTET STRING length 0x20 (privateKey)
315 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
316 "941eed09366bc03299986481f3a4d859"
317 "a144" // TAG [1] len 0x44 (publicKey) {
318 "03420004bf85d7720d07c25461683bc6"
319 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
320 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
321 "bcc41c6eb00083cf3376d11fd44949e0"
322 "b2183bfe"
323 // } end SEQUENCE (ECPrivateKey)
324 // } end SEQUENCE (PrivateKeyInfo)
325);
Selene Huang31ab4042020-04-29 04:22:39 -0700326
David Drysdaled2cc8c22021-04-15 13:29:45 +0100327string ec_521_key = hex2str(
328 // RFC 5208 s5
329 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
330 "020100" // INTEGER length 1 value 0 (version)
331 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
332 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
333 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
334 "0605" // OBJECT IDENTIFIER length 5 (param)
335 "2B81040023" // 1.3.132.0.35 (secp521r1)
336 // } end SEQUENCE (AlgorithmIdentifier)
337 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
338 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
339 "020101" // INTEGER length 1 value 1 (version)
340 "0442" // OCTET STRING length 0x42 (privateKey)
341 "0011458C586DB5DAA92AFAB03F4FE46A"
342 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
343 "9D18D7D08B5BCFA0E53C75B064AD51C4"
344 "49BAE0258D54B94B1E885DED08ED4FB2"
345 "5CE9"
346 "A18189" // TAG [1] len 0x89 (publicKey) {
347 "03818600040149EC11C6DF0FA122C6A9"
348 "AFD9754A4FA9513A627CA329E349535A"
349 "5629875A8ADFBE27DCB932C051986377"
350 "108D054C28C6F39B6F2C9AF81802F9F3"
351 "26B842FF2E5F3C00AB7635CFB36157FC"
352 "0882D574A10D839C1A0C049DC5E0D775"
353 "E2EE50671A208431BB45E78E70BEFE93"
354 "0DB34818EE4D5C26259F5C6B8E28A652"
355 "950F9F88D7B4B2C9D9"
356 // } end SEQUENCE (ECPrivateKey)
357 // } end SEQUENCE (PrivateKeyInfo)
358);
Selene Huang31ab4042020-04-29 04:22:39 -0700359
David Drysdaled2cc8c22021-04-15 13:29:45 +0100360string ec_256_key_rfc5915 = hex2str(
361 // RFC 5208 s5
362 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
363 "020100" // INTEGER length 1 value 0 (version)
364 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
365 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
366 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
367 "0608" // OBJECT IDENTIFIER length 8 (param)
368 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
369 // } end SEQUENCE (AlgorithmIdentifier)
370 "0479" // OCTET STRING length 0x79 (privateKey) holding...
371 // RFC 5915 s3
372 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
373 "020101" // INTEGER length 1 value 1 (version)
374 "0420" // OCTET STRING length 0x42 (privateKey)
375 "782370a8c8ce5537baadd04dcff079c8"
376 "158cfa9c67b818b38e8d21c9fa750c1d"
377 "a00a" // TAG [0] length 0xa (parameters)
378 "0608" // OBJECT IDENTIFIER length 8
379 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
380 // } end TAG [0]
381 "a144" // TAG [1] length 0x44 (publicKey) {
382 "0342" // BIT STRING length 0x42
383 "00" // no pad bits
384 "04e2cc561ee701da0ad0ef0d176bb0c9"
385 "19d42e79c393fdc1bd6c4010d85cf2cf"
386 "8e68c905464666f98dad4f01573ba810"
387 "78b3428570a439ba3229fbc026c55068"
388 "2f"
389 // } end SEQUENCE (ECPrivateKey)
390 // } end SEQUENCE (PrivateKeyInfo)
391);
Selene Huang31ab4042020-04-29 04:22:39 -0700392
David Drysdaled2cc8c22021-04-15 13:29:45 +0100393string ec_256_key_sec1 = hex2str(
394 // RFC 5208 s5
395 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
396 "020100" // INTEGER length 1 value 0 (version)
397 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
398 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
399 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
400 "0608" // OBJECT IDENTIFIER length 8 (param)
401 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
402 // } end SEQUENCE (AlgorithmIdentifier)
403 "046d" // OCTET STRING length 0x6d (privateKey) holding...
404 // SEC1-v2 C.4
405 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
406 "020101" // INTEGER length 1 value 0x01 (version)
407 "0420" // OCTET STRING length 0x20 (privateKey)
408 "782370a8c8ce5537baadd04dcff079c8"
409 "158cfa9c67b818b38e8d21c9fa750c1d"
410 "a144" // TAG [1] length 0x44 (publicKey) {
411 "0342" // BIT STRING length 0x42
412 "00" // no pad bits
413 "04e2cc561ee701da0ad0ef0d176bb0c9"
414 "19d42e79c393fdc1bd6c4010d85cf2cf"
415 "8e68c905464666f98dad4f01573ba810"
416 "78b3428570a439ba3229fbc026c55068"
417 "2f"
418 // } end TAG [1] (publicKey)
419 // } end SEQUENCE (PrivateKeyInfo)
420);
Selene Huang31ab4042020-04-29 04:22:39 -0700421
David Drysdale42fe1892021-10-14 14:43:46 +0100422/**
423 * Ed25519 key pair generated as follows:
424 * ```
425 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
426 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
427 * Generating a ED25519 private key writing new private key to
428 * 'ed25519_priv.key'
429 * -----
430 * % cat ed25519_priv.key
431 * -----BEGIN PRIVATE KEY-----
432 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
433 * -----END PRIVATE KEY-----
434 * % der2ascii -pem -i ed25519_priv.key
435 * SEQUENCE {
436 * INTEGER { 0 }
437 * SEQUENCE {
438 * # ed25519
439 * OBJECT_IDENTIFIER { 1.3.101.112 }
440 * }
441 * OCTET_STRING {
442 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
443 * }
444 * }
445 * % cat ed25519.pem
446 * -----BEGIN CERTIFICATE-----
447 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
448 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
449 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
450 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
451 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
452 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
453 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
454 * -----END CERTIFICATE-----
455 * % openssl x509 -in ed25519.pem -text -noout
456 * Certificate:
457 * Data:
458 * Version: 3 (0x2)
459 * Serial Number:
460 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
461 * Signature Algorithm: ED25519
462 * Issuer: CN = fake.ed25519.com
463 * Validity
464 * Not Before: Oct 20 08:27:42 2021 GMT
465 * Not After : Sep 20 08:27:42 2023 GMT
466 * Subject: CN = fake.ed25519.com
467 * Subject Public Key Info:
468 * Public Key Algorithm: ED25519
469 * ED25519 Public-Key:
470 * pub:
471 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
472 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
473 * 56:91
474 * X509v3 extensions:
475 * X509v3 Subject Key Identifier:
476 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
477 * X509v3 Authority Key Identifier:
478 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
479 *
480 * X509v3 Basic Constraints: critical
481 * CA:TRUE
482 * Signature Algorithm: ED25519
483 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
484 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
485 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
486 * e7:07:32:60:32:8d:bb:eb:f6:0f
487 * ```
488 */
489string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
490string ed25519_pkcs8_key = hex2str(
491 // RFC 5208 s5
492 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
493 "0201" // INTEGER length 1 (Version)
494 "00" // version 0
495 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
496 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
497 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
498 // } end SEQUENCE (AlgorithmIdentifier)
499 "0422" // OCTET STRING length 0x22 (PrivateKey)
500 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
501 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
502 // } end SEQUENCE (PrivateKeyInfo)
503);
504string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
505
506/**
507 * X25519 key pair generated as follows:
508 * ```
509 * % openssl genpkey -algorithm X25519 > x25519_priv.key
510 * % cat x25519_priv.key
511 * -----BEGIN PRIVATE KEY-----
512 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
513 * -----END PRIVATE KEY-----
514 * % der2ascii -pem -i x25519_priv.key
515 * SEQUENCE {
516 * INTEGER { 0 }
517 * SEQUENCE {
518 * # x25519
519 * OBJECT_IDENTIFIER { 1.3.101.110 }
520 * }
521 * OCTET_STRING {
522 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
523 * }
524 * }
525 * ```
526 */
527
528string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
529string x25519_pkcs8_key = hex2str(
530 // RFC 5208 s5
531 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
532 "0201" // INTEGER length 1 (Version)
533 "00" // version 0
534 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
535 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
536 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
537 "0422" // OCTET STRING length 0x22 (PrivateKey)
538 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
539 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
540string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
541
Selene Huang31ab4042020-04-29 04:22:39 -0700542struct RSA_Delete {
543 void operator()(RSA* p) { RSA_free(p); }
544};
545
Selene Huang31ab4042020-04-29 04:22:39 -0700546std::string make_string(const uint8_t* data, size_t length) {
547 return std::string(reinterpret_cast<const char*>(data), length);
548}
549
550template <size_t N>
551std::string make_string(const uint8_t (&a)[N]) {
552 return make_string(a, N);
553}
554
555class AidlBuf : public vector<uint8_t> {
556 typedef vector<uint8_t> super;
557
558 public:
559 AidlBuf() {}
560 AidlBuf(const super& other) : super(other) {}
561 AidlBuf(super&& other) : super(std::move(other)) {}
562 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
563
564 AidlBuf& operator=(const super& other) {
565 super::operator=(other);
566 return *this;
567 }
568
569 AidlBuf& operator=(super&& other) {
570 super::operator=(std::move(other));
571 return *this;
572 }
573
574 AidlBuf& operator=(const string& other) {
575 resize(other.size());
576 for (size_t i = 0; i < other.size(); ++i) {
577 (*this)[i] = static_cast<uint8_t>(other[i]);
578 }
579 return *this;
580 }
581
582 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
583};
584
David Drysdale4dc01072021-04-01 12:17:35 +0100585string device_suffix(const string& name) {
586 size_t pos = name.find('/');
587 if (pos == string::npos) {
588 return name;
589 }
590 return name.substr(pos + 1);
591}
592
593bool matching_rp_instance(const string& km_name,
594 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
595 string km_suffix = device_suffix(km_name);
596
597 vector<string> rp_names =
598 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
599 for (const string& rp_name : rp_names) {
600 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
601 // KeyMint instance, assume they match.
602 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
603 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
604 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
605 return true;
606 }
607 }
608 return false;
609}
610
Selene Huang31ab4042020-04-29 04:22:39 -0700611} // namespace
612
613class NewKeyGenerationTest : public KeyMintAidlTestBase {
614 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700615 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000616 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700617 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700618
Selene Huang31ab4042020-04-29 04:22:39 -0700619 // Check that some unexpected tags/values are NOT present.
620 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
621 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000622 }
623
624 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
625 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
626 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
627 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
628
629 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000630 }
631
632 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
633 // TODO(swillden): Distinguish which params should be in which auth list.
634 AuthorizationSet auths;
635 for (auto& entry : keyCharacteristics) {
636 auths.push_back(AuthorizationSet(entry.authorizations));
637 }
638 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
639
640 // Verify that App data, ROT and auth timeout are NOT included.
641 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
642 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700643 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
644
David Drysdaled2cc8c22021-04-15 13:29:45 +0100645 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
646 // never adds it.
647 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
648
David Drysdale7de9feb2021-03-05 14:56:19 +0000649 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700650 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000651 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700652 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700653 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000654 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700655 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000656
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000657 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100658 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
659 EXPECT_TRUE(vendor_pl);
660 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000661
662 // Should include boot patchlevel (but there are some test scenarios where this is not
663 // possible).
664 if (check_boot_pl) {
665 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
666 EXPECT_TRUE(boot_pl);
667 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100668
David Drysdale7de9feb2021-03-05 14:56:19 +0000669 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700670 }
671};
672
673/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000674 * NewKeyGenerationTest.Aes
675 *
676 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
677 * have correct characteristics.
678 */
679TEST_P(NewKeyGenerationTest, Aes) {
680 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
681 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
682 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
683 SCOPED_TRACE(testing::Message()
684 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
685 vector<uint8_t> key_blob;
686 vector<KeyCharacteristics> key_characteristics;
687 auto builder = AuthorizationSetBuilder()
688 .AesEncryptionKey(key_size)
689 .BlockMode(block_mode)
690 .Padding(padding_mode)
691 .SetDefaultValidity();
692 if (block_mode == BlockMode::GCM) {
693 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
694 }
695 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
696
697 EXPECT_GT(key_blob.size(), 0U);
698 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100699 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000700
701 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
702
703 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
704 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
705 << "Key size " << key_size << "missing";
706
707 CheckedDeleteKey(&key_blob);
708 }
709 }
710 }
711}
712
713/*
714 * NewKeyGenerationTest.AesInvalidSize
715 *
716 * Verifies that specifying an invalid key size for AES key generation returns
717 * UNSUPPORTED_KEY_SIZE.
718 */
719TEST_P(NewKeyGenerationTest, AesInvalidSize) {
720 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
721 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
722 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
723 SCOPED_TRACE(testing::Message()
724 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
725 vector<uint8_t> key_blob;
726 vector<KeyCharacteristics> key_characteristics;
727 auto builder = AuthorizationSetBuilder()
728 .AesEncryptionKey(key_size)
729 .BlockMode(block_mode)
730 .Padding(padding_mode)
731 .SetDefaultValidity();
732 if (block_mode == BlockMode::GCM) {
733 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
734 }
735 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
736 GenerateKey(builder, &key_blob, &key_characteristics));
737 }
738 }
739 }
740
741 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
742 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
743 vector<uint8_t> key_blob;
744 vector<KeyCharacteristics> key_characteristics;
745 // No key size specified
746 auto builder = AuthorizationSetBuilder()
747 .Authorization(TAG_ALGORITHM, Algorithm::AES)
748 .BlockMode(block_mode)
749 .Padding(padding_mode)
750 .SetDefaultValidity();
751 if (block_mode == BlockMode::GCM) {
752 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
753 }
754 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
755 GenerateKey(builder, &key_blob, &key_characteristics));
756 }
757 }
758}
759
760/*
761 * NewKeyGenerationTest.AesInvalidPadding
762 *
763 * Verifies that specifying an invalid padding on AES keys gives a failure
764 * somewhere along the way.
765 */
766TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
767 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
768 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
769 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
770 SCOPED_TRACE(testing::Message()
771 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000772 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800773 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000774 .AesEncryptionKey(key_size)
775 .BlockMode(block_mode)
776 .Padding(padding_mode)
777 .SetDefaultValidity();
778 if (block_mode == BlockMode::GCM) {
779 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
780 }
781
Tommy Chiu3950b452021-05-03 22:01:46 +0800782 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000783 if (result == ErrorCode::OK) {
784 // Key creation was OK but has generated a key that cannot be used.
785 auto params =
786 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800787 if (block_mode == BlockMode::GCM) {
788 params.Authorization(TAG_MAC_LENGTH, 128);
789 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000790 auto result = Begin(KeyPurpose::ENCRYPT, params);
791 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100792 result == ErrorCode::INVALID_KEY_BLOB)
793 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000794 } else {
795 // The KeyMint implementation detected that the generated key
796 // is unusable.
797 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
798 }
799 }
800 }
801 }
802}
803
804/*
805 * NewKeyGenerationTest.AesGcmMissingMinMac
806 *
807 * Verifies that specifying an invalid key size for AES key generation returns
808 * UNSUPPORTED_KEY_SIZE.
809 */
810TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
811 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
812 BlockMode block_mode = BlockMode::GCM;
813 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
814 SCOPED_TRACE(testing::Message()
815 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
816 vector<uint8_t> key_blob;
817 vector<KeyCharacteristics> key_characteristics;
818 // No MIN_MAC_LENGTH provided.
819 auto builder = AuthorizationSetBuilder()
820 .AesEncryptionKey(key_size)
821 .BlockMode(block_mode)
822 .Padding(padding_mode)
823 .SetDefaultValidity();
824 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
825 GenerateKey(builder, &key_blob, &key_characteristics));
826 }
827 }
828}
829
830/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100831 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
832 *
833 * Verifies that specifying an invalid min MAC size for AES key generation returns
834 * UNSUPPORTED_MIN_MAC_LENGTH.
835 */
836TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
837 for (size_t min_mac_len : {88, 136}) {
838 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
839 BlockMode block_mode = BlockMode::GCM;
840 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
841 SCOPED_TRACE(testing::Message()
842 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
843 vector<uint8_t> key_blob;
844 vector<KeyCharacteristics> key_characteristics;
845 auto builder = AuthorizationSetBuilder()
846 .AesEncryptionKey(key_size)
847 .BlockMode(block_mode)
848 .Padding(padding_mode)
849 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
850 .SetDefaultValidity();
851 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
852 GenerateKey(builder, &key_blob, &key_characteristics));
853 }
854 }
855 }
856}
857
858/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000859 * NewKeyGenerationTest.TripleDes
860 *
861 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
862 * have correct characteristics.
863 */
864TEST_P(NewKeyGenerationTest, TripleDes) {
865 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
866 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
867 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
868 SCOPED_TRACE(testing::Message()
869 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
870 vector<uint8_t> key_blob;
871 vector<KeyCharacteristics> key_characteristics;
872 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
873 .TripleDesEncryptionKey(key_size)
874 .BlockMode(block_mode)
875 .Padding(padding_mode)
876 .Authorization(TAG_NO_AUTH_REQUIRED)
877 .SetDefaultValidity(),
878 &key_blob, &key_characteristics));
879
880 EXPECT_GT(key_blob.size(), 0U);
881 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100882 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000883
884 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
885
886 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
887 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
888 << "Key size " << key_size << "missing";
889
890 CheckedDeleteKey(&key_blob);
891 }
892 }
893 }
894}
895
896/*
897 * NewKeyGenerationTest.TripleDesWithAttestation
898 *
899 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
900 * have correct characteristics.
901 *
902 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
903 * put in a certificate) but which isn't an error.
904 */
905TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
906 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
907 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
908 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
909 SCOPED_TRACE(testing::Message()
910 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
911
912 auto challenge = "hello";
913 auto app_id = "foo";
914
915 vector<uint8_t> key_blob;
916 vector<KeyCharacteristics> key_characteristics;
917 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
918 .TripleDesEncryptionKey(key_size)
919 .BlockMode(block_mode)
920 .Padding(padding_mode)
921 .Authorization(TAG_NO_AUTH_REQUIRED)
922 .AttestationChallenge(challenge)
923 .AttestationApplicationId(app_id)
924 .SetDefaultValidity(),
925 &key_blob, &key_characteristics));
926
927 EXPECT_GT(key_blob.size(), 0U);
928 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100929 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000930
931 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
932
933 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
934 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
935 << "Key size " << key_size << "missing";
936
937 CheckedDeleteKey(&key_blob);
938 }
939 }
940 }
941}
942
943/*
944 * NewKeyGenerationTest.TripleDesInvalidSize
945 *
946 * Verifies that specifying an invalid key size for 3-DES key generation returns
947 * UNSUPPORTED_KEY_SIZE.
948 */
949TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
950 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
951 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
952 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
953 SCOPED_TRACE(testing::Message()
954 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
955 vector<uint8_t> key_blob;
956 vector<KeyCharacteristics> key_characteristics;
957 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
958 GenerateKey(AuthorizationSetBuilder()
959 .TripleDesEncryptionKey(key_size)
960 .BlockMode(block_mode)
961 .Padding(padding_mode)
962 .Authorization(TAG_NO_AUTH_REQUIRED)
963 .SetDefaultValidity(),
964 &key_blob, &key_characteristics));
965 }
966 }
967 }
968
969 // Omitting the key size fails.
970 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
971 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
972 SCOPED_TRACE(testing::Message()
973 << "3DES-default-" << block_mode << "-" << padding_mode);
974 vector<uint8_t> key_blob;
975 vector<KeyCharacteristics> key_characteristics;
976 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
977 GenerateKey(AuthorizationSetBuilder()
978 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
979 .BlockMode(block_mode)
980 .Padding(padding_mode)
981 .Authorization(TAG_NO_AUTH_REQUIRED)
982 .SetDefaultValidity(),
983 &key_blob, &key_characteristics));
984 }
985 }
986}
987
988/*
Selene Huang31ab4042020-04-29 04:22:39 -0700989 * NewKeyGenerationTest.Rsa
990 *
991 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
992 * have correct characteristics.
993 */
994TEST_P(NewKeyGenerationTest, Rsa) {
995 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
996 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700997 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700998 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
999 .RsaSigningKey(key_size, 65537)
1000 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001001 .Padding(PaddingMode::NONE)
1002 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001003 &key_blob, &key_characteristics));
1004
1005 ASSERT_GT(key_blob.size(), 0U);
1006 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001007 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001008
Shawn Willden7f424372021-01-10 18:06:50 -07001009 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001010
1011 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1012 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1013 << "Key size " << key_size << "missing";
1014 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1015
1016 CheckedDeleteKey(&key_blob);
1017 }
1018}
1019
1020/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001021 * NewKeyGenerationTest.RsaWithMissingValidity
1022 *
1023 * Verifies that keymint returns an error while generating asymmetric key
1024 * without providing NOT_BEFORE and NOT_AFTER parameters.
1025 */
1026TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
1027 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1028 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1029 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1030
1031 vector<uint8_t> key_blob;
1032 vector<KeyCharacteristics> key_characteristics;
1033 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1034 GenerateKey(AuthorizationSetBuilder()
1035 .RsaSigningKey(2048, 65537)
1036 .Digest(Digest::NONE)
1037 .Padding(PaddingMode::NONE)
1038 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1039 kUndefinedExpirationDateTime),
1040 &key_blob, &key_characteristics));
1041
1042 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1043 GenerateKey(AuthorizationSetBuilder()
1044 .RsaSigningKey(2048, 65537)
1045 .Digest(Digest::NONE)
1046 .Padding(PaddingMode::NONE)
1047 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1048 &key_blob, &key_characteristics));
1049}
1050
1051/*
Qi Wud22ec842020-11-26 13:27:53 +08001052 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001053 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001054 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1055 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001056 */
1057TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001058 auto challenge = "hello";
1059 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001060
Selene Huang6e46f142021-04-20 19:20:11 -07001061 auto subject = "cert subj 2";
1062 vector<uint8_t> subject_der(make_name_from_str(subject));
1063
1064 uint64_t serial_int = 66;
1065 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1066
Selene Huang4f64c222021-04-13 19:54:36 -07001067 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001068 vector<uint8_t> key_blob;
1069 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001070 auto builder = AuthorizationSetBuilder()
1071 .RsaSigningKey(key_size, 65537)
1072 .Digest(Digest::NONE)
1073 .Padding(PaddingMode::NONE)
1074 .AttestationChallenge(challenge)
1075 .AttestationApplicationId(app_id)
1076 .Authorization(TAG_NO_AUTH_REQUIRED)
1077 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1078 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1079 .SetDefaultValidity();
1080
1081 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001082 // Strongbox may not support factory provisioned attestation key.
1083 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001084 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1085 result = GenerateKeyWithSelfSignedAttestKey(
1086 AuthorizationSetBuilder()
1087 .RsaKey(key_size, 65537)
1088 .AttestKey()
1089 .SetDefaultValidity(), /* attest key params */
1090 builder, &key_blob, &key_characteristics);
1091 }
subrahmanyaman05642492022-02-05 07:10:56 +00001092 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001093 ASSERT_EQ(ErrorCode::OK, result);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001094 ASSERT_GT(key_blob.size(), 0U);
1095 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001096 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001097
1098 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1099
1100 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1101 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1102 << "Key size " << key_size << "missing";
1103 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1104
David Drysdalea8a888e2022-06-08 12:43:56 +01001105 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001106 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001107 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001108
1109 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1110 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001111 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001112 sw_enforced, hw_enforced, SecLevel(),
1113 cert_chain_[0].encodedCertificate));
1114
1115 CheckedDeleteKey(&key_blob);
1116 }
1117}
1118
1119/*
David Drysdale4dc01072021-04-01 12:17:35 +01001120 * NewKeyGenerationTest.RsaWithRpkAttestation
1121 *
1122 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
1123 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale0fce69d2021-04-13 17:22:13 +01001124 *
1125 * This test is disabled because the KeyMint specification does not require that implementations
1126 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
1127 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +01001128 */
David Drysdale0fce69d2021-04-13 17:22:13 +01001129TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +01001130 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
1131 // instance.
1132 std::shared_ptr<IRemotelyProvisionedComponent> rp;
1133 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
1134 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
1135
1136 // Generate a P-256 keypair to use as an attestation key.
1137 MacedPublicKey macedPubKey;
1138 std::vector<uint8_t> privateKeyBlob;
1139 auto status =
1140 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1141 ASSERT_TRUE(status.isOk());
1142 vector<uint8_t> coseKeyData;
1143 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1144
1145 AttestationKey attestation_key;
1146 attestation_key.keyBlob = std::move(privateKeyBlob);
1147 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1148
1149 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1150 auto challenge = "hello";
1151 auto app_id = "foo";
1152
1153 vector<uint8_t> key_blob;
1154 vector<KeyCharacteristics> key_characteristics;
1155 ASSERT_EQ(ErrorCode::OK,
1156 GenerateKey(AuthorizationSetBuilder()
1157 .RsaSigningKey(key_size, 65537)
1158 .Digest(Digest::NONE)
1159 .Padding(PaddingMode::NONE)
1160 .AttestationChallenge(challenge)
1161 .AttestationApplicationId(app_id)
1162 .Authorization(TAG_NO_AUTH_REQUIRED)
1163 .SetDefaultValidity(),
1164 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1165
1166 ASSERT_GT(key_blob.size(), 0U);
1167 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001168 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001169
1170 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1171
1172 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1173 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1174 << "Key size " << key_size << "missing";
1175 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1176
1177 // Attestation by itself is not valid (last entry is not self-signed).
1178 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1179
1180 // The signature over the attested key should correspond to the P256 public key.
David Drysdalea8a888e2022-06-08 12:43:56 +01001181 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale4dc01072021-04-01 12:17:35 +01001182 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1183 ASSERT_TRUE(key_cert.get());
1184 EVP_PKEY_Ptr signing_pubkey;
1185 p256_pub_key(coseKeyData, &signing_pubkey);
1186 ASSERT_TRUE(signing_pubkey.get());
1187
1188 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1189 << "Verification of attested certificate failed "
1190 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1191
1192 CheckedDeleteKey(&key_blob);
1193 }
1194}
1195
1196/*
Selene Huang4f64c222021-04-13 19:54:36 -07001197 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1198 *
1199 * Verifies that keymint attestation for RSA encryption keys with challenge and
1200 * app id is also successful.
1201 */
1202TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1203 auto key_size = 2048;
1204 auto challenge = "hello";
1205 auto app_id = "foo";
1206
Selene Huang6e46f142021-04-20 19:20:11 -07001207 auto subject = "subj 2";
1208 vector<uint8_t> subject_der(make_name_from_str(subject));
1209
1210 uint64_t serial_int = 111166;
1211 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1212
Selene Huang4f64c222021-04-13 19:54:36 -07001213 vector<uint8_t> key_blob;
1214 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001215 auto builder = AuthorizationSetBuilder()
1216 .RsaEncryptionKey(key_size, 65537)
1217 .Padding(PaddingMode::NONE)
1218 .AttestationChallenge(challenge)
1219 .AttestationApplicationId(app_id)
1220 .Authorization(TAG_NO_AUTH_REQUIRED)
1221 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1222 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1223 .SetDefaultValidity();
1224
1225 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001226 // Strongbox may not support factory provisioned attestation key.
1227 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001228 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1229 result = GenerateKeyWithSelfSignedAttestKey(
1230 AuthorizationSetBuilder()
1231 .RsaKey(key_size, 65537)
1232 .AttestKey()
1233 .SetDefaultValidity(), /* attest key params */
1234 builder, &key_blob, &key_characteristics);
1235 }
subrahmanyaman05642492022-02-05 07:10:56 +00001236 }
1237 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001238
1239 ASSERT_GT(key_blob.size(), 0U);
1240 AuthorizationSet auths;
1241 for (auto& entry : key_characteristics) {
1242 auths.push_back(AuthorizationSet(entry.authorizations));
1243 }
1244
1245 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1246 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1247
1248 // Verify that App data and ROT are NOT included.
1249 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1250 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1251
1252 // Check that some unexpected tags/values are NOT present.
1253 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1254 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1255
1256 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1257
1258 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1259 ASSERT_TRUE(os_ver);
1260 EXPECT_EQ(*os_ver, os_version());
1261
1262 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1263
1264 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1265 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1266 << "Key size " << key_size << "missing";
1267 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1268
David Drysdalea8a888e2022-06-08 12:43:56 +01001269 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001270 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001271 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001272
1273 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1274 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001275 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001276 sw_enforced, hw_enforced, SecLevel(),
1277 cert_chain_[0].encodedCertificate));
1278
1279 CheckedDeleteKey(&key_blob);
1280}
1281
1282/*
1283 * NewKeyGenerationTest.RsaWithSelfSign
1284 *
1285 * Verifies that attesting to RSA key generation is successful, and returns
1286 * self signed certificate if no challenge is provided. And signing etc
1287 * works as expected.
1288 */
1289TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001290 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1291 vector<uint8_t> subject_der(make_name_from_str(subject));
1292
1293 uint64_t serial_int = 0;
1294 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1295
Selene Huang4f64c222021-04-13 19:54:36 -07001296 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1297 vector<uint8_t> key_blob;
1298 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001299 ASSERT_EQ(ErrorCode::OK,
1300 GenerateKey(AuthorizationSetBuilder()
1301 .RsaSigningKey(key_size, 65537)
1302 .Digest(Digest::NONE)
1303 .Padding(PaddingMode::NONE)
1304 .Authorization(TAG_NO_AUTH_REQUIRED)
1305 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1306 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1307 .SetDefaultValidity(),
1308 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001309
1310 ASSERT_GT(key_blob.size(), 0U);
1311 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001312 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001313
1314 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1315
1316 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1317 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1318 << "Key size " << key_size << "missing";
1319 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1320
David Drysdalea8a888e2022-06-08 12:43:56 +01001321 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang6e46f142021-04-20 19:20:11 -07001322 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001323 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001324
1325 CheckedDeleteKey(&key_blob);
1326 }
1327}
1328
1329/*
1330 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1331 *
1332 * Verifies that attesting to RSA checks for missing app ID.
1333 */
1334TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1335 auto challenge = "hello";
1336 vector<uint8_t> key_blob;
1337 vector<KeyCharacteristics> key_characteristics;
1338
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001339 auto builder = AuthorizationSetBuilder()
1340 .RsaSigningKey(2048, 65537)
1341 .Digest(Digest::NONE)
1342 .Padding(PaddingMode::NONE)
1343 .AttestationChallenge(challenge)
1344 .Authorization(TAG_NO_AUTH_REQUIRED)
1345 .SetDefaultValidity();
1346
1347 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001348 // Strongbox may not support factory provisioned attestation key.
1349 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001350 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1351 result = GenerateKeyWithSelfSignedAttestKey(
1352 AuthorizationSetBuilder()
1353 .RsaKey(2048, 65537)
1354 .AttestKey()
1355 .SetDefaultValidity(), /* attest key params */
1356 builder, &key_blob, &key_characteristics);
1357 }
subrahmanyaman05642492022-02-05 07:10:56 +00001358 }
1359 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001360}
1361
1362/*
1363 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1364 *
1365 * Verifies that attesting to RSA ignores app id if challenge is missing.
1366 */
1367TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1368 auto key_size = 2048;
1369 auto app_id = "foo";
1370
Selene Huang6e46f142021-04-20 19:20:11 -07001371 auto subject = "cert subj 2";
1372 vector<uint8_t> subject_der(make_name_from_str(subject));
1373
1374 uint64_t serial_int = 1;
1375 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1376
Selene Huang4f64c222021-04-13 19:54:36 -07001377 vector<uint8_t> key_blob;
1378 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001379 ASSERT_EQ(ErrorCode::OK,
1380 GenerateKey(AuthorizationSetBuilder()
1381 .RsaSigningKey(key_size, 65537)
1382 .Digest(Digest::NONE)
1383 .Padding(PaddingMode::NONE)
1384 .AttestationApplicationId(app_id)
1385 .Authorization(TAG_NO_AUTH_REQUIRED)
1386 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1387 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1388 .SetDefaultValidity(),
1389 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001390
1391 ASSERT_GT(key_blob.size(), 0U);
1392 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001393 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001394
1395 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1396
1397 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1398 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1399 << "Key size " << key_size << "missing";
1400 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1401
David Drysdalea8a888e2022-06-08 12:43:56 +01001402 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001403 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001404 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1405 ASSERT_EQ(cert_chain_.size(), 1);
1406
1407 CheckedDeleteKey(&key_blob);
1408}
1409
1410/*
Qi Wud22ec842020-11-26 13:27:53 +08001411 * NewKeyGenerationTest.LimitedUsageRsa
1412 *
1413 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1414 * resulting keys have correct characteristics.
1415 */
1416TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1417 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1418 vector<uint8_t> key_blob;
1419 vector<KeyCharacteristics> key_characteristics;
1420 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1421 .RsaSigningKey(key_size, 65537)
1422 .Digest(Digest::NONE)
1423 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001424 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1425 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001426 &key_blob, &key_characteristics));
1427
1428 ASSERT_GT(key_blob.size(), 0U);
1429 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001430 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001431
1432 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1433
1434 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1435 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1436 << "Key size " << key_size << "missing";
1437 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1438
1439 // Check the usage count limit tag appears in the authorizations.
1440 AuthorizationSet auths;
1441 for (auto& entry : key_characteristics) {
1442 auths.push_back(AuthorizationSet(entry.authorizations));
1443 }
1444 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1445 << "key usage count limit " << 1U << " missing";
1446
1447 CheckedDeleteKey(&key_blob);
1448 }
1449}
1450
1451/*
Qi Wubeefae42021-01-28 23:16:37 +08001452 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1453 *
1454 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1455 * resulting keys have correct characteristics and attestation.
1456 */
1457TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001458 auto challenge = "hello";
1459 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001460
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 = 66;
1465 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1466
Selene Huang4f64c222021-04-13 19:54:36 -07001467 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001468 vector<uint8_t> key_blob;
1469 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001470 auto builder = AuthorizationSetBuilder()
1471 .RsaSigningKey(key_size, 65537)
1472 .Digest(Digest::NONE)
1473 .Padding(PaddingMode::NONE)
1474 .AttestationChallenge(challenge)
1475 .AttestationApplicationId(app_id)
1476 .Authorization(TAG_NO_AUTH_REQUIRED)
1477 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1478 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1479 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1480 .SetDefaultValidity();
1481
1482 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001483 // Strongbox may not support factory provisioned attestation key.
1484 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001485 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1486 result = GenerateKeyWithSelfSignedAttestKey(
1487 AuthorizationSetBuilder()
1488 .RsaKey(key_size, 65537)
1489 .AttestKey()
1490 .SetDefaultValidity(), /* attest key params */
1491 builder, &key_blob, &key_characteristics);
1492 }
subrahmanyaman05642492022-02-05 07:10:56 +00001493 }
1494 ASSERT_EQ(ErrorCode::OK, result);
Qi Wubeefae42021-01-28 23:16:37 +08001495
1496 ASSERT_GT(key_blob.size(), 0U);
1497 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001498 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001499
1500 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1501
1502 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1503 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1504 << "Key size " << key_size << "missing";
1505 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1506
1507 // Check the usage count limit tag appears in the authorizations.
1508 AuthorizationSet auths;
1509 for (auto& entry : key_characteristics) {
1510 auths.push_back(AuthorizationSet(entry.authorizations));
1511 }
1512 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1513 << "key usage count limit " << 1U << " missing";
1514
1515 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001516 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001517 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001518 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001519
1520 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1521 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001522 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001523 sw_enforced, hw_enforced, SecLevel(),
1524 cert_chain_[0].encodedCertificate));
1525
1526 CheckedDeleteKey(&key_blob);
1527 }
1528}
1529
1530/*
Selene Huang31ab4042020-04-29 04:22:39 -07001531 * NewKeyGenerationTest.NoInvalidRsaSizes
1532 *
1533 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1534 */
1535TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1536 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1537 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001538 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001539 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1540 GenerateKey(AuthorizationSetBuilder()
1541 .RsaSigningKey(key_size, 65537)
1542 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001543 .Padding(PaddingMode::NONE)
1544 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001545 &key_blob, &key_characteristics));
1546 }
1547}
1548
1549/*
1550 * NewKeyGenerationTest.RsaNoDefaultSize
1551 *
1552 * Verifies that failing to specify a key size for RSA key generation returns
1553 * UNSUPPORTED_KEY_SIZE.
1554 */
1555TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1556 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1557 GenerateKey(AuthorizationSetBuilder()
1558 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1559 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001560 .SigningKey()
1561 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001562}
1563
1564/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001565 * NewKeyGenerationTest.RsaMissingParams
1566 *
1567 * Verifies that omitting optional tags works.
1568 */
1569TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1570 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1571 ASSERT_EQ(ErrorCode::OK,
1572 GenerateKey(
1573 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1574 CheckedDeleteKey();
1575 }
1576}
1577
1578/*
Selene Huang31ab4042020-04-29 04:22:39 -07001579 * NewKeyGenerationTest.Ecdsa
1580 *
David Drysdale42fe1892021-10-14 14:43:46 +01001581 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001582 * have correct characteristics.
1583 */
1584TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001585 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001586 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001587 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001588 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001589 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001590 .Digest(Digest::NONE)
1591 .SetDefaultValidity(),
1592 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001593 ASSERT_GT(key_blob.size(), 0U);
1594 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001595 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001596
Shawn Willden7f424372021-01-10 18:06:50 -07001597 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001598
1599 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001600 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001601
1602 CheckedDeleteKey(&key_blob);
1603 }
1604}
1605
1606/*
David Drysdale42fe1892021-10-14 14:43:46 +01001607 * NewKeyGenerationTest.EcdsaCurve25519
1608 *
1609 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1610 * has correct characteristics.
1611 */
1612TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1613 if (!Curve25519Supported()) {
1614 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1615 }
1616
1617 EcCurve curve = EcCurve::CURVE_25519;
1618 vector<uint8_t> key_blob;
1619 vector<KeyCharacteristics> key_characteristics;
1620 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1621 .EcdsaSigningKey(curve)
1622 .Digest(Digest::NONE)
1623 .SetDefaultValidity(),
1624 &key_blob, &key_characteristics);
1625 ASSERT_EQ(result, ErrorCode::OK);
1626 ASSERT_GT(key_blob.size(), 0U);
1627
1628 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1629 ASSERT_GT(cert_chain_.size(), 0);
1630
1631 CheckBaseParams(key_characteristics);
1632 CheckCharacteristics(key_blob, key_characteristics);
1633
1634 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1635
1636 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1637 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1638
1639 CheckedDeleteKey(&key_blob);
1640}
1641
1642/*
1643 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1644 *
1645 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1646 * SIGN and AGREE_KEY.
1647 */
1648TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1649 if (!Curve25519Supported()) {
1650 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1651 }
1652
1653 EcCurve curve = EcCurve::CURVE_25519;
1654 vector<uint8_t> key_blob;
1655 vector<KeyCharacteristics> key_characteristics;
1656 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1657 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1658 .EcdsaSigningKey(curve)
1659 .Digest(Digest::NONE)
1660 .SetDefaultValidity(),
1661 &key_blob, &key_characteristics);
1662 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1663}
1664
1665/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001666 * NewKeyGenerationTest.EcdsaWithMissingValidity
1667 *
1668 * Verifies that keymint returns an error while generating asymmetric key
1669 * without providing NOT_BEFORE and NOT_AFTER parameters.
1670 */
1671TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
1672 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1673 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1674 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1675
1676 vector<uint8_t> key_blob;
1677 vector<KeyCharacteristics> key_characteristics;
1678 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1679 GenerateKey(AuthorizationSetBuilder()
1680 .EcdsaSigningKey(EcCurve::P_256)
1681 .Digest(Digest::NONE)
1682 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1683 kUndefinedExpirationDateTime),
1684 &key_blob, &key_characteristics));
1685
1686 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1687 GenerateKey(AuthorizationSetBuilder()
1688 .EcdsaSigningKey(EcCurve::P_256)
1689 .Digest(Digest::NONE)
1690 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1691 &key_blob, &key_characteristics));
1692}
1693
1694/*
Selene Huang4f64c222021-04-13 19:54:36 -07001695 * NewKeyGenerationTest.EcdsaAttestation
1696 *
1697 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1698 * an attestation will be generated.
1699 */
1700TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1701 auto challenge = "hello";
1702 auto app_id = "foo";
1703
Selene Huang6e46f142021-04-20 19:20:11 -07001704 auto subject = "cert subj 2";
1705 vector<uint8_t> subject_der(make_name_from_str(subject));
1706
1707 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1708 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1709
David Drysdaledf09e542021-06-08 15:46:11 +01001710 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001711 vector<uint8_t> key_blob;
1712 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001713 auto builder = AuthorizationSetBuilder()
1714 .Authorization(TAG_NO_AUTH_REQUIRED)
1715 .EcdsaSigningKey(curve)
1716 .Digest(Digest::NONE)
1717 .AttestationChallenge(challenge)
1718 .AttestationApplicationId(app_id)
1719 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1720 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1721 .SetDefaultValidity();
1722
1723 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001724 // Strongbox may not support factory provisioned attestation key.
1725 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001726 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1727 result = GenerateKeyWithSelfSignedAttestKey(
1728 AuthorizationSetBuilder()
1729 .EcdsaKey(curve)
1730 .AttestKey()
1731 .SetDefaultValidity(), /* attest key params */
1732 builder, &key_blob, &key_characteristics);
1733 }
subrahmanyaman05642492022-02-05 07:10:56 +00001734 }
1735 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001736 ASSERT_GT(key_blob.size(), 0U);
1737 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001738 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001739
1740 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1741
1742 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001743 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001744
1745 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1746 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001747 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001748
1749 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1750 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001751 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001752 sw_enforced, hw_enforced, SecLevel(),
1753 cert_chain_[0].encodedCertificate));
1754
1755 CheckedDeleteKey(&key_blob);
1756 }
1757}
1758
1759/*
David Drysdale42fe1892021-10-14 14:43:46 +01001760 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1761 *
1762 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1763 * an attestation will be generated.
1764 */
1765TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1766 if (!Curve25519Supported()) {
1767 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1768 }
1769
1770 EcCurve curve = EcCurve::CURVE_25519;
1771 auto challenge = "hello";
1772 auto app_id = "foo";
1773
1774 auto subject = "cert subj 2";
1775 vector<uint8_t> subject_der(make_name_from_str(subject));
1776
1777 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1778 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1779
1780 vector<uint8_t> key_blob;
1781 vector<KeyCharacteristics> key_characteristics;
1782 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1783 .Authorization(TAG_NO_AUTH_REQUIRED)
1784 .EcdsaSigningKey(curve)
1785 .Digest(Digest::NONE)
1786 .AttestationChallenge(challenge)
1787 .AttestationApplicationId(app_id)
1788 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1789 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1790 .SetDefaultValidity(),
1791 &key_blob, &key_characteristics);
1792 ASSERT_EQ(ErrorCode::OK, result);
1793 ASSERT_GT(key_blob.size(), 0U);
1794 CheckBaseParams(key_characteristics);
1795 CheckCharacteristics(key_blob, key_characteristics);
1796
1797 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1798
1799 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1800 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1801
1802 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1803 ASSERT_GT(cert_chain_.size(), 0);
1804 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1805
1806 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1807 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1808 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1809 sw_enforced, hw_enforced, SecLevel(),
1810 cert_chain_[0].encodedCertificate));
1811
1812 CheckedDeleteKey(&key_blob);
1813}
1814
1815/*
David Drysdale37af4b32021-05-14 16:46:59 +01001816 * NewKeyGenerationTest.EcdsaAttestationTags
1817 *
1818 * Verifies that creation of an attested ECDSA key includes various tags in the
1819 * attestation extension.
1820 */
1821TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1822 auto challenge = "hello";
1823 auto app_id = "foo";
1824 auto subject = "cert subj 2";
1825 vector<uint8_t> subject_der(make_name_from_str(subject));
1826 uint64_t serial_int = 0x1010;
1827 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1828 const AuthorizationSetBuilder base_builder =
1829 AuthorizationSetBuilder()
1830 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001831 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001832 .Digest(Digest::NONE)
1833 .AttestationChallenge(challenge)
1834 .AttestationApplicationId(app_id)
1835 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1836 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1837 .SetDefaultValidity();
1838
1839 // Various tags that map to fields in the attestation extension ASN.1 schema.
1840 auto extra_tags = AuthorizationSetBuilder()
1841 .Authorization(TAG_ROLLBACK_RESISTANCE)
1842 .Authorization(TAG_EARLY_BOOT_ONLY)
1843 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1844 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1845 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1846 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1847 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1848 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1849 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1850 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1851 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1852 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001853
David Drysdale37af4b32021-05-14 16:46:59 +01001854 for (const KeyParameter& tag : extra_tags) {
1855 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1856 vector<uint8_t> key_blob;
1857 vector<KeyCharacteristics> key_characteristics;
1858 AuthorizationSetBuilder builder = base_builder;
1859 builder.push_back(tag);
1860 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1861 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1862 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1863 continue;
1864 }
Seth Mooreb393b082021-07-12 14:18:28 -07001865 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1866 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001867 continue;
1868 }
subrahmanyaman05642492022-02-05 07:10:56 +00001869 // Strongbox may not support factory provisioned attestation key.
1870 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001871 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1872 result = GenerateKeyWithSelfSignedAttestKey(
1873 AuthorizationSetBuilder()
1874 .EcdsaKey(EcCurve::P_256)
1875 .AttestKey()
1876 .SetDefaultValidity(), /* attest key params */
1877 builder, &key_blob, &key_characteristics);
1878 }
subrahmanyaman05642492022-02-05 07:10:56 +00001879 }
David Drysdale37af4b32021-05-14 16:46:59 +01001880 ASSERT_EQ(result, ErrorCode::OK);
1881 ASSERT_GT(key_blob.size(), 0U);
1882
1883 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1884 ASSERT_GT(cert_chain_.size(), 0);
1885 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1886
1887 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1888 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001889 // Some tags are optional, so don't require them to be in the enforcements.
1890 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001891 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1892 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1893 }
1894
1895 // Verifying the attestation record will check for the specific tag because
1896 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001897 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1898 hw_enforced, SecLevel(),
1899 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01001900
1901 CheckedDeleteKey(&key_blob);
1902 }
1903
David Drysdalec53b7d92021-10-11 12:35:58 +01001904 // Collection of invalid attestation ID tags.
1905 auto invalid_tags =
1906 AuthorizationSetBuilder()
1907 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1908 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1909 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1910 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1911 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
1912 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
1913 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
1914 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01001915 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01001916 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01001917 vector<uint8_t> key_blob;
1918 vector<KeyCharacteristics> key_characteristics;
1919 AuthorizationSetBuilder builder =
1920 AuthorizationSetBuilder()
1921 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001922 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001923 .Digest(Digest::NONE)
1924 .AttestationChallenge(challenge)
1925 .AttestationApplicationId(app_id)
1926 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1927 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1928 .SetDefaultValidity();
1929 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001930
1931 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
1932 // Strongbox may not support factory provisioned attestation key.
1933 if (SecLevel() == SecurityLevel::STRONGBOX) {
1934 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1935 error = GenerateKeyWithSelfSignedAttestKey(
1936 AuthorizationSetBuilder()
1937 .EcdsaKey(EcCurve::P_256)
1938 .AttestKey()
1939 .SetDefaultValidity(), /* attest key params */
1940 builder, &key_blob, &key_characteristics);
1941 }
1942 }
1943 ASSERT_EQ(error, ErrorCode::CANNOT_ATTEST_IDS);
David Drysdale37af4b32021-05-14 16:46:59 +01001944 }
1945}
1946
1947/*
David Drysdalec53b7d92021-10-11 12:35:58 +01001948 * NewKeyGenerationTest.EcdsaAttestationIdTags
1949 *
1950 * Verifies that creation of an attested ECDSA key includes various ID tags in the
1951 * attestation extension.
1952 */
1953TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
David Drysdale555ba002022-05-03 18:48:57 +01001954 if (is_gsi_image()) {
1955 // GSI sets up a standard set of device identifiers that may not match
1956 // the device identifiers held by the device.
1957 GTEST_SKIP() << "Test not applicable under GSI";
1958 }
David Drysdalec53b7d92021-10-11 12:35:58 +01001959 auto challenge = "hello";
1960 auto app_id = "foo";
1961 auto subject = "cert subj 2";
1962 vector<uint8_t> subject_der(make_name_from_str(subject));
1963 uint64_t serial_int = 0x1010;
1964 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1965 const AuthorizationSetBuilder base_builder =
1966 AuthorizationSetBuilder()
1967 .Authorization(TAG_NO_AUTH_REQUIRED)
1968 .EcdsaSigningKey(EcCurve::P_256)
1969 .Digest(Digest::NONE)
1970 .AttestationChallenge(challenge)
1971 .AttestationApplicationId(app_id)
1972 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1973 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1974 .SetDefaultValidity();
1975
1976 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
1977 auto extra_tags = AuthorizationSetBuilder();
1978 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
1979 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
1980 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
1981 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
1982 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
1983 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
1984
1985 for (const KeyParameter& tag : extra_tags) {
1986 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1987 vector<uint8_t> key_blob;
1988 vector<KeyCharacteristics> key_characteristics;
1989 AuthorizationSetBuilder builder = base_builder;
1990 builder.push_back(tag);
1991 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001992 // Strongbox may not support factory provisioned attestation key.
1993 if (SecLevel() == SecurityLevel::STRONGBOX) {
1994 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1995 }
Prashant Patil88ad1892022-03-15 16:31:02 +00001996 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
1997 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01001998 continue;
1999 }
2000 ASSERT_EQ(result, ErrorCode::OK);
2001 ASSERT_GT(key_blob.size(), 0U);
2002
2003 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2004 ASSERT_GT(cert_chain_.size(), 0);
2005 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2006
2007 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2008 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2009
2010 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2011 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2012 // attestation extension should contain them, so make sure the extra tag is added.
2013 hw_enforced.push_back(tag);
2014
2015 // Verifying the attestation record will check for the specific tag because
2016 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002017 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2018 hw_enforced, SecLevel(),
2019 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002020
2021 CheckedDeleteKey(&key_blob);
2022 }
2023}
2024
2025/*
David Drysdale565ccc72021-10-11 12:49:50 +01002026 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2027 *
2028 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2029 */
2030TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2031 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002032 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002033 auto challenge = "hello";
2034 auto subject = "cert subj 2";
2035 vector<uint8_t> subject_der(make_name_from_str(subject));
2036 uint64_t serial_int = 0x1010;
2037 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002038 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002039 AuthorizationSetBuilder()
2040 .Authorization(TAG_NO_AUTH_REQUIRED)
2041 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2042 .EcdsaSigningKey(EcCurve::P_256)
2043 .Digest(Digest::NONE)
2044 .AttestationChallenge(challenge)
2045 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2046 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2047 .AttestationApplicationId(app_id)
2048 .Authorization(TAG_CREATION_DATETIME, datetime)
2049 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002050 if (reset) {
2051 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2052 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002053 auto result = GenerateKey(builder);
2054 if (SecLevel() == SecurityLevel::STRONGBOX) {
2055 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2056 result = GenerateKeyWithSelfSignedAttestKey(
2057 AuthorizationSetBuilder()
2058 .EcdsaKey(EcCurve::P_256)
2059 .AttestKey()
2060 .SetDefaultValidity(), /* attest key params */
2061 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2062 }
2063 }
2064 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002065 ASSERT_GT(key_blob_.size(), 0U);
2066
2067 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2068 ASSERT_GT(cert_chain_.size(), 0);
2069 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2070
2071 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2072 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2073
2074 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002075 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2076 hw_enforced, SecLevel(),
2077 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002078 EXPECT_GT(unique_id->size(), 0);
2079 CheckedDeleteKey();
2080 };
2081
2082 // Generate unique ID
2083 auto app_id = "foo";
2084 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2085 vector<uint8_t> unique_id;
2086 get_unique_id(app_id, cert_date, &unique_id);
2087
2088 // Generating a new key with the same parameters should give the same unique ID.
2089 vector<uint8_t> unique_id2;
2090 get_unique_id(app_id, cert_date, &unique_id2);
2091 EXPECT_EQ(unique_id, unique_id2);
2092
2093 // Generating a new key with a slightly different date should give the same unique ID.
2094 uint64_t rounded_date = cert_date / 2592000000LLU;
2095 uint64_t min_date = rounded_date * 2592000000LLU;
2096 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2097
2098 vector<uint8_t> unique_id3;
2099 get_unique_id(app_id, min_date, &unique_id3);
2100 EXPECT_EQ(unique_id, unique_id3);
2101
2102 vector<uint8_t> unique_id4;
2103 get_unique_id(app_id, max_date, &unique_id4);
2104 EXPECT_EQ(unique_id, unique_id4);
2105
2106 // A different attestation application ID should yield a different unique ID.
2107 auto app_id2 = "different_foo";
2108 vector<uint8_t> unique_id5;
2109 get_unique_id(app_id2, cert_date, &unique_id5);
2110 EXPECT_NE(unique_id, unique_id5);
2111
2112 // A radically different date should yield a different unique ID.
2113 vector<uint8_t> unique_id6;
2114 get_unique_id(app_id, 1611621648000, &unique_id6);
2115 EXPECT_NE(unique_id, unique_id6);
2116
2117 vector<uint8_t> unique_id7;
2118 get_unique_id(app_id, max_date + 1, &unique_id7);
2119 EXPECT_NE(unique_id, unique_id7);
2120
2121 vector<uint8_t> unique_id8;
2122 get_unique_id(app_id, min_date - 1, &unique_id8);
2123 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002124
2125 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2126 vector<uint8_t> unique_id9;
2127 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2128 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002129}
2130
2131/*
David Drysdale37af4b32021-05-14 16:46:59 +01002132 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2133 *
2134 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2135 */
2136TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2137 auto challenge = "hello";
2138 auto attest_app_id = "foo";
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));
2143
2144 // Earlier versions of the attestation extension schema included a slot:
2145 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2146 // This should never have been included, and should never be filled in.
2147 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2148 // to confirm that this field never makes it into the attestation extension.
2149 vector<uint8_t> key_blob;
2150 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002151 auto builder = AuthorizationSetBuilder()
2152 .Authorization(TAG_NO_AUTH_REQUIRED)
2153 .EcdsaSigningKey(EcCurve::P_256)
2154 .Digest(Digest::NONE)
2155 .AttestationChallenge(challenge)
2156 .AttestationApplicationId(attest_app_id)
2157 .Authorization(TAG_APPLICATION_ID, "client_id")
2158 .Authorization(TAG_APPLICATION_DATA, "appdata")
2159 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2160 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2161 .SetDefaultValidity();
2162
2163 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002164 // Strongbox may not support factory provisioned attestation key.
2165 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002166 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2167 result = GenerateKeyWithSelfSignedAttestKey(
2168 AuthorizationSetBuilder()
2169 .EcdsaKey(EcCurve::P_256)
2170 .AttestKey()
2171 .SetDefaultValidity(), /* attest key params */
2172 builder, &key_blob, &key_characteristics);
2173 }
subrahmanyaman05642492022-02-05 07:10:56 +00002174 }
David Drysdale37af4b32021-05-14 16:46:59 +01002175 ASSERT_EQ(result, ErrorCode::OK);
2176 ASSERT_GT(key_blob.size(), 0U);
2177
2178 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2179 ASSERT_GT(cert_chain_.size(), 0);
2180 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2181
2182 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2183 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002184 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2185 hw_enforced, SecLevel(),
2186 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002187
2188 // Check that the app id is not in the cert.
2189 string app_id = "clientid";
2190 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2191 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2192 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2193 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2194 cert_chain_[0].encodedCertificate.end());
2195
2196 CheckedDeleteKey(&key_blob);
2197}
2198
2199/*
Selene Huang4f64c222021-04-13 19:54:36 -07002200 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2201 *
2202 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2203 * the key will generate a self signed attestation.
2204 */
2205TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002206 auto subject = "cert subj 2";
2207 vector<uint8_t> subject_der(make_name_from_str(subject));
2208
2209 uint64_t serial_int = 0x123456FFF1234;
2210 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2211
David Drysdaledf09e542021-06-08 15:46:11 +01002212 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002213 vector<uint8_t> key_blob;
2214 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002215 ASSERT_EQ(ErrorCode::OK,
2216 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002217 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002218 .Digest(Digest::NONE)
2219 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2220 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2221 .SetDefaultValidity(),
2222 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002223 ASSERT_GT(key_blob.size(), 0U);
2224 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002225 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002226
2227 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2228
2229 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002230 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002231
2232 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2233 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002234 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002235
2236 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2237 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2238
2239 CheckedDeleteKey(&key_blob);
2240 }
2241}
2242
2243/*
2244 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2245 *
2246 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2247 * app id must also be provided or else it will fail.
2248 */
2249TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2250 auto challenge = "hello";
2251 vector<uint8_t> key_blob;
2252 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002253 auto builder = AuthorizationSetBuilder()
2254 .EcdsaSigningKey(EcCurve::P_256)
2255 .Digest(Digest::NONE)
2256 .AttestationChallenge(challenge)
2257 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002258
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002259 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002260 // Strongbox may not support factory provisioned attestation key.
2261 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002262 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2263 result = GenerateKeyWithSelfSignedAttestKey(
2264 AuthorizationSetBuilder()
2265 .EcdsaKey(EcCurve::P_256)
2266 .AttestKey()
2267 .SetDefaultValidity(), /* attest key params */
2268 builder, &key_blob, &key_characteristics);
2269 }
subrahmanyaman05642492022-02-05 07:10:56 +00002270 }
2271 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002272}
2273
2274/*
2275 * NewKeyGenerationTest.EcdsaIgnoreAppId
2276 *
2277 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2278 * any appid will be ignored, and keymint will generate a self sign certificate.
2279 */
2280TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2281 auto app_id = "foo";
2282
David Drysdaledf09e542021-06-08 15:46:11 +01002283 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002284 vector<uint8_t> key_blob;
2285 vector<KeyCharacteristics> key_characteristics;
2286 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002287 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002288 .Digest(Digest::NONE)
2289 .AttestationApplicationId(app_id)
2290 .SetDefaultValidity(),
2291 &key_blob, &key_characteristics));
2292
2293 ASSERT_GT(key_blob.size(), 0U);
2294 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002295 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002296
2297 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2298
2299 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002300 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002301
2302 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2303 ASSERT_EQ(cert_chain_.size(), 1);
2304
2305 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2306 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2307
2308 CheckedDeleteKey(&key_blob);
2309 }
2310}
2311
2312/*
2313 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2314 *
2315 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2316 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2317 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2318 * to specify how many following bytes will be used to encode the length.
2319 */
2320TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2321 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002322 std::vector<uint32_t> app_id_lengths{143, 258};
2323
2324 for (uint32_t length : app_id_lengths) {
2325 const string app_id(length, 'a');
2326 vector<uint8_t> key_blob;
2327 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002328 auto builder = AuthorizationSetBuilder()
2329 .Authorization(TAG_NO_AUTH_REQUIRED)
2330 .EcdsaSigningKey(EcCurve::P_256)
2331 .Digest(Digest::NONE)
2332 .AttestationChallenge(challenge)
2333 .AttestationApplicationId(app_id)
2334 .SetDefaultValidity();
2335
2336 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002337 // Strongbox may not support factory provisioned attestation key.
2338 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002339 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2340 result = GenerateKeyWithSelfSignedAttestKey(
2341 AuthorizationSetBuilder()
2342 .EcdsaKey(EcCurve::P_256)
2343 .AttestKey()
2344 .SetDefaultValidity(), /* attest key params */
2345 builder, &key_blob, &key_characteristics);
2346 }
subrahmanyaman05642492022-02-05 07:10:56 +00002347 }
2348 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002349 ASSERT_GT(key_blob.size(), 0U);
2350 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002351 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002352
2353 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2354
2355 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002356 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002357
2358 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2359 ASSERT_GT(cert_chain_.size(), 0);
2360
2361 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2362 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002363 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002364 sw_enforced, hw_enforced, SecLevel(),
2365 cert_chain_[0].encodedCertificate));
2366
2367 CheckedDeleteKey(&key_blob);
2368 }
2369}
2370
2371/*
Qi Wud22ec842020-11-26 13:27:53 +08002372 * NewKeyGenerationTest.LimitedUsageEcdsa
2373 *
2374 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2375 * resulting keys have correct characteristics.
2376 */
2377TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002378 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08002379 vector<uint8_t> key_blob;
2380 vector<KeyCharacteristics> key_characteristics;
2381 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002382 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002383 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002384 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2385 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002386 &key_blob, &key_characteristics));
2387
2388 ASSERT_GT(key_blob.size(), 0U);
2389 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002390 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002391
2392 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2393
2394 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002395 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002396
2397 // Check the usage count limit tag appears in the authorizations.
2398 AuthorizationSet auths;
2399 for (auto& entry : key_characteristics) {
2400 auths.push_back(AuthorizationSet(entry.authorizations));
2401 }
2402 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2403 << "key usage count limit " << 1U << " missing";
2404
2405 CheckedDeleteKey(&key_blob);
2406 }
2407}
2408
2409/*
Selene Huang31ab4042020-04-29 04:22:39 -07002410 * NewKeyGenerationTest.EcdsaDefaultSize
2411 *
David Drysdaledf09e542021-06-08 15:46:11 +01002412 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002413 * UNSUPPORTED_KEY_SIZE.
2414 */
2415TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2416 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2417 GenerateKey(AuthorizationSetBuilder()
2418 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2419 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002420 .Digest(Digest::NONE)
2421 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002422}
2423
2424/*
David Drysdale42fe1892021-10-14 14:43:46 +01002425 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002426 *
David Drysdale42fe1892021-10-14 14:43:46 +01002427 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002428 * UNSUPPORTED_KEY_SIZE.
2429 */
David Drysdale42fe1892021-10-14 14:43:46 +01002430TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002431 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07002432 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002433 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002434 auto result = GenerateKey(AuthorizationSetBuilder()
2435 .EcdsaSigningKey(curve)
2436 .Digest(Digest::NONE)
2437 .SetDefaultValidity(),
2438 &key_blob, &key_characteristics);
2439 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2440 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002441 }
2442
David Drysdaledf09e542021-06-08 15:46:11 +01002443 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2444 GenerateKey(AuthorizationSetBuilder()
2445 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2446 .Authorization(TAG_KEY_SIZE, 190)
2447 .SigningKey()
2448 .Digest(Digest::NONE)
2449 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002450}
2451
2452/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002453 * NewKeyGenerationTest.EcdsaMissingCurve
2454 *
2455 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
2456 */
2457TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2458 if (AidlVersion() < 2) {
2459 /*
2460 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2461 * However, this was not checked at the time so we can only be strict about checking this
2462 * for implementations of KeyMint version 2 and above.
2463 */
2464 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
2465 }
2466 /* If EC_CURVE not provided, generateKey
2467 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2468 */
2469 auto result = GenerateKey(
2470 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2471 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2472 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2473}
2474
2475/*
Selene Huang31ab4042020-04-29 04:22:39 -07002476 * NewKeyGenerationTest.EcdsaMismatchKeySize
2477 *
2478 * Verifies that specifying mismatched key size and curve for EC key generation returns
2479 * INVALID_ARGUMENT.
2480 */
2481TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002482 if (SecLevel() == SecurityLevel::STRONGBOX) {
2483 GTEST_SKIP() << "Test not applicable to StrongBox device";
2484 }
Selene Huang31ab4042020-04-29 04:22:39 -07002485
David Drysdaledf09e542021-06-08 15:46:11 +01002486 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002487 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002488 .Authorization(TAG_KEY_SIZE, 224)
2489 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002490 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002491 .Digest(Digest::NONE)
2492 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002493 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002494}
2495
2496/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002497 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002498 *
2499 * Verifies that keymint does not support any curve designated as unsupported.
2500 */
2501TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2502 Digest digest;
2503 if (SecLevel() == SecurityLevel::STRONGBOX) {
2504 digest = Digest::SHA_2_256;
2505 } else {
2506 digest = Digest::SHA_2_512;
2507 }
2508 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08002509 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2510 .EcdsaSigningKey(curve)
2511 .Digest(digest)
2512 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002513 << "Failed to generate key on curve: " << curve;
2514 CheckedDeleteKey();
2515 }
2516}
2517
2518/*
2519 * NewKeyGenerationTest.Hmac
2520 *
2521 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2522 * characteristics.
2523 */
2524TEST_P(NewKeyGenerationTest, Hmac) {
2525 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2526 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002527 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002528 constexpr size_t key_size = 128;
2529 ASSERT_EQ(ErrorCode::OK,
2530 GenerateKey(
2531 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2532 TAG_MIN_MAC_LENGTH, 128),
2533 &key_blob, &key_characteristics));
2534
2535 ASSERT_GT(key_blob.size(), 0U);
2536 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002537 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002538
Shawn Willden7f424372021-01-10 18:06:50 -07002539 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2540 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2541 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2542 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002543
2544 CheckedDeleteKey(&key_blob);
2545 }
2546}
2547
2548/*
Selene Huang4f64c222021-04-13 19:54:36 -07002549 * NewKeyGenerationTest.HmacNoAttestation
2550 *
2551 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2552 * and app id are provided.
2553 */
2554TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2555 auto challenge = "hello";
2556 auto app_id = "foo";
2557
2558 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2559 vector<uint8_t> key_blob;
2560 vector<KeyCharacteristics> key_characteristics;
2561 constexpr size_t key_size = 128;
2562 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2563 .HmacKey(key_size)
2564 .Digest(digest)
2565 .AttestationChallenge(challenge)
2566 .AttestationApplicationId(app_id)
2567 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2568 &key_blob, &key_characteristics));
2569
2570 ASSERT_GT(key_blob.size(), 0U);
2571 ASSERT_EQ(cert_chain_.size(), 0);
2572 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002573 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002574
2575 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2576 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2577 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2578 << "Key size " << key_size << "missing";
2579
2580 CheckedDeleteKey(&key_blob);
2581 }
2582}
2583
2584/*
Qi Wud22ec842020-11-26 13:27:53 +08002585 * NewKeyGenerationTest.LimitedUsageHmac
2586 *
2587 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2588 * resulting keys have correct characteristics.
2589 */
2590TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2591 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2592 vector<uint8_t> key_blob;
2593 vector<KeyCharacteristics> key_characteristics;
2594 constexpr size_t key_size = 128;
2595 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2596 .HmacKey(key_size)
2597 .Digest(digest)
2598 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2599 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2600 &key_blob, &key_characteristics));
2601
2602 ASSERT_GT(key_blob.size(), 0U);
2603 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002604 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002605
2606 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2607 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2608 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2609 << "Key size " << key_size << "missing";
2610
2611 // Check the usage count limit tag appears in the authorizations.
2612 AuthorizationSet auths;
2613 for (auto& entry : key_characteristics) {
2614 auths.push_back(AuthorizationSet(entry.authorizations));
2615 }
2616 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2617 << "key usage count limit " << 1U << " missing";
2618
2619 CheckedDeleteKey(&key_blob);
2620 }
2621}
2622
2623/*
Selene Huang31ab4042020-04-29 04:22:39 -07002624 * NewKeyGenerationTest.HmacCheckKeySizes
2625 *
2626 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2627 */
2628TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2629 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2630 if (key_size < 64 || key_size % 8 != 0) {
2631 // To keep this test from being very slow, we only test a random fraction of
2632 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2633 // them, we expect to run ~40 of them in each run.
2634 if (key_size % 8 == 0 || random() % 10 == 0) {
2635 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2636 GenerateKey(AuthorizationSetBuilder()
2637 .HmacKey(key_size)
2638 .Digest(Digest::SHA_2_256)
2639 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2640 << "HMAC key size " << key_size << " invalid";
2641 }
2642 } else {
2643 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2644 .HmacKey(key_size)
2645 .Digest(Digest::SHA_2_256)
2646 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2647 << "Failed to generate HMAC key of size " << key_size;
2648 CheckedDeleteKey();
2649 }
2650 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002651 if (SecLevel() == SecurityLevel::STRONGBOX) {
2652 // STRONGBOX devices must not support keys larger than 512 bits.
2653 size_t key_size = 520;
2654 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2655 GenerateKey(AuthorizationSetBuilder()
2656 .HmacKey(key_size)
2657 .Digest(Digest::SHA_2_256)
2658 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2659 << "HMAC key size " << key_size << " unexpectedly valid";
2660 }
Selene Huang31ab4042020-04-29 04:22:39 -07002661}
2662
2663/*
2664 * NewKeyGenerationTest.HmacCheckMinMacLengths
2665 *
2666 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2667 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2668 * specific MAC length that failed, so reproducing a failed run will be easy.
2669 */
2670TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2671 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2672 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2673 // To keep this test from being very long, we only test a random fraction of
2674 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2675 // we expect to run ~17 of them in each run.
2676 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2677 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2678 GenerateKey(AuthorizationSetBuilder()
2679 .HmacKey(128)
2680 .Digest(Digest::SHA_2_256)
2681 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2682 << "HMAC min mac length " << min_mac_length << " invalid.";
2683 }
2684 } else {
2685 EXPECT_EQ(ErrorCode::OK,
2686 GenerateKey(AuthorizationSetBuilder()
2687 .HmacKey(128)
2688 .Digest(Digest::SHA_2_256)
2689 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2690 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2691 CheckedDeleteKey();
2692 }
2693 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002694
2695 // Minimum MAC length must be no more than 512 bits.
2696 size_t min_mac_length = 520;
2697 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2698 GenerateKey(AuthorizationSetBuilder()
2699 .HmacKey(128)
2700 .Digest(Digest::SHA_2_256)
2701 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2702 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002703}
2704
2705/*
2706 * NewKeyGenerationTest.HmacMultipleDigests
2707 *
2708 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2709 */
2710TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002711 if (SecLevel() == SecurityLevel::STRONGBOX) {
2712 GTEST_SKIP() << "Test not applicable to StrongBox device";
2713 }
Selene Huang31ab4042020-04-29 04:22:39 -07002714
2715 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2716 GenerateKey(AuthorizationSetBuilder()
2717 .HmacKey(128)
2718 .Digest(Digest::SHA1)
2719 .Digest(Digest::SHA_2_256)
2720 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2721}
2722
2723/*
2724 * NewKeyGenerationTest.HmacDigestNone
2725 *
2726 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2727 */
2728TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2729 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2730 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2731 128)));
2732
2733 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2734 GenerateKey(AuthorizationSetBuilder()
2735 .HmacKey(128)
2736 .Digest(Digest::NONE)
2737 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2738}
2739
Selene Huang4f64c222021-04-13 19:54:36 -07002740/*
2741 * NewKeyGenerationTest.AesNoAttestation
2742 *
2743 * Verifies that attestation parameters to AES keys are ignored and generateKey
2744 * will succeed.
2745 */
2746TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2747 auto challenge = "hello";
2748 auto app_id = "foo";
2749
2750 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2751 .Authorization(TAG_NO_AUTH_REQUIRED)
2752 .AesEncryptionKey(128)
2753 .EcbMode()
2754 .Padding(PaddingMode::PKCS7)
2755 .AttestationChallenge(challenge)
2756 .AttestationApplicationId(app_id)));
2757
2758 ASSERT_EQ(cert_chain_.size(), 0);
2759}
2760
2761/*
2762 * NewKeyGenerationTest.TripleDesNoAttestation
2763 *
2764 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2765 * will be successful. No attestation should be generated.
2766 */
2767TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2768 auto challenge = "hello";
2769 auto app_id = "foo";
2770
2771 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2772 .TripleDesEncryptionKey(168)
2773 .BlockMode(BlockMode::ECB)
2774 .Authorization(TAG_NO_AUTH_REQUIRED)
2775 .Padding(PaddingMode::NONE)
2776 .AttestationChallenge(challenge)
2777 .AttestationApplicationId(app_id)));
2778 ASSERT_EQ(cert_chain_.size(), 0);
2779}
2780
Selene Huang31ab4042020-04-29 04:22:39 -07002781INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2782
2783typedef KeyMintAidlTestBase SigningOperationsTest;
2784
2785/*
2786 * SigningOperationsTest.RsaSuccess
2787 *
2788 * Verifies that raw RSA signature operations succeed.
2789 */
2790TEST_P(SigningOperationsTest, RsaSuccess) {
2791 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2792 .RsaSigningKey(2048, 65537)
2793 .Digest(Digest::NONE)
2794 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002795 .Authorization(TAG_NO_AUTH_REQUIRED)
2796 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002797 string message = "12345678901234567890123456789012";
2798 string signature = SignMessage(
2799 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002800 LocalVerifyMessage(message, signature,
2801 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2802}
2803
2804/*
2805 * SigningOperationsTest.RsaAllPaddingsAndDigests
2806 *
2807 * Verifies RSA signature/verification for all padding modes and digests.
2808 */
2809TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2810 auto authorizations = AuthorizationSetBuilder()
2811 .Authorization(TAG_NO_AUTH_REQUIRED)
2812 .RsaSigningKey(2048, 65537)
2813 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2814 .Padding(PaddingMode::NONE)
2815 .Padding(PaddingMode::RSA_PSS)
2816 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2817 .SetDefaultValidity();
2818
2819 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2820
2821 string message(128, 'a');
2822 string corrupt_message(message);
2823 ++corrupt_message[corrupt_message.size() / 2];
2824
2825 for (auto padding :
2826 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2827 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2828 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2829 // Digesting only makes sense with padding.
2830 continue;
2831 }
2832
2833 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2834 // PSS requires digesting.
2835 continue;
2836 }
2837
2838 string signature =
2839 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2840 LocalVerifyMessage(message, signature,
2841 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2842 }
2843 }
Selene Huang31ab4042020-04-29 04:22:39 -07002844}
2845
2846/*
2847 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2848 *
Shawn Willden7f424372021-01-10 18:06:50 -07002849 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002850 */
2851TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2852 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2853 .Authorization(TAG_NO_AUTH_REQUIRED)
2854 .RsaSigningKey(2048, 65537)
2855 .Digest(Digest::NONE)
2856 .Padding(PaddingMode::NONE)
2857 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002858 .Authorization(TAG_APPLICATION_DATA, "appdata")
2859 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002860
2861 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2862
Selene Huang31ab4042020-04-29 04:22:39 -07002863 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2864 Begin(KeyPurpose::SIGN,
2865 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2866 AbortIfNeeded();
2867 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2868 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2869 .Digest(Digest::NONE)
2870 .Padding(PaddingMode::NONE)
2871 .Authorization(TAG_APPLICATION_ID, "clientid")));
2872 AbortIfNeeded();
2873 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2874 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2875 .Digest(Digest::NONE)
2876 .Padding(PaddingMode::NONE)
2877 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2878 AbortIfNeeded();
2879 EXPECT_EQ(ErrorCode::OK,
2880 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2881 .Digest(Digest::NONE)
2882 .Padding(PaddingMode::NONE)
2883 .Authorization(TAG_APPLICATION_DATA, "appdata")
2884 .Authorization(TAG_APPLICATION_ID, "clientid")));
2885 AbortIfNeeded();
2886}
2887
2888/*
2889 * SigningOperationsTest.RsaPssSha256Success
2890 *
2891 * Verifies that RSA-PSS signature operations succeed.
2892 */
2893TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2894 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2895 .RsaSigningKey(2048, 65537)
2896 .Digest(Digest::SHA_2_256)
2897 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002898 .Authorization(TAG_NO_AUTH_REQUIRED)
2899 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002900 // Use large message, which won't work without digesting.
2901 string message(1024, 'a');
2902 string signature = SignMessage(
2903 message,
2904 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2905}
2906
2907/*
2908 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2909 *
2910 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2911 * supports only unpadded operations.
2912 */
2913TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2914 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2915 .RsaSigningKey(2048, 65537)
2916 .Digest(Digest::NONE)
2917 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002918 .Padding(PaddingMode::NONE)
2919 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002920 string message = "12345678901234567890123456789012";
2921 string signature;
2922
2923 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2924 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2925 .Digest(Digest::NONE)
2926 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2927}
2928
2929/*
2930 * SigningOperationsTest.NoUserConfirmation
2931 *
2932 * Verifies that keymint rejects signing operations for keys with
2933 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2934 * presented.
2935 */
2936TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002937 if (SecLevel() == SecurityLevel::STRONGBOX) {
2938 GTEST_SKIP() << "Test not applicable to StrongBox device";
2939 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002940 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2941 .RsaSigningKey(1024, 65537)
2942 .Digest(Digest::NONE)
2943 .Padding(PaddingMode::NONE)
2944 .Authorization(TAG_NO_AUTH_REQUIRED)
2945 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2946 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002947
2948 const string message = "12345678901234567890123456789012";
2949 EXPECT_EQ(ErrorCode::OK,
2950 Begin(KeyPurpose::SIGN,
2951 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2952 string signature;
2953 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2954}
2955
2956/*
2957 * SigningOperationsTest.RsaPkcs1Sha256Success
2958 *
2959 * Verifies that digested RSA-PKCS1 signature operations succeed.
2960 */
2961TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2962 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2963 .RsaSigningKey(2048, 65537)
2964 .Digest(Digest::SHA_2_256)
2965 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002966 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2967 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002968 string message(1024, 'a');
2969 string signature = SignMessage(message, AuthorizationSetBuilder()
2970 .Digest(Digest::SHA_2_256)
2971 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2972}
2973
2974/*
2975 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2976 *
2977 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2978 */
2979TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2980 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2981 .RsaSigningKey(2048, 65537)
2982 .Digest(Digest::NONE)
2983 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002984 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2985 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002986 string message(53, 'a');
2987 string signature = SignMessage(message, AuthorizationSetBuilder()
2988 .Digest(Digest::NONE)
2989 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2990}
2991
2992/*
2993 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2994 *
2995 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2996 * given a too-long message.
2997 */
2998TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2999 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3000 .RsaSigningKey(2048, 65537)
3001 .Digest(Digest::NONE)
3002 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003003 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3004 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003005 string message(257, 'a');
3006
3007 EXPECT_EQ(ErrorCode::OK,
3008 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3009 .Digest(Digest::NONE)
3010 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3011 string signature;
3012 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3013}
3014
3015/*
3016 * SigningOperationsTest.RsaPssSha512TooSmallKey
3017 *
3018 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3019 * used with a key that is too small for the message.
3020 *
3021 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3022 * keymint specification requires that salt_size == digest_size, so the message will be
3023 * digest_size * 2 +
3024 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3025 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3026 * for a 1024-bit key.
3027 */
3028TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003029 if (SecLevel() == SecurityLevel::STRONGBOX) {
3030 GTEST_SKIP() << "Test not applicable to StrongBox device";
3031 }
Selene Huang31ab4042020-04-29 04:22:39 -07003032 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3033 .RsaSigningKey(1024, 65537)
3034 .Digest(Digest::SHA_2_512)
3035 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003036 .Padding(PaddingMode::RSA_PSS)
3037 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003038 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3039 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3040 .Digest(Digest::SHA_2_512)
3041 .Padding(PaddingMode::RSA_PSS)));
3042}
3043
3044/*
3045 * SigningOperationsTest.RsaNoPaddingTooLong
3046 *
3047 * Verifies that raw RSA signature operations fail with the correct error code when
3048 * given a too-long message.
3049 */
3050TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3051 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3052 .RsaSigningKey(2048, 65537)
3053 .Digest(Digest::NONE)
3054 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003055 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3056 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003057 // One byte too long
3058 string message(2048 / 8 + 1, 'a');
3059 ASSERT_EQ(ErrorCode::OK,
3060 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3061 .Digest(Digest::NONE)
3062 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3063 string result;
3064 ErrorCode finish_error_code = Finish(message, &result);
3065 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3066 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3067
3068 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3069 message = string(128 * 1024, 'a');
3070 ASSERT_EQ(ErrorCode::OK,
3071 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3072 .Digest(Digest::NONE)
3073 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3074 finish_error_code = Finish(message, &result);
3075 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3076 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3077}
3078
3079/*
3080 * SigningOperationsTest.RsaAbort
3081 *
3082 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3083 * test, but the behavior should be algorithm and purpose-independent.
3084 */
3085TEST_P(SigningOperationsTest, RsaAbort) {
3086 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3087 .RsaSigningKey(2048, 65537)
3088 .Digest(Digest::NONE)
3089 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003090 .Padding(PaddingMode::NONE)
3091 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003092
3093 ASSERT_EQ(ErrorCode::OK,
3094 Begin(KeyPurpose::SIGN,
3095 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3096 EXPECT_EQ(ErrorCode::OK, Abort());
3097
3098 // Another abort should fail
3099 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3100
3101 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003102 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003103}
3104
3105/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003106 * SigningOperationsTest.RsaNonUniqueParams
3107 *
3108 * Verifies that an operation with multiple padding modes is rejected.
3109 */
3110TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3111 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3112 .RsaSigningKey(2048, 65537)
3113 .Digest(Digest::NONE)
3114 .Digest(Digest::SHA1)
3115 .Authorization(TAG_NO_AUTH_REQUIRED)
3116 .Padding(PaddingMode::NONE)
3117 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3118 .SetDefaultValidity()));
3119
3120 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3121 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3122 .Digest(Digest::NONE)
3123 .Padding(PaddingMode::NONE)
3124 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3125
Tommy Chiuc93c4392021-05-11 18:36:50 +08003126 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3127 .Digest(Digest::NONE)
3128 .Digest(Digest::SHA1)
3129 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3130 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003131
3132 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3133 Begin(KeyPurpose::SIGN,
3134 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3135}
3136
3137/*
Selene Huang31ab4042020-04-29 04:22:39 -07003138 * SigningOperationsTest.RsaUnsupportedPadding
3139 *
3140 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3141 * with a padding mode inappropriate for RSA.
3142 */
3143TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3144 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3145 .RsaSigningKey(2048, 65537)
3146 .Authorization(TAG_NO_AUTH_REQUIRED)
3147 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003148 .Padding(PaddingMode::PKCS7)
3149 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003150 ASSERT_EQ(
3151 ErrorCode::UNSUPPORTED_PADDING_MODE,
3152 Begin(KeyPurpose::SIGN,
3153 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003154 CheckedDeleteKey();
3155
3156 ASSERT_EQ(ErrorCode::OK,
3157 GenerateKey(
3158 AuthorizationSetBuilder()
3159 .RsaSigningKey(2048, 65537)
3160 .Authorization(TAG_NO_AUTH_REQUIRED)
3161 .Digest(Digest::SHA_2_256 /* supported digest */)
3162 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3163 .SetDefaultValidity()));
3164 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3165 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3166 .Digest(Digest::SHA_2_256)
3167 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003168}
3169
3170/*
3171 * SigningOperationsTest.RsaPssNoDigest
3172 *
3173 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3174 */
3175TEST_P(SigningOperationsTest, RsaNoDigest) {
3176 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3177 .RsaSigningKey(2048, 65537)
3178 .Authorization(TAG_NO_AUTH_REQUIRED)
3179 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003180 .Padding(PaddingMode::RSA_PSS)
3181 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003182 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3183 Begin(KeyPurpose::SIGN,
3184 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3185
3186 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3187 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3188}
3189
3190/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003191 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003192 *
3193 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3194 * supported in some cases (as validated in other tests), but a mode must be specified.
3195 */
3196TEST_P(SigningOperationsTest, RsaNoPadding) {
3197 // Padding must be specified
3198 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3199 .RsaKey(2048, 65537)
3200 .Authorization(TAG_NO_AUTH_REQUIRED)
3201 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003202 .Digest(Digest::NONE)
3203 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003204 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3205 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3206}
3207
3208/*
3209 * SigningOperationsTest.RsaShortMessage
3210 *
3211 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3212 */
3213TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3215 .Authorization(TAG_NO_AUTH_REQUIRED)
3216 .RsaSigningKey(2048, 65537)
3217 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003218 .Padding(PaddingMode::NONE)
3219 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003220
3221 // Barely shorter
3222 string message(2048 / 8 - 1, 'a');
3223 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3224
3225 // Much shorter
3226 message = "a";
3227 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3228}
3229
3230/*
3231 * SigningOperationsTest.RsaSignWithEncryptionKey
3232 *
3233 * Verifies that RSA encryption keys cannot be used to sign.
3234 */
3235TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3236 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3237 .Authorization(TAG_NO_AUTH_REQUIRED)
3238 .RsaEncryptionKey(2048, 65537)
3239 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003240 .Padding(PaddingMode::NONE)
3241 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003242 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3243 Begin(KeyPurpose::SIGN,
3244 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3245}
3246
3247/*
3248 * SigningOperationsTest.RsaSignTooLargeMessage
3249 *
3250 * Verifies that attempting a raw signature of a message which is the same length as the key,
3251 * but numerically larger than the public modulus, fails with the correct error.
3252 */
3253TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3254 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3255 .Authorization(TAG_NO_AUTH_REQUIRED)
3256 .RsaSigningKey(2048, 65537)
3257 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003258 .Padding(PaddingMode::NONE)
3259 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003260
3261 // Largest possible message will always be larger than the public modulus.
3262 string message(2048 / 8, static_cast<char>(0xff));
3263 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3264 .Authorization(TAG_NO_AUTH_REQUIRED)
3265 .Digest(Digest::NONE)
3266 .Padding(PaddingMode::NONE)));
3267 string signature;
3268 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3269}
3270
3271/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003272 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3273 *
David Drysdale42fe1892021-10-14 14:43:46 +01003274 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003275 */
3276TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003277
3278 string message = "1234567890";
3279 string corrupt_message = "2234567890";
3280 for (auto curve : ValidCurves()) {
3281 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003282 // Ed25519 only allows Digest::NONE.
3283 auto digests = (curve == EcCurve::CURVE_25519)
3284 ? std::vector<Digest>(1, Digest::NONE)
3285 : ValidDigests(true /* withNone */, false /* withMD5 */);
3286
David Drysdaledf8f52e2021-05-06 08:10:58 +01003287 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3288 .Authorization(TAG_NO_AUTH_REQUIRED)
3289 .EcdsaSigningKey(curve)
3290 .Digest(digests)
3291 .SetDefaultValidity());
3292 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3293 if (error != ErrorCode::OK) {
3294 continue;
3295 }
3296
3297 for (auto digest : digests) {
3298 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3299 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3300 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3301 }
3302
3303 auto rc = DeleteKey();
3304 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3305 }
3306}
3307
3308/*
Selene Huang31ab4042020-04-29 04:22:39 -07003309 * SigningOperationsTest.EcdsaAllCurves
3310 *
David Drysdale42fe1892021-10-14 14:43:46 +01003311 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003312 */
3313TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3314 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003315 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3316 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003317 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3318 .Authorization(TAG_NO_AUTH_REQUIRED)
3319 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003320 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003321 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003322 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3323 if (error != ErrorCode::OK) continue;
3324
3325 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003326 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003327 CheckedDeleteKey();
3328 }
3329}
3330
3331/*
David Drysdale42fe1892021-10-14 14:43:46 +01003332 * SigningOperationsTest.EcdsaCurve25519
3333 *
3334 * Verifies that ECDSA operations succeed with curve25519.
3335 */
3336TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3337 if (!Curve25519Supported()) {
3338 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3339 }
3340
3341 EcCurve curve = EcCurve::CURVE_25519;
3342 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3343 .Authorization(TAG_NO_AUTH_REQUIRED)
3344 .EcdsaSigningKey(curve)
3345 .Digest(Digest::NONE)
3346 .SetDefaultValidity());
3347 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3348
3349 string message(1024, 'a');
3350 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3351 CheckedDeleteKey();
3352}
3353
3354/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003355 * SigningOperationsTest.EcdsaCurve25519MaxSize
3356 *
3357 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3358 */
3359TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3360 if (!Curve25519Supported()) {
3361 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3362 }
3363
3364 EcCurve curve = EcCurve::CURVE_25519;
3365 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3366 .Authorization(TAG_NO_AUTH_REQUIRED)
3367 .EcdsaSigningKey(curve)
3368 .Digest(Digest::NONE)
3369 .SetDefaultValidity());
3370 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3371
3372 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3373
3374 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3375 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3376 string message(msg_size, 'a');
3377
3378 // Attempt to sign via Begin+Finish.
3379 AuthorizationSet out_params;
3380 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3381 EXPECT_TRUE(out_params.empty());
3382 string signature;
3383 auto result = Finish(message, &signature);
3384 EXPECT_EQ(result, ErrorCode::OK);
3385 LocalVerifyMessage(message, signature, params);
3386
3387 // Attempt to sign via Begin+Update+Finish
3388 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3389 EXPECT_TRUE(out_params.empty());
3390 string output;
3391 result = Update(message, &output);
3392 EXPECT_EQ(result, ErrorCode::OK);
3393 EXPECT_EQ(output.size(), 0);
3394 string signature2;
3395 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3396 LocalVerifyMessage(message, signature2, params);
3397 }
3398
3399 CheckedDeleteKey();
3400}
3401
3402/*
3403 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3404 *
3405 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3406 */
3407TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3408 if (!Curve25519Supported()) {
3409 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3410 }
3411
3412 EcCurve curve = EcCurve::CURVE_25519;
3413 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3414 .Authorization(TAG_NO_AUTH_REQUIRED)
3415 .EcdsaSigningKey(curve)
3416 .Digest(Digest::NONE)
3417 .SetDefaultValidity());
3418 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3419
3420 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3421
3422 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3423 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3424 string message(msg_size, 'a');
3425
3426 // Attempt to sign via Begin+Finish.
3427 AuthorizationSet out_params;
3428 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3429 EXPECT_TRUE(out_params.empty());
3430 string signature;
3431 auto result = Finish(message, &signature);
3432 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3433
3434 // Attempt to sign via Begin+Update (but never get to Finish)
3435 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3436 EXPECT_TRUE(out_params.empty());
3437 string output;
3438 result = Update(message, &output);
3439 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3440 }
3441
3442 CheckedDeleteKey();
3443}
3444
3445/*
Selene Huang31ab4042020-04-29 04:22:39 -07003446 * SigningOperationsTest.EcdsaNoDigestHugeData
3447 *
3448 * Verifies that ECDSA operations support very large messages, even without digesting. This
3449 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3450 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3451 * the framework.
3452 */
3453TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3454 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3455 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003456 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003457 .Digest(Digest::NONE)
3458 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003459 string message(1 * 1024, 'a');
3460 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3461}
3462
3463/*
3464 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3465 *
3466 * Verifies that using an EC key requires the correct app ID/data.
3467 */
3468TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3469 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3470 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003471 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003472 .Digest(Digest::NONE)
3473 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003474 .Authorization(TAG_APPLICATION_DATA, "appdata")
3475 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003476
3477 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3478
Selene Huang31ab4042020-04-29 04:22:39 -07003479 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3480 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3481 AbortIfNeeded();
3482 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3483 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3484 .Digest(Digest::NONE)
3485 .Authorization(TAG_APPLICATION_ID, "clientid")));
3486 AbortIfNeeded();
3487 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3488 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3489 .Digest(Digest::NONE)
3490 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3491 AbortIfNeeded();
3492 EXPECT_EQ(ErrorCode::OK,
3493 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3494 .Digest(Digest::NONE)
3495 .Authorization(TAG_APPLICATION_DATA, "appdata")
3496 .Authorization(TAG_APPLICATION_ID, "clientid")));
3497 AbortIfNeeded();
3498}
3499
3500/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003501 * SigningOperationsTest.EcdsaIncompatibleDigest
3502 *
3503 * Verifies that using an EC key requires compatible digest.
3504 */
3505TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3506 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3507 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003508 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003509 .Digest(Digest::NONE)
3510 .Digest(Digest::SHA1)
3511 .SetDefaultValidity()));
3512 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3513 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3514 AbortIfNeeded();
3515}
3516
3517/*
Selene Huang31ab4042020-04-29 04:22:39 -07003518 * SigningOperationsTest.AesEcbSign
3519 *
3520 * Verifies that attempts to use AES keys to sign fail in the correct way.
3521 */
3522TEST_P(SigningOperationsTest, AesEcbSign) {
3523 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3524 .Authorization(TAG_NO_AUTH_REQUIRED)
3525 .SigningKey()
3526 .AesEncryptionKey(128)
3527 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3528
3529 AuthorizationSet out_params;
3530 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3531 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3532 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3533 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3534}
3535
3536/*
3537 * SigningOperationsTest.HmacAllDigests
3538 *
3539 * Verifies that HMAC works with all digests.
3540 */
3541TEST_P(SigningOperationsTest, HmacAllDigests) {
3542 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
3543 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3544 .Authorization(TAG_NO_AUTH_REQUIRED)
3545 .HmacKey(128)
3546 .Digest(digest)
3547 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3548 << "Failed to create HMAC key with digest " << digest;
3549 string message = "12345678901234567890123456789012";
3550 string signature = MacMessage(message, digest, 160);
3551 EXPECT_EQ(160U / 8U, signature.size())
3552 << "Failed to sign with HMAC key with digest " << digest;
3553 CheckedDeleteKey();
3554 }
3555}
3556
3557/*
3558 * SigningOperationsTest.HmacSha256TooLargeMacLength
3559 *
3560 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3561 * digest size.
3562 */
3563TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3564 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3565 .Authorization(TAG_NO_AUTH_REQUIRED)
3566 .HmacKey(128)
3567 .Digest(Digest::SHA_2_256)
3568 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3569 AuthorizationSet output_params;
3570 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3571 AuthorizationSetBuilder()
3572 .Digest(Digest::SHA_2_256)
3573 .Authorization(TAG_MAC_LENGTH, 264),
3574 &output_params));
3575}
3576
3577/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003578 * SigningOperationsTest.HmacSha256InvalidMacLength
3579 *
3580 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3581 * not a multiple of 8.
3582 */
3583TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3584 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3585 .Authorization(TAG_NO_AUTH_REQUIRED)
3586 .HmacKey(128)
3587 .Digest(Digest::SHA_2_256)
3588 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3589 AuthorizationSet output_params;
3590 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3591 AuthorizationSetBuilder()
3592 .Digest(Digest::SHA_2_256)
3593 .Authorization(TAG_MAC_LENGTH, 161),
3594 &output_params));
3595}
3596
3597/*
Selene Huang31ab4042020-04-29 04:22:39 -07003598 * SigningOperationsTest.HmacSha256TooSmallMacLength
3599 *
3600 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3601 * specified minimum MAC length.
3602 */
3603TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3604 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3605 .Authorization(TAG_NO_AUTH_REQUIRED)
3606 .HmacKey(128)
3607 .Digest(Digest::SHA_2_256)
3608 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3609 AuthorizationSet output_params;
3610 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3611 AuthorizationSetBuilder()
3612 .Digest(Digest::SHA_2_256)
3613 .Authorization(TAG_MAC_LENGTH, 120),
3614 &output_params));
3615}
3616
3617/*
3618 * SigningOperationsTest.HmacRfc4231TestCase3
3619 *
3620 * Validates against the test vectors from RFC 4231 test case 3.
3621 */
3622TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3623 string key(20, 0xaa);
3624 string message(50, 0xdd);
3625 uint8_t sha_224_expected[] = {
3626 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3627 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3628 };
3629 uint8_t sha_256_expected[] = {
3630 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3631 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3632 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3633 };
3634 uint8_t sha_384_expected[] = {
3635 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3636 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3637 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3638 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3639 };
3640 uint8_t sha_512_expected[] = {
3641 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3642 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3643 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3644 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3645 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3646 };
3647
3648 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3649 if (SecLevel() != SecurityLevel::STRONGBOX) {
3650 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3651 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3652 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3653 }
3654}
3655
3656/*
3657 * SigningOperationsTest.HmacRfc4231TestCase5
3658 *
3659 * Validates against the test vectors from RFC 4231 test case 5.
3660 */
3661TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3662 string key(20, 0x0c);
3663 string message = "Test With Truncation";
3664
3665 uint8_t sha_224_expected[] = {
3666 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3667 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3668 };
3669 uint8_t sha_256_expected[] = {
3670 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3671 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3672 };
3673 uint8_t sha_384_expected[] = {
3674 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3675 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3676 };
3677 uint8_t sha_512_expected[] = {
3678 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3679 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3680 };
3681
3682 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3683 if (SecLevel() != SecurityLevel::STRONGBOX) {
3684 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3685 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3686 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3687 }
3688}
3689
3690INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3691
3692typedef KeyMintAidlTestBase VerificationOperationsTest;
3693
3694/*
Selene Huang31ab4042020-04-29 04:22:39 -07003695 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3696 *
3697 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3698 */
3699TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3700 string key_material = "HelloThisIsAKey";
3701
3702 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003703 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003704 EXPECT_EQ(ErrorCode::OK,
3705 ImportKey(AuthorizationSetBuilder()
3706 .Authorization(TAG_NO_AUTH_REQUIRED)
3707 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3708 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3709 .Digest(Digest::SHA_2_256)
3710 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3711 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3712 EXPECT_EQ(ErrorCode::OK,
3713 ImportKey(AuthorizationSetBuilder()
3714 .Authorization(TAG_NO_AUTH_REQUIRED)
3715 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3716 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3717 .Digest(Digest::SHA_2_256)
3718 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3719 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3720
3721 string message = "This is a message.";
3722 string signature = SignMessage(
3723 signing_key, message,
3724 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3725
3726 // Signing key should not work.
3727 AuthorizationSet out_params;
3728 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3729 Begin(KeyPurpose::VERIFY, signing_key,
3730 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3731
3732 // Verification key should work.
3733 VerifyMessage(verification_key, message, signature,
3734 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3735
3736 CheckedDeleteKey(&signing_key);
3737 CheckedDeleteKey(&verification_key);
3738}
3739
Prashant Patildec9fdc2021-12-08 15:25:47 +00003740/*
3741 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3742 *
3743 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3744 */
3745TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3746 string key_material = "HelloThisIsAKey";
3747
3748 vector<uint8_t> signing_key, verification_key;
3749 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3750 EXPECT_EQ(ErrorCode::OK,
3751 ImportKey(AuthorizationSetBuilder()
3752 .Authorization(TAG_NO_AUTH_REQUIRED)
3753 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3754 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3755 .Digest(Digest::SHA_2_256)
3756 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3757 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3758 EXPECT_EQ(ErrorCode::OK,
3759 ImportKey(AuthorizationSetBuilder()
3760 .Authorization(TAG_NO_AUTH_REQUIRED)
3761 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3762 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3763 .Digest(Digest::SHA_2_256)
3764 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3765 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3766
3767 string message = "This is a message.";
3768 string signature = SignMessage(
3769 signing_key, message,
3770 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3771
3772 AuthorizationSet begin_out_params;
3773 ASSERT_EQ(ErrorCode::OK,
3774 Begin(KeyPurpose::VERIFY, verification_key,
3775 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3776
3777 string corruptMessage = "This is b message."; // Corrupted message
3778 string output;
3779 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3780
3781 ASSERT_EQ(ErrorCode::OK,
3782 Begin(KeyPurpose::VERIFY, verification_key,
3783 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3784
3785 signature[0] += 1; // Corrupt a signature
3786 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3787
3788 CheckedDeleteKey(&signing_key);
3789 CheckedDeleteKey(&verification_key);
3790}
3791
Selene Huang31ab4042020-04-29 04:22:39 -07003792INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3793
3794typedef KeyMintAidlTestBase ExportKeyTest;
3795
3796/*
3797 * ExportKeyTest.RsaUnsupportedKeyFormat
3798 *
3799 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3800 */
3801// TODO(seleneh) add ExportKey to GenerateKey
3802// check result
3803
3804class ImportKeyTest : public KeyMintAidlTestBase {
3805 public:
3806 template <TagType tag_type, Tag tag, typename ValueT>
3807 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3808 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003809 for (auto& entry : key_characteristics_) {
3810 if (entry.securityLevel == SecLevel()) {
3811 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3812 << "Tag " << tag << " with value " << expected
3813 << " not found at security level" << entry.securityLevel;
3814 } else {
3815 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3816 << "Tag " << tag << " found at security level " << entry.securityLevel;
3817 }
Selene Huang31ab4042020-04-29 04:22:39 -07003818 }
3819 }
3820
3821 void CheckOrigin() {
3822 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003823 // Origin isn't a crypto param, but it always lives with them.
3824 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003825 }
3826};
3827
3828/*
3829 * ImportKeyTest.RsaSuccess
3830 *
3831 * Verifies that importing and using an RSA key pair works correctly.
3832 */
3833TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003834 uint32_t key_size;
3835 string key;
3836
3837 if (SecLevel() == SecurityLevel::STRONGBOX) {
3838 key_size = 2048;
3839 key = rsa_2048_key;
3840 } else {
3841 key_size = 1024;
3842 key = rsa_key;
3843 }
3844
Selene Huang31ab4042020-04-29 04:22:39 -07003845 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3846 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003847 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003848 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003849 .Padding(PaddingMode::RSA_PSS)
3850 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003851 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003852
3853 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003854 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003855 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3856 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3857 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3858 CheckOrigin();
3859
3860 string message(1024 / 8, 'a');
3861 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3862 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003863 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003864}
3865
3866/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003867 * ImportKeyTest.RsaSuccessWithoutParams
3868 *
3869 * Verifies that importing and using an RSA key pair without specifying parameters
3870 * works correctly.
3871 */
3872TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3873 uint32_t key_size;
3874 string key;
3875
3876 if (SecLevel() == SecurityLevel::STRONGBOX) {
3877 key_size = 2048;
3878 key = rsa_2048_key;
3879 } else {
3880 key_size = 1024;
3881 key = rsa_key;
3882 }
3883
3884 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3885 .Authorization(TAG_NO_AUTH_REQUIRED)
3886 .SigningKey()
3887 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3888 .Digest(Digest::SHA_2_256)
3889 .Padding(PaddingMode::RSA_PSS)
3890 .SetDefaultValidity(),
3891 KeyFormat::PKCS8, key));
3892
3893 // Key size and public exponent are determined from the imported key material.
3894 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3895 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3896
3897 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3898 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3899 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3900 CheckOrigin();
3901
3902 string message(1024 / 8, 'a');
3903 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3904 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003905 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003906}
3907
3908/*
Selene Huang31ab4042020-04-29 04:22:39 -07003909 * ImportKeyTest.RsaKeySizeMismatch
3910 *
3911 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3912 * correct way.
3913 */
3914TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3915 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3916 ImportKey(AuthorizationSetBuilder()
3917 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3918 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003919 .Padding(PaddingMode::NONE)
3920 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003921 KeyFormat::PKCS8, rsa_key));
3922}
3923
3924/*
3925 * ImportKeyTest.RsaPublicExponentMismatch
3926 *
3927 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3928 * fails in the correct way.
3929 */
3930TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3931 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3932 ImportKey(AuthorizationSetBuilder()
3933 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3934 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003935 .Padding(PaddingMode::NONE)
3936 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003937 KeyFormat::PKCS8, rsa_key));
3938}
3939
3940/*
David Drysdalee60248c2021-10-04 12:54:13 +01003941 * ImportKeyTest.RsaAttestMultiPurposeFail
3942 *
3943 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
3944 */
3945TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00003946 if (AidlVersion() < 2) {
3947 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
3948 // with other key purposes. However, this was not checked at the time
3949 // so we can only be strict about checking this for implementations of KeyMint
3950 // version 2 and above.
3951 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
3952 }
David Drysdalee60248c2021-10-04 12:54:13 +01003953 uint32_t key_size = 2048;
3954 string key = rsa_2048_key;
3955
3956 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3957 ImportKey(AuthorizationSetBuilder()
3958 .Authorization(TAG_NO_AUTH_REQUIRED)
3959 .RsaSigningKey(key_size, 65537)
3960 .AttestKey()
3961 .Digest(Digest::SHA_2_256)
3962 .Padding(PaddingMode::RSA_PSS)
3963 .SetDefaultValidity(),
3964 KeyFormat::PKCS8, key));
3965}
3966
3967/*
Selene Huang31ab4042020-04-29 04:22:39 -07003968 * ImportKeyTest.EcdsaSuccess
3969 *
3970 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3971 */
3972TEST_P(ImportKeyTest, EcdsaSuccess) {
3973 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3974 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003975 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003976 .Digest(Digest::SHA_2_256)
3977 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003978 KeyFormat::PKCS8, ec_256_key));
3979
3980 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003981 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3982 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3983
3984 CheckOrigin();
3985
3986 string message(32, 'a');
3987 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3988 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003989 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003990}
3991
3992/*
3993 * ImportKeyTest.EcdsaP256RFC5915Success
3994 *
3995 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3996 * correctly.
3997 */
3998TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3999 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4000 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004001 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004002 .Digest(Digest::SHA_2_256)
4003 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004004 KeyFormat::PKCS8, ec_256_key_rfc5915));
4005
4006 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004007 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4008 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4009
4010 CheckOrigin();
4011
4012 string message(32, 'a');
4013 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4014 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004015 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004016}
4017
4018/*
4019 * ImportKeyTest.EcdsaP256SEC1Success
4020 *
4021 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4022 */
4023TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4024 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4025 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004026 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004027 .Digest(Digest::SHA_2_256)
4028 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004029 KeyFormat::PKCS8, ec_256_key_sec1));
4030
4031 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004032 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4033 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4034
4035 CheckOrigin();
4036
4037 string message(32, 'a');
4038 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4039 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004040 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004041}
4042
4043/*
4044 * ImportKeyTest.Ecdsa521Success
4045 *
4046 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4047 */
4048TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004049 if (SecLevel() == SecurityLevel::STRONGBOX) {
4050 GTEST_SKIP() << "Test not applicable to StrongBox device";
4051 }
Selene Huang31ab4042020-04-29 04:22:39 -07004052 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4053 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004054 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004055 .Digest(Digest::SHA_2_256)
4056 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004057 KeyFormat::PKCS8, ec_521_key));
4058
4059 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004060 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4061 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4062 CheckOrigin();
4063
4064 string message(32, 'a');
4065 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4066 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004067 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004068}
4069
4070/*
Selene Huang31ab4042020-04-29 04:22:39 -07004071 * ImportKeyTest.EcdsaCurveMismatch
4072 *
4073 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4074 * the correct way.
4075 */
4076TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4077 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4078 ImportKey(AuthorizationSetBuilder()
4079 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004080 .Digest(Digest::NONE)
4081 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004082 KeyFormat::PKCS8, ec_256_key));
4083}
4084
4085/*
David Drysdalee60248c2021-10-04 12:54:13 +01004086 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4087 *
4088 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4089 */
4090TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004091 if (AidlVersion() < 2) {
4092 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4093 // with other key purposes. However, this was not checked at the time
4094 // so we can only be strict about checking this for implementations of KeyMint
4095 // version 2 and above.
4096 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4097 }
David Drysdalee60248c2021-10-04 12:54:13 +01004098 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4099 ImportKey(AuthorizationSetBuilder()
4100 .Authorization(TAG_NO_AUTH_REQUIRED)
4101 .EcdsaSigningKey(EcCurve::P_256)
4102 .AttestKey()
4103 .Digest(Digest::SHA_2_256)
4104 .SetDefaultValidity(),
4105 KeyFormat::PKCS8, ec_256_key));
4106}
4107
4108/*
David Drysdale42fe1892021-10-14 14:43:46 +01004109 * ImportKeyTest.Ed25519RawSuccess
4110 *
4111 * Verifies that importing and using a raw Ed25519 private key works correctly.
4112 */
4113TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4114 if (!Curve25519Supported()) {
4115 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4116 }
4117
4118 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4119 .Authorization(TAG_NO_AUTH_REQUIRED)
4120 .EcdsaSigningKey(EcCurve::CURVE_25519)
4121 .Digest(Digest::NONE)
4122 .SetDefaultValidity(),
4123 KeyFormat::RAW, ed25519_key));
4124 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4125 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4126 CheckOrigin();
4127
4128 // The returned cert should hold the correct public key.
4129 ASSERT_GT(cert_chain_.size(), 0);
4130 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4131 ASSERT_NE(kmKeyCert, nullptr);
4132 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4133 ASSERT_NE(kmPubKey.get(), nullptr);
4134 size_t kmPubKeySize = 32;
4135 uint8_t kmPubKeyData[32];
4136 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4137 ASSERT_EQ(kmPubKeySize, 32);
4138 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4139
4140 string message(32, 'a');
4141 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4142 string signature = SignMessage(message, params);
4143 LocalVerifyMessage(message, signature, params);
4144}
4145
4146/*
4147 * ImportKeyTest.Ed25519Pkcs8Success
4148 *
4149 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4150 */
4151TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4152 if (!Curve25519Supported()) {
4153 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4154 }
4155
4156 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4157 .Authorization(TAG_NO_AUTH_REQUIRED)
4158 .EcdsaSigningKey(EcCurve::CURVE_25519)
4159 .Digest(Digest::NONE)
4160 .SetDefaultValidity(),
4161 KeyFormat::PKCS8, ed25519_pkcs8_key));
4162 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4163 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4164 CheckOrigin();
4165
4166 // The returned cert should hold the correct public key.
4167 ASSERT_GT(cert_chain_.size(), 0);
4168 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4169 ASSERT_NE(kmKeyCert, nullptr);
4170 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4171 ASSERT_NE(kmPubKey.get(), nullptr);
4172 size_t kmPubKeySize = 32;
4173 uint8_t kmPubKeyData[32];
4174 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4175 ASSERT_EQ(kmPubKeySize, 32);
4176 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4177
4178 string message(32, 'a');
4179 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4180 string signature = SignMessage(message, params);
4181 LocalVerifyMessage(message, signature, params);
4182}
4183
4184/*
4185 * ImportKeyTest.Ed25519CurveMismatch
4186 *
4187 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4188 * the correct way.
4189 */
4190TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4191 if (!Curve25519Supported()) {
4192 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4193 }
4194
4195 ASSERT_NE(ErrorCode::OK,
4196 ImportKey(AuthorizationSetBuilder()
4197 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4198 .Digest(Digest::NONE)
4199 .SetDefaultValidity(),
4200 KeyFormat::RAW, ed25519_key));
4201}
4202
4203/*
4204 * ImportKeyTest.Ed25519FormatMismatch
4205 *
4206 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4207 */
4208TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4209 if (!Curve25519Supported()) {
4210 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4211 }
4212
4213 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4214 .EcdsaSigningKey(EcCurve::CURVE_25519)
4215 .Digest(Digest::NONE)
4216 .SetDefaultValidity(),
4217 KeyFormat::PKCS8, ed25519_key));
4218 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4219 .EcdsaSigningKey(EcCurve::CURVE_25519)
4220 .Digest(Digest::NONE)
4221 .SetDefaultValidity(),
4222 KeyFormat::RAW, ed25519_pkcs8_key));
4223}
4224
4225/*
4226 * ImportKeyTest.Ed25519PurposeMismatch
4227 *
4228 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4229 */
4230TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4231 if (!Curve25519Supported()) {
4232 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4233 }
4234
4235 // Can't have both SIGN and ATTEST_KEY
4236 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4237 .EcdsaSigningKey(EcCurve::CURVE_25519)
4238 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4239 .Digest(Digest::NONE)
4240 .SetDefaultValidity(),
4241 KeyFormat::RAW, ed25519_key));
4242 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4243 // PKCS#8 format and so includes an OID).
4244 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4245 .EcdsaKey(EcCurve::CURVE_25519)
4246 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4247 .Digest(Digest::NONE)
4248 .SetDefaultValidity(),
4249 KeyFormat::PKCS8, ed25519_pkcs8_key));
4250}
4251
4252/*
4253 * ImportKeyTest.X25519RawSuccess
4254 *
4255 * Verifies that importing and using a raw X25519 private key works correctly.
4256 */
4257TEST_P(ImportKeyTest, X25519RawSuccess) {
4258 if (!Curve25519Supported()) {
4259 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4260 }
4261
4262 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4263 .Authorization(TAG_NO_AUTH_REQUIRED)
4264 .EcdsaKey(EcCurve::CURVE_25519)
4265 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4266 .SetDefaultValidity(),
4267 KeyFormat::RAW, x25519_key));
4268
4269 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4270 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4271 CheckOrigin();
4272}
4273
4274/*
4275 * ImportKeyTest.X25519Pkcs8Success
4276 *
4277 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4278 */
4279TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4280 if (!Curve25519Supported()) {
4281 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4282 }
4283
4284 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4285 .Authorization(TAG_NO_AUTH_REQUIRED)
4286 .EcdsaKey(EcCurve::CURVE_25519)
4287 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4288 .SetDefaultValidity(),
4289 KeyFormat::PKCS8, x25519_pkcs8_key));
4290
4291 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4292 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4293 CheckOrigin();
4294}
4295
4296/*
4297 * ImportKeyTest.X25519CurveMismatch
4298 *
4299 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4300 * the correct way.
4301 */
4302TEST_P(ImportKeyTest, X25519CurveMismatch) {
4303 if (!Curve25519Supported()) {
4304 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4305 }
4306
4307 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4308 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4309 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4310 .SetDefaultValidity(),
4311 KeyFormat::RAW, x25519_key));
4312}
4313
4314/*
4315 * ImportKeyTest.X25519FormatMismatch
4316 *
4317 * Verifies that importing an X25519 key with an invalid format fails.
4318 */
4319TEST_P(ImportKeyTest, X25519FormatMismatch) {
4320 if (!Curve25519Supported()) {
4321 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4322 }
4323
4324 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4325 .EcdsaKey(EcCurve::CURVE_25519)
4326 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4327 .SetDefaultValidity(),
4328 KeyFormat::PKCS8, x25519_key));
4329 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4330 .EcdsaKey(EcCurve::CURVE_25519)
4331 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4332 .SetDefaultValidity(),
4333 KeyFormat::RAW, x25519_pkcs8_key));
4334}
4335
4336/*
4337 * ImportKeyTest.X25519PurposeMismatch
4338 *
4339 * Verifies that importing an X25519 key pair with an invalid format fails.
4340 */
4341TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4342 if (!Curve25519Supported()) {
4343 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4344 }
4345
4346 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4347 .EcdsaKey(EcCurve::CURVE_25519)
4348 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4349 .SetDefaultValidity(),
4350 KeyFormat::PKCS8, x25519_pkcs8_key));
4351 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4352 .EcdsaSigningKey(EcCurve::CURVE_25519)
4353 .SetDefaultValidity(),
4354 KeyFormat::PKCS8, x25519_pkcs8_key));
4355}
4356
4357/*
Selene Huang31ab4042020-04-29 04:22:39 -07004358 * ImportKeyTest.AesSuccess
4359 *
4360 * Verifies that importing and using an AES key works.
4361 */
4362TEST_P(ImportKeyTest, AesSuccess) {
4363 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4364 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4365 .Authorization(TAG_NO_AUTH_REQUIRED)
4366 .AesEncryptionKey(key.size() * 8)
4367 .EcbMode()
4368 .Padding(PaddingMode::PKCS7),
4369 KeyFormat::RAW, key));
4370
4371 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4372 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4373 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4374 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4375 CheckOrigin();
4376
4377 string message = "Hello World!";
4378 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4379 string ciphertext = EncryptMessage(message, params);
4380 string plaintext = DecryptMessage(ciphertext, params);
4381 EXPECT_EQ(message, plaintext);
4382}
4383
4384/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004385 * ImportKeyTest.AesFailure
4386 *
4387 * Verifies that importing an invalid AES key fails.
4388 */
4389TEST_P(ImportKeyTest, AesFailure) {
4390 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4391 uint32_t bitlen = key.size() * 8;
4392 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004393 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004394 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004395 .Authorization(TAG_NO_AUTH_REQUIRED)
4396 .AesEncryptionKey(key_size)
4397 .EcbMode()
4398 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004399 KeyFormat::RAW, key);
4400 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004401 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4402 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004403 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004404
4405 // Explicit key size matches that of the provided key, but it's not a valid size.
4406 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4407 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4408 ImportKey(AuthorizationSetBuilder()
4409 .Authorization(TAG_NO_AUTH_REQUIRED)
4410 .AesEncryptionKey(long_key.size() * 8)
4411 .EcbMode()
4412 .Padding(PaddingMode::PKCS7),
4413 KeyFormat::RAW, long_key));
4414 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4415 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4416 ImportKey(AuthorizationSetBuilder()
4417 .Authorization(TAG_NO_AUTH_REQUIRED)
4418 .AesEncryptionKey(short_key.size() * 8)
4419 .EcbMode()
4420 .Padding(PaddingMode::PKCS7),
4421 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004422}
4423
4424/*
4425 * ImportKeyTest.TripleDesSuccess
4426 *
4427 * Verifies that importing and using a 3DES key works.
4428 */
4429TEST_P(ImportKeyTest, TripleDesSuccess) {
4430 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4431 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4432 .Authorization(TAG_NO_AUTH_REQUIRED)
4433 .TripleDesEncryptionKey(168)
4434 .EcbMode()
4435 .Padding(PaddingMode::PKCS7),
4436 KeyFormat::RAW, key));
4437
4438 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4439 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4440 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4441 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4442 CheckOrigin();
4443
4444 string message = "Hello World!";
4445 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4446 string ciphertext = EncryptMessage(message, params);
4447 string plaintext = DecryptMessage(ciphertext, params);
4448 EXPECT_EQ(message, plaintext);
4449}
4450
4451/*
4452 * ImportKeyTest.TripleDesFailure
4453 *
4454 * Verifies that importing an invalid 3DES key fails.
4455 */
4456TEST_P(ImportKeyTest, TripleDesFailure) {
4457 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004458 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004459 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004460 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004461 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004462 .Authorization(TAG_NO_AUTH_REQUIRED)
4463 .TripleDesEncryptionKey(key_size)
4464 .EcbMode()
4465 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004466 KeyFormat::RAW, key);
4467 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004468 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4469 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004470 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004471 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004472 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004473 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4474 ImportKey(AuthorizationSetBuilder()
4475 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004476 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004477 .EcbMode()
4478 .Padding(PaddingMode::PKCS7),
4479 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004480 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004481 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4482 ImportKey(AuthorizationSetBuilder()
4483 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004484 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004485 .EcbMode()
4486 .Padding(PaddingMode::PKCS7),
4487 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004488}
4489
4490/*
4491 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004492 *
4493 * Verifies that importing and using an HMAC key works.
4494 */
4495TEST_P(ImportKeyTest, HmacKeySuccess) {
4496 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4497 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4498 .Authorization(TAG_NO_AUTH_REQUIRED)
4499 .HmacKey(key.size() * 8)
4500 .Digest(Digest::SHA_2_256)
4501 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4502 KeyFormat::RAW, key));
4503
4504 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4505 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4506 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4507 CheckOrigin();
4508
4509 string message = "Hello World!";
4510 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4511 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4512}
4513
4514INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4515
4516auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004517 // IKeyMintDevice.aidl
4518 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4519 "020100" // INTEGER length 1 value 0x00 (version)
4520 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4521 "934bf94e2aa28a3f83c9f79297250262"
4522 "fbe3276b5a1c91159bbfa3ef8957aac8"
4523 "4b59b30b455a79c2973480823d8b3863"
4524 "c3deef4a8e243590268d80e18751a0e1"
4525 "30f67ce6a1ace9f79b95e097474febc9"
4526 "81195b1d13a69086c0863f66a7b7fdb4"
4527 "8792227b1ac5e2489febdf087ab54864"
4528 "83033a6f001ca5d1ec1e27f5c30f4cec"
4529 "2642074a39ae68aee552e196627a8e3d"
4530 "867e67a8c01b11e75f13cca0a97ab668"
4531 "b50cda07a8ecb7cd8e3dd7009c963653"
4532 "4f6f239cffe1fc8daa466f78b676c711"
4533 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4534 "99b801597d5220e307eaa5bee507fb94"
4535 "d1fa69f9e519b2de315bac92c36f2ea1"
4536 "fa1df4478c0ddedeae8c70e0233cd098"
4537 "040c" // OCTET STRING length 0x0c (initializationVector)
4538 "d796b02c370f1fa4cc0124f1"
4539 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4540 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4541 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4542 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4543 "3106" // SET length 0x06
4544 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4545 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4546 // } end SET
4547 // } end [1]
4548 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4549 "020120" // INTEGER length 1 value 0x20 (AES)
4550 // } end [2]
4551 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4552 "02020100" // INTEGER length 2 value 0x100
4553 // } end [3]
4554 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4555 "3103" // SET length 0x03 {
4556 "020101" // INTEGER length 1 value 0x01 (ECB)
4557 // } end SET
4558 // } end [4]
4559 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4560 "3103" // SET length 0x03 {
4561 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4562 // } end SET
4563 // } end [5]
4564 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4565 // (noAuthRequired)
4566 "0500" // NULL
4567 // } end [503]
4568 // } end SEQUENCE (AuthorizationList)
4569 // } end SEQUENCE (KeyDescription)
4570 "0420" // OCTET STRING length 0x20 (encryptedKey)
4571 "ccd540855f833a5e1480bfd2d36faf3a"
4572 "eee15df5beabe2691bc82dde2a7aa910"
4573 "0410" // OCTET STRING length 0x10 (tag)
4574 "64c9f689c60ff6223ab6e6999e0eb6e5"
4575 // } SEQUENCE (SecureKeyWrapper)
4576);
Selene Huang31ab4042020-04-29 04:22:39 -07004577
4578auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004579 // IKeyMintDevice.aidl
4580 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4581 "020100" // INTEGER length 1 value 0x00 (version)
4582 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4583 "aad93ed5924f283b4bb5526fbe7a1412"
4584 "f9d9749ec30db9062b29e574a8546f33"
4585 "c88732452f5b8e6a391ee76c39ed1712"
4586 "c61d8df6213dec1cffbc17a8c6d04c7b"
4587 "30893d8daa9b2015213e219468215532"
4588 "07f8f9931c4caba23ed3bee28b36947e"
4589 "47f10e0a5c3dc51c988a628daad3e5e1"
4590 "f4005e79c2d5a96c284b4b8d7e4948f3"
4591 "31e5b85dd5a236f85579f3ea1d1b8484"
4592 "87470bdb0ab4f81a12bee42c99fe0df4"
4593 "bee3759453e69ad1d68a809ce06b949f"
4594 "7694a990429b2fe81e066ff43e56a216"
4595 "02db70757922a4bcc23ab89f1e35da77"
4596 "586775f423e519c2ea394caf48a28d0c"
4597 "8020f1dcf6b3a68ec246f615ae96dae9"
4598 "a079b1f6eb959033c1af5c125fd94168"
4599 "040c" // OCTET STRING length 0x0c (initializationVector)
4600 "6d9721d08589581ab49204a3"
4601 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4602 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4603 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4604 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4605 "3106" // SET length 0x06
4606 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4607 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4608 // } end SET
4609 // } end [1]
4610 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4611 "020120" // INTEGER length 1 value 0x20 (AES)
4612 // } end [2]
4613 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4614 "02020100" // INTEGER length 2 value 0x100
4615 // } end [3]
4616 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4617 "3103" // SET length 0x03 {
4618 "020101" // INTEGER length 1 value 0x01 (ECB)
4619 // } end SET
4620 // } end [4]
4621 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4622 "3103" // SET length 0x03 {
4623 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4624 // } end SET
4625 // } end [5]
4626 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4627 // (noAuthRequired)
4628 "0500" // NULL
4629 // } end [503]
4630 // } end SEQUENCE (AuthorizationList)
4631 // } end SEQUENCE (KeyDescription)
4632 "0420" // OCTET STRING length 0x20 (encryptedKey)
4633 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4634 "c20d1f99a9a024a76f35c8e2cab9b68d"
4635 "0410" // OCTET STRING length 0x10 (tag)
4636 "2560c70109ae67c030f00b98b512a670"
4637 // } SEQUENCE (SecureKeyWrapper)
4638);
Selene Huang31ab4042020-04-29 04:22:39 -07004639
4640auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004641 // RFC 5208 s5
4642 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4643 "020100" // INTEGER length 1 value 0x00 (version)
4644 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4645 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4646 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4647 "0500" // NULL (parameters)
4648 // } SEQUENCE (AlgorithmIdentifier)
4649 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4650 // RFC 8017 A.1.2
4651 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4652 "020100" // INTEGER length 1 value 0x00 (version)
4653 "02820101" // INTEGER length 0x0101 (modulus) value...
4654 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4655 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4656 "7b06e673a837313d56b1c725150a3fef" // 0x30
4657 "86acbddc41bb759c2854eae32d35841e" // 0x40
4658 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4659 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4660 "312d7bd5921ffaea1347c157406fef71" // 0x70
4661 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4662 "f4645c11f5c1374c3886427411c44979" // 0x90
4663 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4664 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4665 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4666 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4667 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4668 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4669 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4670 "55" // 0x101
4671 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4672 "02820100" // INTEGER length 0x100 (privateExponent) value...
4673 "431447b6251908112b1ee76f99f3711a" // 0x10
4674 "52b6630960046c2de70de188d833f8b8" // 0x20
4675 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4676 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4677 "e710b630a03adc683b5d2c43080e52be" // 0x50
4678 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4679 "822bccff087d63c940ba8a45f670feb2" // 0x70
4680 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4681 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4682 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4683 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4684 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4685 "52659d5a5ba05b663737a8696281865b" // 0xd0
4686 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4687 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4688 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4689 "028181" // INTEGER length 0x81 (prime1) value...
4690 "00de392e18d682c829266cc3454e1d61" // 0x10
4691 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4692 "ff841be5bac82a164c5970007047b8c5" // 0x30
4693 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4694 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4695 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4696 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4697 "9e91346130748a6e3c124f9149d71c74" // 0x80
4698 "35"
4699 "028181" // INTEGER length 0x81 (prime2) value...
4700 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4701 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4702 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4703 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4704 "9ed39a2d934c880440aed8832f984316" // 0x50
4705 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4706 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4707 "b880677c068e1be936e81288815252a8" // 0x80
4708 "a1"
4709 "028180" // INTEGER length 0x80 (exponent1) value...
4710 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4711 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4712 "5a063212a4f105a3764743e53281988a" // 0x30
4713 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4714 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4715 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4716 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4717 "4719d6e2b9439823719cd08bcd031781" // 0x80
4718 "028181" // INTEGER length 0x81 (exponent2) value...
4719 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4720 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4721 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4722 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4723 "1254186af30b22c10582a8a43e34fe94" // 0x50
4724 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4725 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4726 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4727 "61"
4728 "028181" // INTEGER length 0x81 (coefficient) value...
4729 "00c931617c77829dfb1270502be9195c" // 0x10
4730 "8f2830885f57dba869536811e6864236" // 0x20
4731 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4732 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4733 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4734 "959356210723287b0affcc9f727044d4" // 0x60
4735 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4736 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4737 "22"
4738 // } SEQUENCE
4739 // } SEQUENCE ()
4740);
Selene Huang31ab4042020-04-29 04:22:39 -07004741
4742string zero_masking_key =
4743 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4744string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4745
4746class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4747
4748TEST_P(ImportWrappedKeyTest, Success) {
4749 auto wrapping_key_desc = AuthorizationSetBuilder()
4750 .RsaEncryptionKey(2048, 65537)
4751 .Digest(Digest::SHA_2_256)
4752 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004753 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4754 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004755
4756 ASSERT_EQ(ErrorCode::OK,
4757 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4758 AuthorizationSetBuilder()
4759 .Digest(Digest::SHA_2_256)
4760 .Padding(PaddingMode::RSA_OAEP)));
4761
4762 string message = "Hello World!";
4763 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4764 string ciphertext = EncryptMessage(message, params);
4765 string plaintext = DecryptMessage(ciphertext, params);
4766 EXPECT_EQ(message, plaintext);
4767}
4768
David Drysdaled2cc8c22021-04-15 13:29:45 +01004769/*
4770 * ImportWrappedKeyTest.SuccessSidsIgnored
4771 *
4772 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
4773 * include Tag:USER_SECURE_ID.
4774 */
4775TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
4776 auto wrapping_key_desc = AuthorizationSetBuilder()
4777 .RsaEncryptionKey(2048, 65537)
4778 .Digest(Digest::SHA_2_256)
4779 .Padding(PaddingMode::RSA_OAEP)
4780 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4781 .SetDefaultValidity();
4782
4783 int64_t password_sid = 42;
4784 int64_t biometric_sid = 24;
4785 ASSERT_EQ(ErrorCode::OK,
4786 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4787 AuthorizationSetBuilder()
4788 .Digest(Digest::SHA_2_256)
4789 .Padding(PaddingMode::RSA_OAEP),
4790 password_sid, biometric_sid));
4791
4792 string message = "Hello World!";
4793 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4794 string ciphertext = EncryptMessage(message, params);
4795 string plaintext = DecryptMessage(ciphertext, params);
4796 EXPECT_EQ(message, plaintext);
4797}
4798
Selene Huang31ab4042020-04-29 04:22:39 -07004799TEST_P(ImportWrappedKeyTest, SuccessMasked) {
4800 auto wrapping_key_desc = AuthorizationSetBuilder()
4801 .RsaEncryptionKey(2048, 65537)
4802 .Digest(Digest::SHA_2_256)
4803 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004804 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4805 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004806
4807 ASSERT_EQ(ErrorCode::OK,
4808 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
4809 AuthorizationSetBuilder()
4810 .Digest(Digest::SHA_2_256)
4811 .Padding(PaddingMode::RSA_OAEP)));
4812}
4813
4814TEST_P(ImportWrappedKeyTest, WrongMask) {
4815 auto wrapping_key_desc = AuthorizationSetBuilder()
4816 .RsaEncryptionKey(2048, 65537)
4817 .Digest(Digest::SHA_2_256)
4818 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004819 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4820 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004821
4822 ASSERT_EQ(
4823 ErrorCode::VERIFICATION_FAILED,
4824 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4825 AuthorizationSetBuilder()
4826 .Digest(Digest::SHA_2_256)
4827 .Padding(PaddingMode::RSA_OAEP)));
4828}
4829
4830TEST_P(ImportWrappedKeyTest, WrongPurpose) {
4831 auto wrapping_key_desc = AuthorizationSetBuilder()
4832 .RsaEncryptionKey(2048, 65537)
4833 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004834 .Padding(PaddingMode::RSA_OAEP)
4835 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004836
4837 ASSERT_EQ(
4838 ErrorCode::INCOMPATIBLE_PURPOSE,
4839 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4840 AuthorizationSetBuilder()
4841 .Digest(Digest::SHA_2_256)
4842 .Padding(PaddingMode::RSA_OAEP)));
4843}
4844
David Drysdaled2cc8c22021-04-15 13:29:45 +01004845TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
4846 auto wrapping_key_desc = AuthorizationSetBuilder()
4847 .RsaEncryptionKey(2048, 65537)
4848 .Digest(Digest::SHA_2_256)
4849 .Padding(PaddingMode::RSA_PSS)
4850 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4851 .SetDefaultValidity();
4852
4853 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
4854 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4855 AuthorizationSetBuilder()
4856 .Digest(Digest::SHA_2_256)
4857 .Padding(PaddingMode::RSA_OAEP)));
4858}
4859
4860TEST_P(ImportWrappedKeyTest, WrongDigest) {
4861 auto wrapping_key_desc = AuthorizationSetBuilder()
4862 .RsaEncryptionKey(2048, 65537)
4863 .Digest(Digest::SHA_2_512)
4864 .Padding(PaddingMode::RSA_OAEP)
4865 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4866 .SetDefaultValidity();
4867
4868 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
4869 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4870 AuthorizationSetBuilder()
4871 .Digest(Digest::SHA_2_256)
4872 .Padding(PaddingMode::RSA_OAEP)));
4873}
4874
Selene Huang31ab4042020-04-29 04:22:39 -07004875INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
4876
4877typedef KeyMintAidlTestBase EncryptionOperationsTest;
4878
4879/*
4880 * EncryptionOperationsTest.RsaNoPaddingSuccess
4881 *
David Drysdale59cae642021-05-12 13:52:03 +01004882 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07004883 */
4884TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00004885 for (uint64_t exponent : ValidExponents()) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01004886 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4887 .Authorization(TAG_NO_AUTH_REQUIRED)
4888 .RsaEncryptionKey(2048, exponent)
4889 .Padding(PaddingMode::NONE)
4890 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004891
David Drysdaled2cc8c22021-04-15 13:29:45 +01004892 string message = string(2048 / 8, 'a');
4893 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004894 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004895 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004896
David Drysdale59cae642021-05-12 13:52:03 +01004897 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004898 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004899
David Drysdaled2cc8c22021-04-15 13:29:45 +01004900 // Unpadded RSA is deterministic
4901 EXPECT_EQ(ciphertext1, ciphertext2);
4902
4903 CheckedDeleteKey();
4904 }
Selene Huang31ab4042020-04-29 04:22:39 -07004905}
4906
4907/*
4908 * EncryptionOperationsTest.RsaNoPaddingShortMessage
4909 *
David Drysdale59cae642021-05-12 13:52:03 +01004910 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07004911 */
4912TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
4913 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4914 .Authorization(TAG_NO_AUTH_REQUIRED)
4915 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004916 .Padding(PaddingMode::NONE)
4917 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004918
4919 string message = "1";
4920 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4921
David Drysdale59cae642021-05-12 13:52:03 +01004922 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004923 EXPECT_EQ(2048U / 8, ciphertext.size());
4924
4925 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
4926 string plaintext = DecryptMessage(ciphertext, params);
4927
4928 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07004929}
4930
4931/*
Selene Huang31ab4042020-04-29 04:22:39 -07004932 * EncryptionOperationsTest.RsaOaepSuccess
4933 *
David Drysdale59cae642021-05-12 13:52:03 +01004934 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07004935 */
4936TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
4937 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4938
4939 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01004940 ASSERT_EQ(ErrorCode::OK,
4941 GenerateKey(AuthorizationSetBuilder()
4942 .Authorization(TAG_NO_AUTH_REQUIRED)
4943 .RsaEncryptionKey(key_size, 65537)
4944 .Padding(PaddingMode::RSA_OAEP)
4945 .Digest(digests)
4946 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
4947 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004948
4949 string message = "Hello";
4950
4951 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01004952 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4953
4954 auto params = AuthorizationSetBuilder()
4955 .Digest(digest)
4956 .Padding(PaddingMode::RSA_OAEP)
4957 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
4958 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004959 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4960 EXPECT_EQ(key_size / 8, ciphertext1.size());
4961
David Drysdale59cae642021-05-12 13:52:03 +01004962 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004963 EXPECT_EQ(key_size / 8, ciphertext2.size());
4964
4965 // OAEP randomizes padding so every result should be different (with astronomically high
4966 // probability).
4967 EXPECT_NE(ciphertext1, ciphertext2);
4968
4969 string plaintext1 = DecryptMessage(ciphertext1, params);
4970 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4971 string plaintext2 = DecryptMessage(ciphertext2, params);
4972 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4973
4974 // Decrypting corrupted ciphertext should fail.
4975 size_t offset_to_corrupt = random() % ciphertext1.size();
4976 char corrupt_byte;
4977 do {
4978 corrupt_byte = static_cast<char>(random() % 256);
4979 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4980 ciphertext1[offset_to_corrupt] = corrupt_byte;
4981
4982 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4983 string result;
4984 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4985 EXPECT_EQ(0U, result.size());
4986 }
4987}
4988
4989/*
4990 * EncryptionOperationsTest.RsaOaepInvalidDigest
4991 *
David Drysdale59cae642021-05-12 13:52:03 +01004992 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07004993 * without a digest.
4994 */
4995TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
4996 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4997 .Authorization(TAG_NO_AUTH_REQUIRED)
4998 .RsaEncryptionKey(2048, 65537)
4999 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005000 .Digest(Digest::NONE)
5001 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005002
5003 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005004 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005005}
5006
5007/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005008 * EncryptionOperationsTest.RsaOaepInvalidPadding
5009 *
David Drysdale59cae642021-05-12 13:52:03 +01005010 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005011 * with a padding value that is only suitable for signing/verifying.
5012 */
5013TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5014 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5015 .Authorization(TAG_NO_AUTH_REQUIRED)
5016 .RsaEncryptionKey(2048, 65537)
5017 .Padding(PaddingMode::RSA_PSS)
5018 .Digest(Digest::NONE)
5019 .SetDefaultValidity()));
5020
5021 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005022 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005023}
5024
5025/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005026 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005027 *
David Drysdale59cae642021-05-12 13:52:03 +01005028 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005029 * with a different digest than was used to encrypt.
5030 */
5031TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005032 if (SecLevel() == SecurityLevel::STRONGBOX) {
5033 GTEST_SKIP() << "Test not applicable to StrongBox device";
5034 }
Selene Huang31ab4042020-04-29 04:22:39 -07005035
5036 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5037 .Authorization(TAG_NO_AUTH_REQUIRED)
5038 .RsaEncryptionKey(1024, 65537)
5039 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005040 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5041 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005042 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005043 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005044 message,
5045 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5046
5047 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5048 .Digest(Digest::SHA_2_256)
5049 .Padding(PaddingMode::RSA_OAEP)));
5050 string result;
5051 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5052 EXPECT_EQ(0U, result.size());
5053}
5054
5055/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005056 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5057 *
David Drysdale59cae642021-05-12 13:52:03 +01005058 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005059 * digests.
5060 */
5061TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5062 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5063
5064 size_t key_size = 2048; // Need largish key for SHA-512 test.
5065 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5066 .OaepMGFDigest(digests)
5067 .Authorization(TAG_NO_AUTH_REQUIRED)
5068 .RsaEncryptionKey(key_size, 65537)
5069 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005070 .Digest(Digest::SHA_2_256)
5071 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005072
5073 string message = "Hello";
5074
5075 for (auto digest : digests) {
5076 auto params = AuthorizationSetBuilder()
5077 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5078 .Digest(Digest::SHA_2_256)
5079 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005080 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005081 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5082 EXPECT_EQ(key_size / 8, ciphertext1.size());
5083
David Drysdale59cae642021-05-12 13:52:03 +01005084 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005085 EXPECT_EQ(key_size / 8, ciphertext2.size());
5086
5087 // OAEP randomizes padding so every result should be different (with astronomically high
5088 // probability).
5089 EXPECT_NE(ciphertext1, ciphertext2);
5090
5091 string plaintext1 = DecryptMessage(ciphertext1, params);
5092 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5093 string plaintext2 = DecryptMessage(ciphertext2, params);
5094 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5095
5096 // Decrypting corrupted ciphertext should fail.
5097 size_t offset_to_corrupt = random() % ciphertext1.size();
5098 char corrupt_byte;
5099 do {
5100 corrupt_byte = static_cast<char>(random() % 256);
5101 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5102 ciphertext1[offset_to_corrupt] = corrupt_byte;
5103
5104 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5105 string result;
5106 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5107 EXPECT_EQ(0U, result.size());
5108 }
5109}
5110
5111/*
5112 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5113 *
David Drysdale59cae642021-05-12 13:52:03 +01005114 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005115 * with incompatible MGF digest.
5116 */
5117TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5118 ASSERT_EQ(ErrorCode::OK,
5119 GenerateKey(AuthorizationSetBuilder()
5120 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5121 .Authorization(TAG_NO_AUTH_REQUIRED)
5122 .RsaEncryptionKey(2048, 65537)
5123 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005124 .Digest(Digest::SHA_2_256)
5125 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005126 string message = "Hello World!";
5127
5128 auto params = AuthorizationSetBuilder()
5129 .Padding(PaddingMode::RSA_OAEP)
5130 .Digest(Digest::SHA_2_256)
5131 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005132 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005133}
5134
5135/*
5136 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5137 *
5138 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5139 * with unsupported MGF digest.
5140 */
5141TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5142 ASSERT_EQ(ErrorCode::OK,
5143 GenerateKey(AuthorizationSetBuilder()
5144 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5145 .Authorization(TAG_NO_AUTH_REQUIRED)
5146 .RsaEncryptionKey(2048, 65537)
5147 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005148 .Digest(Digest::SHA_2_256)
5149 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005150 string message = "Hello World!";
5151
5152 auto params = AuthorizationSetBuilder()
5153 .Padding(PaddingMode::RSA_OAEP)
5154 .Digest(Digest::SHA_2_256)
5155 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005156 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005157}
5158
5159/*
Selene Huang31ab4042020-04-29 04:22:39 -07005160 * EncryptionOperationsTest.RsaPkcs1Success
5161 *
5162 * Verifies that RSA PKCS encryption/decrypts works.
5163 */
5164TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5165 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5166 .Authorization(TAG_NO_AUTH_REQUIRED)
5167 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005168 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5169 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005170
5171 string message = "Hello World!";
5172 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005173 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005174 EXPECT_EQ(2048U / 8, ciphertext1.size());
5175
David Drysdale59cae642021-05-12 13:52:03 +01005176 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005177 EXPECT_EQ(2048U / 8, ciphertext2.size());
5178
5179 // PKCS1 v1.5 randomizes padding so every result should be different.
5180 EXPECT_NE(ciphertext1, ciphertext2);
5181
5182 string plaintext = DecryptMessage(ciphertext1, params);
5183 EXPECT_EQ(message, plaintext);
5184
5185 // Decrypting corrupted ciphertext should fail.
5186 size_t offset_to_corrupt = random() % ciphertext1.size();
5187 char corrupt_byte;
5188 do {
5189 corrupt_byte = static_cast<char>(random() % 256);
5190 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5191 ciphertext1[offset_to_corrupt] = corrupt_byte;
5192
5193 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5194 string result;
5195 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5196 EXPECT_EQ(0U, result.size());
5197}
5198
5199/*
Selene Huang31ab4042020-04-29 04:22:39 -07005200 * EncryptionOperationsTest.EcdsaEncrypt
5201 *
5202 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5203 */
5204TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5205 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5206 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005207 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005208 .Digest(Digest::NONE)
5209 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005210 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5211 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5212 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5213}
5214
5215/*
5216 * EncryptionOperationsTest.HmacEncrypt
5217 *
5218 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5219 */
5220TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5221 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5222 .Authorization(TAG_NO_AUTH_REQUIRED)
5223 .HmacKey(128)
5224 .Digest(Digest::SHA_2_256)
5225 .Padding(PaddingMode::NONE)
5226 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5227 auto params = AuthorizationSetBuilder()
5228 .Digest(Digest::SHA_2_256)
5229 .Padding(PaddingMode::NONE)
5230 .Authorization(TAG_MAC_LENGTH, 128);
5231 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5232 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5233}
5234
5235/*
5236 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5237 *
5238 * Verifies that AES ECB mode works.
5239 */
5240TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5241 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5242 .Authorization(TAG_NO_AUTH_REQUIRED)
5243 .AesEncryptionKey(128)
5244 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5245 .Padding(PaddingMode::NONE)));
5246
5247 ASSERT_GT(key_blob_.size(), 0U);
5248 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5249
5250 // Two-block message.
5251 string message = "12345678901234567890123456789012";
5252 string ciphertext1 = EncryptMessage(message, params);
5253 EXPECT_EQ(message.size(), ciphertext1.size());
5254
5255 string ciphertext2 = EncryptMessage(string(message), params);
5256 EXPECT_EQ(message.size(), ciphertext2.size());
5257
5258 // ECB is deterministic.
5259 EXPECT_EQ(ciphertext1, ciphertext2);
5260
5261 string plaintext = DecryptMessage(ciphertext1, params);
5262 EXPECT_EQ(message, plaintext);
5263}
5264
5265/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005266 * EncryptionOperationsTest.AesEcbUnknownTag
5267 *
5268 * Verifies that AES ECB operations ignore unknown tags.
5269 */
5270TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5271 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5272 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5273 KeyParameter unknown_param;
5274 unknown_param.tag = unknown_tag;
5275
5276 vector<KeyCharacteristics> key_characteristics;
5277 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5278 .Authorization(TAG_NO_AUTH_REQUIRED)
5279 .AesEncryptionKey(128)
5280 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5281 .Padding(PaddingMode::NONE)
5282 .Authorization(unknown_param),
5283 &key_blob_, &key_characteristics));
5284 ASSERT_GT(key_blob_.size(), 0U);
5285
5286 // Unknown tags should not be returned in key characteristics.
5287 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5288 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5289 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5290 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5291
5292 // Encrypt without mentioning the unknown parameter.
5293 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5294 string message = "12345678901234567890123456789012";
5295 string ciphertext = EncryptMessage(message, params);
5296 EXPECT_EQ(message.size(), ciphertext.size());
5297
5298 // Decrypt including the unknown parameter.
5299 auto decrypt_params = AuthorizationSetBuilder()
5300 .BlockMode(BlockMode::ECB)
5301 .Padding(PaddingMode::NONE)
5302 .Authorization(unknown_param);
5303 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5304 EXPECT_EQ(message, plaintext);
5305}
5306
5307/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005308 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005309 *
5310 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5311 */
5312TEST_P(EncryptionOperationsTest, AesWrongMode) {
5313 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5314 .Authorization(TAG_NO_AUTH_REQUIRED)
5315 .AesEncryptionKey(128)
5316 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5317 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005318 ASSERT_GT(key_blob_.size(), 0U);
5319
Selene Huang31ab4042020-04-29 04:22:39 -07005320 EXPECT_EQ(
5321 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5322 Begin(KeyPurpose::ENCRYPT,
5323 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5324}
5325
5326/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005327 * EncryptionOperationsTest.AesWrongPadding
5328 *
5329 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5330 */
5331TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5332 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5333 .Authorization(TAG_NO_AUTH_REQUIRED)
5334 .AesEncryptionKey(128)
5335 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5336 .Padding(PaddingMode::NONE)));
5337 ASSERT_GT(key_blob_.size(), 0U);
5338
5339 EXPECT_EQ(
5340 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5341 Begin(KeyPurpose::ENCRYPT,
5342 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5343}
5344
5345/*
5346 * EncryptionOperationsTest.AesInvalidParams
5347 *
5348 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5349 */
5350TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5351 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5352 .Authorization(TAG_NO_AUTH_REQUIRED)
5353 .AesEncryptionKey(128)
5354 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5355 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5356 .Padding(PaddingMode::NONE)
5357 .Padding(PaddingMode::PKCS7)));
5358 ASSERT_GT(key_blob_.size(), 0U);
5359
5360 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5361 .BlockMode(BlockMode::CBC)
5362 .BlockMode(BlockMode::ECB)
5363 .Padding(PaddingMode::NONE));
5364 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5365 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5366
5367 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5368 .BlockMode(BlockMode::ECB)
5369 .Padding(PaddingMode::NONE)
5370 .Padding(PaddingMode::PKCS7));
5371 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5372 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5373}
5374
5375/*
Selene Huang31ab4042020-04-29 04:22:39 -07005376 * EncryptionOperationsTest.AesWrongPurpose
5377 *
5378 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5379 * specified.
5380 */
5381TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5382 auto err = GenerateKey(AuthorizationSetBuilder()
5383 .Authorization(TAG_NO_AUTH_REQUIRED)
5384 .AesKey(128)
5385 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5386 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5387 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5388 .Padding(PaddingMode::NONE));
5389 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5390 ASSERT_GT(key_blob_.size(), 0U);
5391
5392 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5393 .BlockMode(BlockMode::GCM)
5394 .Padding(PaddingMode::NONE)
5395 .Authorization(TAG_MAC_LENGTH, 128));
5396 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5397
5398 CheckedDeleteKey();
5399
5400 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5401 .Authorization(TAG_NO_AUTH_REQUIRED)
5402 .AesKey(128)
5403 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5404 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5405 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5406 .Padding(PaddingMode::NONE)));
5407
5408 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5409 .BlockMode(BlockMode::GCM)
5410 .Padding(PaddingMode::NONE)
5411 .Authorization(TAG_MAC_LENGTH, 128));
5412 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5413}
5414
5415/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005416 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005417 *
5418 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5419 * multiple of the block size and no padding is specified.
5420 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005421TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5422 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5423 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5424 .Authorization(TAG_NO_AUTH_REQUIRED)
5425 .AesEncryptionKey(128)
5426 .Authorization(TAG_BLOCK_MODE, blockMode)
5427 .Padding(PaddingMode::NONE)));
5428 // Message is slightly shorter than two blocks.
5429 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005430
David Drysdaled2cc8c22021-04-15 13:29:45 +01005431 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5432 AuthorizationSet out_params;
5433 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5434 string ciphertext;
5435 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5436 EXPECT_EQ(0U, ciphertext.size());
5437
5438 CheckedDeleteKey();
5439 }
Selene Huang31ab4042020-04-29 04:22:39 -07005440}
5441
5442/*
5443 * EncryptionOperationsTest.AesEcbPkcs7Padding
5444 *
5445 * Verifies that AES PKCS7 padding works for any message length.
5446 */
5447TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5448 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5449 .Authorization(TAG_NO_AUTH_REQUIRED)
5450 .AesEncryptionKey(128)
5451 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5452 .Padding(PaddingMode::PKCS7)));
5453
5454 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5455
5456 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005457 for (size_t i = 0; i <= 48; i++) {
5458 SCOPED_TRACE(testing::Message() << "i = " << i);
5459 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5460 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005461 string ciphertext = EncryptMessage(message, params);
5462 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5463 string plaintext = DecryptMessage(ciphertext, params);
5464 EXPECT_EQ(message, plaintext);
5465 }
5466}
5467
5468/*
5469 * EncryptionOperationsTest.AesEcbWrongPadding
5470 *
5471 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5472 * specified.
5473 */
5474TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5475 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5476 .Authorization(TAG_NO_AUTH_REQUIRED)
5477 .AesEncryptionKey(128)
5478 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5479 .Padding(PaddingMode::NONE)));
5480
5481 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5482
5483 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005484 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005485 string message(i, 'a');
5486 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5487 }
5488}
5489
5490/*
5491 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5492 *
5493 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5494 */
5495TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5496 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5497 .Authorization(TAG_NO_AUTH_REQUIRED)
5498 .AesEncryptionKey(128)
5499 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5500 .Padding(PaddingMode::PKCS7)));
5501
5502 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5503
5504 string message = "a";
5505 string ciphertext = EncryptMessage(message, params);
5506 EXPECT_EQ(16U, ciphertext.size());
5507 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005508
Seth Moore7a55ae32021-06-23 14:28:11 -07005509 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5510 ++ciphertext[ciphertext.size() / 2];
5511
5512 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5513 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005514 ErrorCode error = Finish(ciphertext, &plaintext);
5515 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005516 // This is the expected error, we can exit the test now.
5517 return;
5518 } else {
5519 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005520 ASSERT_EQ(error, ErrorCode::OK)
5521 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005522 }
5523 }
5524 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005525}
5526
David Drysdaleb8093292022-04-08 12:22:35 +01005527/*
5528 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5529 *
5530 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5531 */
5532TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5533 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5534 .Authorization(TAG_NO_AUTH_REQUIRED)
5535 .AesEncryptionKey(128)
5536 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5537 .Padding(PaddingMode::PKCS7)));
5538
5539 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5540
5541 string message = "a";
5542 string ciphertext = EncryptMessage(message, params);
5543 EXPECT_EQ(16U, ciphertext.size());
5544 EXPECT_NE(ciphertext, message);
5545
5546 // Shorten the ciphertext.
5547 ciphertext.resize(ciphertext.size() - 1);
5548 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5549 string plaintext;
5550 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5551}
5552
Selene Huang31ab4042020-04-29 04:22:39 -07005553vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5554 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005555 EXPECT_TRUE(iv);
5556 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005557}
5558
5559/*
5560 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5561 *
5562 * Verifies that AES CTR mode works.
5563 */
5564TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5565 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5566 .Authorization(TAG_NO_AUTH_REQUIRED)
5567 .AesEncryptionKey(128)
5568 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5569 .Padding(PaddingMode::NONE)));
5570
5571 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5572
5573 string message = "123";
5574 AuthorizationSet out_params;
5575 string ciphertext1 = EncryptMessage(message, params, &out_params);
5576 vector<uint8_t> iv1 = CopyIv(out_params);
5577 EXPECT_EQ(16U, iv1.size());
5578
5579 EXPECT_EQ(message.size(), ciphertext1.size());
5580
5581 out_params.Clear();
5582 string ciphertext2 = EncryptMessage(message, params, &out_params);
5583 vector<uint8_t> iv2 = CopyIv(out_params);
5584 EXPECT_EQ(16U, iv2.size());
5585
5586 // IVs should be random, so ciphertexts should differ.
5587 EXPECT_NE(ciphertext1, ciphertext2);
5588
5589 auto params_iv1 =
5590 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5591 auto params_iv2 =
5592 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5593
5594 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5595 EXPECT_EQ(message, plaintext);
5596 plaintext = DecryptMessage(ciphertext2, params_iv2);
5597 EXPECT_EQ(message, plaintext);
5598
5599 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5600 plaintext = DecryptMessage(ciphertext1, params_iv2);
5601 EXPECT_NE(message, plaintext);
5602 plaintext = DecryptMessage(ciphertext2, params_iv1);
5603 EXPECT_NE(message, plaintext);
5604}
5605
5606/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305607 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07005608 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305609 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07005610 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305611TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5612 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5613}
Selene Huang31ab4042020-04-29 04:22:39 -07005614
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305615/*
5616 * EncryptionOperationsTest.AesCbcIncremental
5617 *
5618 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5619 */
5620TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5621 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5622}
Selene Huang31ab4042020-04-29 04:22:39 -07005623
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305624/*
5625 * EncryptionOperationsTest.AesCtrIncremental
5626 *
5627 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5628 */
5629TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5630 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5631}
Selene Huang31ab4042020-04-29 04:22:39 -07005632
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305633/*
5634 * EncryptionOperationsTest.AesGcmIncremental
5635 *
5636 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5637 */
5638TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5639 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07005640}
5641
5642struct AesCtrSp80038aTestVector {
5643 const char* key;
5644 const char* nonce;
5645 const char* plaintext;
5646 const char* ciphertext;
5647};
5648
5649// These test vectors are taken from
5650// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
5651static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
5652 // AES-128
5653 {
5654 "2b7e151628aed2a6abf7158809cf4f3c",
5655 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5656 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5657 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5658 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
5659 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
5660 },
5661 // AES-192
5662 {
5663 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
5664 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5665 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5666 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5667 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
5668 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
5669 },
5670 // AES-256
5671 {
5672 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
5673 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5674 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5675 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5676 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
5677 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
5678 },
5679};
5680
5681/*
5682 * EncryptionOperationsTest.AesCtrSp80038aTestVector
5683 *
5684 * Verifies AES CTR implementation against SP800-38A test vectors.
5685 */
5686TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
5687 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
5688 for (size_t i = 0; i < 3; i++) {
5689 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
5690 const string key = hex2str(test.key);
5691 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
5692 InvalidSizes.end())
5693 continue;
5694 const string nonce = hex2str(test.nonce);
5695 const string plaintext = hex2str(test.plaintext);
5696 const string ciphertext = hex2str(test.ciphertext);
5697 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
5698 }
5699}
5700
5701/*
5702 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
5703 *
5704 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
5705 */
5706TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
5707 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5708 .Authorization(TAG_NO_AUTH_REQUIRED)
5709 .AesEncryptionKey(128)
5710 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5711 .Padding(PaddingMode::PKCS7)));
5712 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5713 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5714}
5715
5716/*
5717 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
5718 *
5719 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5720 */
5721TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
5722 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5723 .Authorization(TAG_NO_AUTH_REQUIRED)
5724 .AesEncryptionKey(128)
5725 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5726 .Authorization(TAG_CALLER_NONCE)
5727 .Padding(PaddingMode::NONE)));
5728
5729 auto params = AuthorizationSetBuilder()
5730 .BlockMode(BlockMode::CTR)
5731 .Padding(PaddingMode::NONE)
5732 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
5733 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5734
5735 params = AuthorizationSetBuilder()
5736 .BlockMode(BlockMode::CTR)
5737 .Padding(PaddingMode::NONE)
5738 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
5739 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5740
5741 params = AuthorizationSetBuilder()
5742 .BlockMode(BlockMode::CTR)
5743 .Padding(PaddingMode::NONE)
5744 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
5745 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5746}
5747
5748/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005749 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07005750 *
5751 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5752 */
5753TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
5754 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5755 .Authorization(TAG_NO_AUTH_REQUIRED)
5756 .AesEncryptionKey(128)
5757 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5758 .Padding(PaddingMode::NONE)));
5759 // Two-block message.
5760 string message = "12345678901234567890123456789012";
5761 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5762 AuthorizationSet out_params;
5763 string ciphertext1 = EncryptMessage(message, params, &out_params);
5764 vector<uint8_t> iv1 = CopyIv(out_params);
5765 EXPECT_EQ(message.size(), ciphertext1.size());
5766
5767 out_params.Clear();
5768
5769 string ciphertext2 = EncryptMessage(message, params, &out_params);
5770 vector<uint8_t> iv2 = CopyIv(out_params);
5771 EXPECT_EQ(message.size(), ciphertext2.size());
5772
5773 // IVs should be random, so ciphertexts should differ.
5774 EXPECT_NE(ciphertext1, ciphertext2);
5775
5776 params.push_back(TAG_NONCE, iv1);
5777 string plaintext = DecryptMessage(ciphertext1, params);
5778 EXPECT_EQ(message, plaintext);
5779}
5780
5781/*
Tommy Chiuee705692021-09-23 20:09:13 +08005782 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
5783 *
5784 * Verifies that keymaster generates correct output on zero-input with
5785 * NonePadding mode
5786 */
5787TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
5788 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5789 .Authorization(TAG_NO_AUTH_REQUIRED)
5790 .AesEncryptionKey(128)
5791 .BlockMode(BlockMode::CBC)
5792 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
5793
5794 // Zero input message
5795 string message = "";
5796 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
5797 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
5798 AuthorizationSet out_params;
5799 string ciphertext1 = EncryptMessage(message, params, &out_params);
5800 vector<uint8_t> iv1 = CopyIv(out_params);
5801 if (padding == PaddingMode::NONE)
5802 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
5803 else
5804 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
5805
5806 out_params.Clear();
5807
5808 string ciphertext2 = EncryptMessage(message, params, &out_params);
5809 vector<uint8_t> iv2 = CopyIv(out_params);
5810 if (padding == PaddingMode::NONE)
5811 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
5812 else
5813 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
5814
5815 // IVs should be random
5816 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
5817
5818 params.push_back(TAG_NONCE, iv1);
5819 string plaintext = DecryptMessage(ciphertext1, params);
5820 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
5821 }
5822}
5823
5824/*
Selene Huang31ab4042020-04-29 04:22:39 -07005825 * EncryptionOperationsTest.AesCallerNonce
5826 *
5827 * Verifies that AES caller-provided nonces work correctly.
5828 */
5829TEST_P(EncryptionOperationsTest, AesCallerNonce) {
5830 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5831 .Authorization(TAG_NO_AUTH_REQUIRED)
5832 .AesEncryptionKey(128)
5833 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5834 .Authorization(TAG_CALLER_NONCE)
5835 .Padding(PaddingMode::NONE)));
5836
5837 string message = "12345678901234567890123456789012";
5838
5839 // Don't specify nonce, should get a random one.
5840 AuthorizationSetBuilder params =
5841 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5842 AuthorizationSet out_params;
5843 string ciphertext = EncryptMessage(message, params, &out_params);
5844 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005845 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005846
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005847 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005848 string plaintext = DecryptMessage(ciphertext, params);
5849 EXPECT_EQ(message, plaintext);
5850
5851 // Now specify a nonce, should also work.
5852 params = AuthorizationSetBuilder()
5853 .BlockMode(BlockMode::CBC)
5854 .Padding(PaddingMode::NONE)
5855 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5856 out_params.Clear();
5857 ciphertext = EncryptMessage(message, params, &out_params);
5858
5859 // Decrypt with correct nonce.
5860 plaintext = DecryptMessage(ciphertext, params);
5861 EXPECT_EQ(message, plaintext);
5862
5863 // Try with wrong nonce.
5864 params = AuthorizationSetBuilder()
5865 .BlockMode(BlockMode::CBC)
5866 .Padding(PaddingMode::NONE)
5867 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
5868 plaintext = DecryptMessage(ciphertext, params);
5869 EXPECT_NE(message, plaintext);
5870}
5871
5872/*
5873 * EncryptionOperationsTest.AesCallerNonceProhibited
5874 *
5875 * Verifies that caller-provided nonces are not permitted when not specified in the key
5876 * authorizations.
5877 */
5878TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
5879 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5880 .Authorization(TAG_NO_AUTH_REQUIRED)
5881 .AesEncryptionKey(128)
5882 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5883 .Padding(PaddingMode::NONE)));
5884
5885 string message = "12345678901234567890123456789012";
5886
5887 // Don't specify nonce, should get a random one.
5888 AuthorizationSetBuilder params =
5889 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5890 AuthorizationSet out_params;
5891 string ciphertext = EncryptMessage(message, params, &out_params);
5892 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005893 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005894
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005895 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005896 string plaintext = DecryptMessage(ciphertext, params);
5897 EXPECT_EQ(message, plaintext);
5898
5899 // Now specify a nonce, should fail
5900 params = AuthorizationSetBuilder()
5901 .BlockMode(BlockMode::CBC)
5902 .Padding(PaddingMode::NONE)
5903 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5904 out_params.Clear();
5905 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5906}
5907
5908/*
5909 * EncryptionOperationsTest.AesGcmRoundTripSuccess
5910 *
5911 * Verifies that AES GCM mode works.
5912 */
5913TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
5914 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5915 .Authorization(TAG_NO_AUTH_REQUIRED)
5916 .AesEncryptionKey(128)
5917 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5918 .Padding(PaddingMode::NONE)
5919 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5920
5921 string aad = "foobar";
5922 string message = "123456789012345678901234567890123456";
5923
5924 auto begin_params = AuthorizationSetBuilder()
5925 .BlockMode(BlockMode::GCM)
5926 .Padding(PaddingMode::NONE)
5927 .Authorization(TAG_MAC_LENGTH, 128);
5928
Selene Huang31ab4042020-04-29 04:22:39 -07005929 // Encrypt
5930 AuthorizationSet begin_out_params;
5931 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5932 << "Begin encrypt";
5933 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005934 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5935 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005936 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5937
5938 // Grab nonce
5939 begin_params.push_back(begin_out_params);
5940
5941 // Decrypt.
5942 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07005943 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005944 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005945 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005946 EXPECT_EQ(message.length(), plaintext.length());
5947 EXPECT_EQ(message, plaintext);
5948}
5949
5950/*
5951 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
5952 *
5953 * Verifies that AES GCM mode works, even when there's a long delay
5954 * between operations.
5955 */
5956TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
5957 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5958 .Authorization(TAG_NO_AUTH_REQUIRED)
5959 .AesEncryptionKey(128)
5960 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5961 .Padding(PaddingMode::NONE)
5962 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5963
5964 string aad = "foobar";
5965 string message = "123456789012345678901234567890123456";
5966
5967 auto begin_params = AuthorizationSetBuilder()
5968 .BlockMode(BlockMode::GCM)
5969 .Padding(PaddingMode::NONE)
5970 .Authorization(TAG_MAC_LENGTH, 128);
5971
Selene Huang31ab4042020-04-29 04:22:39 -07005972 // Encrypt
5973 AuthorizationSet begin_out_params;
5974 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5975 << "Begin encrypt";
5976 string ciphertext;
5977 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005978 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005979 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005980 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005981
5982 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5983
5984 // Grab nonce
5985 begin_params.push_back(begin_out_params);
5986
5987 // Decrypt.
5988 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
5989 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005990 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005991 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005992 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005993 sleep(5);
5994 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
5995 EXPECT_EQ(message.length(), plaintext.length());
5996 EXPECT_EQ(message, plaintext);
5997}
5998
5999/*
6000 * EncryptionOperationsTest.AesGcmDifferentNonces
6001 *
6002 * Verifies that encrypting the same data with different nonces produces different outputs.
6003 */
6004TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6005 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6006 .Authorization(TAG_NO_AUTH_REQUIRED)
6007 .AesEncryptionKey(128)
6008 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6009 .Padding(PaddingMode::NONE)
6010 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6011 .Authorization(TAG_CALLER_NONCE)));
6012
6013 string aad = "foobar";
6014 string message = "123456789012345678901234567890123456";
6015 string nonce1 = "000000000000";
6016 string nonce2 = "111111111111";
6017 string nonce3 = "222222222222";
6018
6019 string ciphertext1 =
6020 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6021 string ciphertext2 =
6022 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6023 string ciphertext3 =
6024 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6025
6026 ASSERT_NE(ciphertext1, ciphertext2);
6027 ASSERT_NE(ciphertext1, ciphertext3);
6028 ASSERT_NE(ciphertext2, ciphertext3);
6029}
6030
6031/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006032 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6033 *
6034 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6035 */
6036TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6037 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6038 .Authorization(TAG_NO_AUTH_REQUIRED)
6039 .AesEncryptionKey(128)
6040 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6041 .Padding(PaddingMode::NONE)
6042 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6043
6044 string aad = "foobar";
6045 string message = "123456789012345678901234567890123456";
6046
6047 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6048 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6049 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6050
6051 ASSERT_NE(ciphertext1, ciphertext2);
6052 ASSERT_NE(ciphertext1, ciphertext3);
6053 ASSERT_NE(ciphertext2, ciphertext3);
6054}
6055
6056/*
Selene Huang31ab4042020-04-29 04:22:39 -07006057 * EncryptionOperationsTest.AesGcmTooShortTag
6058 *
6059 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6060 */
6061TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6062 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6063 .Authorization(TAG_NO_AUTH_REQUIRED)
6064 .AesEncryptionKey(128)
6065 .BlockMode(BlockMode::GCM)
6066 .Padding(PaddingMode::NONE)
6067 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6068 string message = "123456789012345678901234567890123456";
6069 auto params = AuthorizationSetBuilder()
6070 .BlockMode(BlockMode::GCM)
6071 .Padding(PaddingMode::NONE)
6072 .Authorization(TAG_MAC_LENGTH, 96);
6073
6074 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6075}
6076
6077/*
6078 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6079 *
6080 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6081 */
6082TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6083 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6084 .Authorization(TAG_NO_AUTH_REQUIRED)
6085 .AesEncryptionKey(128)
6086 .BlockMode(BlockMode::GCM)
6087 .Padding(PaddingMode::NONE)
6088 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6089 string aad = "foobar";
6090 string message = "123456789012345678901234567890123456";
6091 auto params = AuthorizationSetBuilder()
6092 .BlockMode(BlockMode::GCM)
6093 .Padding(PaddingMode::NONE)
6094 .Authorization(TAG_MAC_LENGTH, 128);
6095
Selene Huang31ab4042020-04-29 04:22:39 -07006096 // Encrypt
6097 AuthorizationSet begin_out_params;
6098 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6099 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006100 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006101
6102 AuthorizationSet finish_out_params;
6103 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006104 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6105 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006106
6107 params = AuthorizationSetBuilder()
6108 .Authorizations(begin_out_params)
6109 .BlockMode(BlockMode::GCM)
6110 .Padding(PaddingMode::NONE)
6111 .Authorization(TAG_MAC_LENGTH, 96);
6112
6113 // Decrypt.
6114 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6115}
6116
6117/*
6118 * EncryptionOperationsTest.AesGcmCorruptKey
6119 *
6120 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6121 */
6122TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6123 const uint8_t nonce_bytes[] = {
6124 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6125 };
6126 string nonce = make_string(nonce_bytes);
6127 const uint8_t ciphertext_bytes[] = {
6128 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6129 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6130 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6131 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6132 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6133 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6134 };
6135 string ciphertext = make_string(ciphertext_bytes);
6136
6137 auto params = AuthorizationSetBuilder()
6138 .BlockMode(BlockMode::GCM)
6139 .Padding(PaddingMode::NONE)
6140 .Authorization(TAG_MAC_LENGTH, 128)
6141 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6142
6143 auto import_params = AuthorizationSetBuilder()
6144 .Authorization(TAG_NO_AUTH_REQUIRED)
6145 .AesEncryptionKey(128)
6146 .BlockMode(BlockMode::GCM)
6147 .Padding(PaddingMode::NONE)
6148 .Authorization(TAG_CALLER_NONCE)
6149 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6150
6151 // Import correct key and decrypt
6152 const uint8_t key_bytes[] = {
6153 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6154 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6155 };
6156 string key = make_string(key_bytes);
6157 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6158 string plaintext = DecryptMessage(ciphertext, params);
6159 CheckedDeleteKey();
6160
6161 // Corrupt key and attempt to decrypt
6162 key[0] = 0;
6163 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6164 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6165 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6166 CheckedDeleteKey();
6167}
6168
6169/*
6170 * EncryptionOperationsTest.AesGcmAadNoData
6171 *
6172 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6173 * encrypt.
6174 */
6175TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6176 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6177 .Authorization(TAG_NO_AUTH_REQUIRED)
6178 .AesEncryptionKey(128)
6179 .BlockMode(BlockMode::GCM)
6180 .Padding(PaddingMode::NONE)
6181 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6182
6183 string aad = "1234567890123456";
6184 auto params = AuthorizationSetBuilder()
6185 .BlockMode(BlockMode::GCM)
6186 .Padding(PaddingMode::NONE)
6187 .Authorization(TAG_MAC_LENGTH, 128);
6188
Selene Huang31ab4042020-04-29 04:22:39 -07006189 // Encrypt
6190 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006191 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006192 string ciphertext;
6193 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006194 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6195 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006196 EXPECT_TRUE(finish_out_params.empty());
6197
6198 // Grab nonce
6199 params.push_back(begin_out_params);
6200
6201 // Decrypt.
6202 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006203 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006204 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006205 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006206
6207 EXPECT_TRUE(finish_out_params.empty());
6208
6209 EXPECT_EQ("", plaintext);
6210}
6211
6212/*
6213 * EncryptionOperationsTest.AesGcmMultiPartAad
6214 *
6215 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6216 * chunks.
6217 */
6218TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6219 const size_t tag_bits = 128;
6220 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6221 .Authorization(TAG_NO_AUTH_REQUIRED)
6222 .AesEncryptionKey(128)
6223 .BlockMode(BlockMode::GCM)
6224 .Padding(PaddingMode::NONE)
6225 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6226
6227 string message = "123456789012345678901234567890123456";
6228 auto begin_params = AuthorizationSetBuilder()
6229 .BlockMode(BlockMode::GCM)
6230 .Padding(PaddingMode::NONE)
6231 .Authorization(TAG_MAC_LENGTH, tag_bits);
6232 AuthorizationSet begin_out_params;
6233
David Drysdale7fc26b92022-05-13 09:54:24 +01006234 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006235
6236 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006237 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6238 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006239 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006240 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6241 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006242
Selene Huang31ab4042020-04-29 04:22:39 -07006243 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006244 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006245
6246 // Grab nonce.
6247 begin_params.push_back(begin_out_params);
6248
6249 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01006250 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006251 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006252 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006253 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006254 EXPECT_EQ(message, plaintext);
6255}
6256
6257/*
6258 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6259 *
6260 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6261 */
6262TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6263 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6264 .Authorization(TAG_NO_AUTH_REQUIRED)
6265 .AesEncryptionKey(128)
6266 .BlockMode(BlockMode::GCM)
6267 .Padding(PaddingMode::NONE)
6268 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6269
6270 string message = "123456789012345678901234567890123456";
6271 auto begin_params = AuthorizationSetBuilder()
6272 .BlockMode(BlockMode::GCM)
6273 .Padding(PaddingMode::NONE)
6274 .Authorization(TAG_MAC_LENGTH, 128);
6275 AuthorizationSet begin_out_params;
6276
David Drysdale7fc26b92022-05-13 09:54:24 +01006277 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006278
Shawn Willden92d79c02021-02-19 07:31:55 -07006279 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006280 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006281 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6282 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006283
David Drysdaled2cc8c22021-04-15 13:29:45 +01006284 // The failure should have already cancelled the operation.
6285 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6286
Shawn Willden92d79c02021-02-19 07:31:55 -07006287 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006288}
6289
6290/*
6291 * EncryptionOperationsTest.AesGcmBadAad
6292 *
6293 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6294 */
6295TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6296 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6297 .Authorization(TAG_NO_AUTH_REQUIRED)
6298 .AesEncryptionKey(128)
6299 .BlockMode(BlockMode::GCM)
6300 .Padding(PaddingMode::NONE)
6301 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6302
6303 string message = "12345678901234567890123456789012";
6304 auto begin_params = AuthorizationSetBuilder()
6305 .BlockMode(BlockMode::GCM)
6306 .Padding(PaddingMode::NONE)
6307 .Authorization(TAG_MAC_LENGTH, 128);
6308
Selene Huang31ab4042020-04-29 04:22:39 -07006309 // Encrypt
6310 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006311 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006312 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006313 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006314 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006315
6316 // Grab nonce
6317 begin_params.push_back(begin_out_params);
6318
Selene Huang31ab4042020-04-29 04:22:39 -07006319 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006320 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006321 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006322 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006323 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006324}
6325
6326/*
6327 * EncryptionOperationsTest.AesGcmWrongNonce
6328 *
6329 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6330 */
6331TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6332 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6333 .Authorization(TAG_NO_AUTH_REQUIRED)
6334 .AesEncryptionKey(128)
6335 .BlockMode(BlockMode::GCM)
6336 .Padding(PaddingMode::NONE)
6337 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6338
6339 string message = "12345678901234567890123456789012";
6340 auto begin_params = AuthorizationSetBuilder()
6341 .BlockMode(BlockMode::GCM)
6342 .Padding(PaddingMode::NONE)
6343 .Authorization(TAG_MAC_LENGTH, 128);
6344
Selene Huang31ab4042020-04-29 04:22:39 -07006345 // Encrypt
6346 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006347 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006348 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006349 string ciphertext;
6350 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006351 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006352
6353 // Wrong nonce
6354 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6355
6356 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006357 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006358 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006359 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006360 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006361
6362 // With wrong nonce, should have gotten garbage plaintext (or none).
6363 EXPECT_NE(message, plaintext);
6364}
6365
6366/*
6367 * EncryptionOperationsTest.AesGcmCorruptTag
6368 *
6369 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6370 */
6371TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6372 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6373 .Authorization(TAG_NO_AUTH_REQUIRED)
6374 .AesEncryptionKey(128)
6375 .BlockMode(BlockMode::GCM)
6376 .Padding(PaddingMode::NONE)
6377 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6378
6379 string aad = "1234567890123456";
6380 string message = "123456789012345678901234567890123456";
6381
6382 auto params = AuthorizationSetBuilder()
6383 .BlockMode(BlockMode::GCM)
6384 .Padding(PaddingMode::NONE)
6385 .Authorization(TAG_MAC_LENGTH, 128);
6386
Selene Huang31ab4042020-04-29 04:22:39 -07006387 // Encrypt
6388 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006389 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006390 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006391 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006392 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006393
6394 // Corrupt tag
6395 ++(*ciphertext.rbegin());
6396
6397 // Grab nonce
6398 params.push_back(begin_out_params);
6399
6400 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006401 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006402 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006403 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006404 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006405}
6406
6407/*
6408 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
6409 *
6410 * Verifies that 3DES is basically functional.
6411 */
6412TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
6413 auto auths = AuthorizationSetBuilder()
6414 .TripleDesEncryptionKey(168)
6415 .BlockMode(BlockMode::ECB)
6416 .Authorization(TAG_NO_AUTH_REQUIRED)
6417 .Padding(PaddingMode::NONE);
6418
6419 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
6420 // Two-block message.
6421 string message = "1234567890123456";
6422 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6423 string ciphertext1 = EncryptMessage(message, inParams);
6424 EXPECT_EQ(message.size(), ciphertext1.size());
6425
6426 string ciphertext2 = EncryptMessage(string(message), inParams);
6427 EXPECT_EQ(message.size(), ciphertext2.size());
6428
6429 // ECB is deterministic.
6430 EXPECT_EQ(ciphertext1, ciphertext2);
6431
6432 string plaintext = DecryptMessage(ciphertext1, inParams);
6433 EXPECT_EQ(message, plaintext);
6434}
6435
6436/*
6437 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
6438 *
6439 * Verifies that CBC keys reject ECB usage.
6440 */
6441TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
6442 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6443 .TripleDesEncryptionKey(168)
6444 .BlockMode(BlockMode::CBC)
6445 .Authorization(TAG_NO_AUTH_REQUIRED)
6446 .Padding(PaddingMode::NONE)));
6447
6448 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6449 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
6450}
6451
6452/*
6453 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
6454 *
6455 * Tests ECB mode with PKCS#7 padding, various message sizes.
6456 */
6457TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
6458 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6459 .TripleDesEncryptionKey(168)
6460 .BlockMode(BlockMode::ECB)
6461 .Authorization(TAG_NO_AUTH_REQUIRED)
6462 .Padding(PaddingMode::PKCS7)));
6463
6464 for (size_t i = 0; i < 32; ++i) {
6465 string message(i, 'a');
6466 auto inParams =
6467 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6468 string ciphertext = EncryptMessage(message, inParams);
6469 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6470 string plaintext = DecryptMessage(ciphertext, inParams);
6471 EXPECT_EQ(message, plaintext);
6472 }
6473}
6474
6475/*
6476 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
6477 *
6478 * Verifies that keys configured for no padding reject PKCS7 padding
6479 */
6480TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
6481 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6482 .TripleDesEncryptionKey(168)
6483 .BlockMode(BlockMode::ECB)
6484 .Authorization(TAG_NO_AUTH_REQUIRED)
6485 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00006486 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6487 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07006488}
6489
6490/*
6491 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
6492 *
6493 * Verifies that corrupted padding is detected.
6494 */
6495TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
6496 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6497 .TripleDesEncryptionKey(168)
6498 .BlockMode(BlockMode::ECB)
6499 .Authorization(TAG_NO_AUTH_REQUIRED)
6500 .Padding(PaddingMode::PKCS7)));
6501
6502 string message = "a";
6503 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
6504 EXPECT_EQ(8U, ciphertext.size());
6505 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006506
6507 AuthorizationSetBuilder begin_params;
6508 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
6509 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07006510
6511 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
6512 ++ciphertext[ciphertext.size() / 2];
6513
David Drysdale7fc26b92022-05-13 09:54:24 +01006514 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07006515 string plaintext;
6516 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6517 ErrorCode error = Finish(&plaintext);
6518 if (error == ErrorCode::INVALID_ARGUMENT) {
6519 // This is the expected error, we can exit the test now.
6520 return;
6521 } else {
6522 // Very small chance we got valid decryption, so try again.
6523 ASSERT_EQ(error, ErrorCode::OK);
6524 }
6525 }
6526 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006527}
6528
6529struct TripleDesTestVector {
6530 const char* name;
6531 const KeyPurpose purpose;
6532 const BlockMode block_mode;
6533 const PaddingMode padding_mode;
6534 const char* key;
6535 const char* iv;
6536 const char* input;
6537 const char* output;
6538};
6539
6540// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
6541// of the NIST vectors are multiples of the block size.
6542static const TripleDesTestVector kTripleDesTestVectors[] = {
6543 {
6544 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6545 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
6546 "", // IV
6547 "329d86bdf1bc5af4", // input
6548 "d946c2756d78633f", // output
6549 },
6550 {
6551 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6552 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
6553 "", // IV
6554 "6b1540781b01ce1997adae102dbf3c5b", // input
6555 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
6556 },
6557 {
6558 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6559 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
6560 "", // IV
6561 "6daad94ce08acfe7", // input
6562 "660e7d32dcc90e79", // output
6563 },
6564 {
6565 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6566 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
6567 "", // IV
6568 "e9653a0a1f05d31b9acd12d73aa9879d", // input
6569 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
6570 },
6571 {
6572 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6573 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
6574 "43f791134c5647ba", // IV
6575 "dcc153cef81d6f24", // input
6576 "92538bd8af18d3ba", // output
6577 },
6578 {
6579 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6580 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6581 "c2e999cb6249023c", // IV
6582 "c689aee38a301bb316da75db36f110b5", // input
6583 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
6584 },
6585 {
6586 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
6587 PaddingMode::PKCS7,
6588 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6589 "c2e999cb6249023c", // IV
6590 "c689aee38a301bb316da75db36f110b500", // input
6591 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
6592 },
6593 {
6594 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
6595 PaddingMode::PKCS7,
6596 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6597 "c2e999cb6249023c", // IV
6598 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
6599 "c689aee38a301bb316da75db36f110b500", // output
6600 },
6601 {
6602 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6603 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
6604 "41746c7e442d3681", // IV
6605 "c53a7b0ec40600fe", // input
6606 "d4f00eb455de1034", // output
6607 },
6608 {
6609 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6610 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
6611 "3982bc02c3727d45", // IV
6612 "6006f10adef52991fcc777a1238bbb65", // input
6613 "edae09288e9e3bc05746d872b48e3b29", // output
6614 },
6615};
6616
6617/*
6618 * EncryptionOperationsTest.TripleDesTestVector
6619 *
6620 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
6621 */
6622TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
6623 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
6624 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
6625 SCOPED_TRACE(test->name);
6626 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
6627 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
6628 hex2str(test->output));
6629 }
6630}
6631
6632/*
6633 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
6634 *
6635 * Validates CBC mode functionality.
6636 */
6637TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
6638 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6639 .TripleDesEncryptionKey(168)
6640 .BlockMode(BlockMode::CBC)
6641 .Authorization(TAG_NO_AUTH_REQUIRED)
6642 .Padding(PaddingMode::NONE)));
6643
6644 ASSERT_GT(key_blob_.size(), 0U);
6645
Brian J Murray734c8412022-01-13 14:55:30 -08006646 // Four-block message.
6647 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07006648 vector<uint8_t> iv1;
6649 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
6650 EXPECT_EQ(message.size(), ciphertext1.size());
6651
6652 vector<uint8_t> iv2;
6653 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
6654 EXPECT_EQ(message.size(), ciphertext2.size());
6655
6656 // IVs should be random, so ciphertexts should differ.
6657 EXPECT_NE(iv1, iv2);
6658 EXPECT_NE(ciphertext1, ciphertext2);
6659
6660 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
6661 EXPECT_EQ(message, plaintext);
6662}
6663
6664/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006665 * EncryptionOperationsTest.TripleDesInvalidCallerIv
6666 *
6667 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
6668 */
6669TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
6670 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6671 .TripleDesEncryptionKey(168)
6672 .BlockMode(BlockMode::CBC)
6673 .Authorization(TAG_NO_AUTH_REQUIRED)
6674 .Authorization(TAG_CALLER_NONCE)
6675 .Padding(PaddingMode::NONE)));
6676 auto params = AuthorizationSetBuilder()
6677 .BlockMode(BlockMode::CBC)
6678 .Padding(PaddingMode::NONE)
6679 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
6680 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6681}
6682
6683/*
Selene Huang31ab4042020-04-29 04:22:39 -07006684 * EncryptionOperationsTest.TripleDesCallerIv
6685 *
6686 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
6687 */
6688TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
6689 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6690 .TripleDesEncryptionKey(168)
6691 .BlockMode(BlockMode::CBC)
6692 .Authorization(TAG_NO_AUTH_REQUIRED)
6693 .Authorization(TAG_CALLER_NONCE)
6694 .Padding(PaddingMode::NONE)));
6695 string message = "1234567890123456";
6696 vector<uint8_t> iv;
6697 // Don't specify IV, should get a random one.
6698 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6699 EXPECT_EQ(message.size(), ciphertext1.size());
6700 EXPECT_EQ(8U, iv.size());
6701
6702 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6703 EXPECT_EQ(message, plaintext);
6704
6705 // Now specify an IV, should also work.
6706 iv = AidlBuf("abcdefgh");
6707 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
6708
6709 // Decrypt with correct IV.
6710 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
6711 EXPECT_EQ(message, plaintext);
6712
6713 // Now try with wrong IV.
6714 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
6715 EXPECT_NE(message, plaintext);
6716}
6717
6718/*
6719 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
6720 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01006721 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07006722 */
6723TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
6724 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6725 .TripleDesEncryptionKey(168)
6726 .BlockMode(BlockMode::CBC)
6727 .Authorization(TAG_NO_AUTH_REQUIRED)
6728 .Padding(PaddingMode::NONE)));
6729
6730 string message = "12345678901234567890123456789012";
6731 vector<uint8_t> iv;
6732 // Don't specify nonce, should get a random one.
6733 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6734 EXPECT_EQ(message.size(), ciphertext1.size());
6735 EXPECT_EQ(8U, iv.size());
6736
6737 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6738 EXPECT_EQ(message, plaintext);
6739
6740 // Now specify a nonce, should fail.
6741 auto input_params = AuthorizationSetBuilder()
6742 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
6743 .BlockMode(BlockMode::CBC)
6744 .Padding(PaddingMode::NONE);
6745 AuthorizationSet output_params;
6746 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
6747 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6748}
6749
6750/*
6751 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
6752 *
6753 * Verifies that 3DES ECB-only keys do not allow CBC usage.
6754 */
6755TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
6756 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6757 .TripleDesEncryptionKey(168)
6758 .BlockMode(BlockMode::ECB)
6759 .Authorization(TAG_NO_AUTH_REQUIRED)
6760 .Padding(PaddingMode::NONE)));
6761 // Two-block message.
6762 string message = "1234567890123456";
6763 auto begin_params =
6764 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6765 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6766}
6767
6768/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006769 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07006770 *
6771 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
6772 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01006773TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
6774 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
6775 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6776 .TripleDesEncryptionKey(168)
6777 .BlockMode(blockMode)
6778 .Authorization(TAG_NO_AUTH_REQUIRED)
6779 .Padding(PaddingMode::NONE)));
6780 // Message is slightly shorter than two blocks.
6781 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07006782
David Drysdaled2cc8c22021-04-15 13:29:45 +01006783 auto begin_params =
6784 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
6785 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006786 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01006787 string ciphertext;
6788 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
6789
6790 CheckedDeleteKey();
6791 }
Selene Huang31ab4042020-04-29 04:22:39 -07006792}
6793
6794/*
6795 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
6796 *
6797 * Verifies that PKCS7 padding works correctly in CBC mode.
6798 */
6799TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
6800 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6801 .TripleDesEncryptionKey(168)
6802 .BlockMode(BlockMode::CBC)
6803 .Authorization(TAG_NO_AUTH_REQUIRED)
6804 .Padding(PaddingMode::PKCS7)));
6805
6806 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08006807 for (size_t i = 0; i <= 32; i++) {
6808 SCOPED_TRACE(testing::Message() << "i = " << i);
6809 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
6810 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07006811 vector<uint8_t> iv;
6812 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6813 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6814 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
6815 EXPECT_EQ(message, plaintext);
6816 }
6817}
6818
6819/*
6820 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
6821 *
6822 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
6823 */
6824TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
6825 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6826 .TripleDesEncryptionKey(168)
6827 .BlockMode(BlockMode::CBC)
6828 .Authorization(TAG_NO_AUTH_REQUIRED)
6829 .Padding(PaddingMode::NONE)));
6830
6831 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08006832 for (size_t i = 0; i <= 32; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07006833 auto begin_params =
6834 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
6835 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6836 }
6837}
6838
6839/*
6840 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
6841 *
6842 * Verifies that corrupted PKCS7 padding is rejected during decryption.
6843 */
6844TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
6845 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6846 .TripleDesEncryptionKey(168)
6847 .BlockMode(BlockMode::CBC)
6848 .Authorization(TAG_NO_AUTH_REQUIRED)
6849 .Padding(PaddingMode::PKCS7)));
6850
6851 string message = "a";
6852 vector<uint8_t> iv;
6853 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6854 EXPECT_EQ(8U, ciphertext.size());
6855 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006856
6857 auto begin_params = AuthorizationSetBuilder()
6858 .BlockMode(BlockMode::CBC)
6859 .Padding(PaddingMode::PKCS7)
6860 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07006861
6862 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08006863 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07006864 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01006865 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07006866 string plaintext;
6867 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6868 ErrorCode error = Finish(&plaintext);
6869 if (error == ErrorCode::INVALID_ARGUMENT) {
6870 // This is the expected error, we can exit the test now.
6871 return;
6872 } else {
6873 // Very small chance we got valid decryption, so try again.
6874 ASSERT_EQ(error, ErrorCode::OK);
6875 }
6876 }
6877 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006878}
6879
6880/*
6881 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
6882 *
6883 * Verifies that 3DES CBC works with many different input sizes.
6884 */
6885TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
6886 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6887 .TripleDesEncryptionKey(168)
6888 .BlockMode(BlockMode::CBC)
6889 .Authorization(TAG_NO_AUTH_REQUIRED)
6890 .Padding(PaddingMode::NONE)));
6891
6892 int increment = 7;
6893 string message(240, 'a');
6894 AuthorizationSet input_params =
6895 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6896 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006897 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006898
6899 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07006900 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006901 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006902 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
6903 EXPECT_EQ(message.size(), ciphertext.size());
6904
6905 // Move TAG_NONCE into input_params
6906 input_params = output_params;
6907 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
6908 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
6909 output_params.Clear();
6910
David Drysdale7fc26b92022-05-13 09:54:24 +01006911 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006912 string plaintext;
6913 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006914 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006915 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
6916 EXPECT_EQ(ciphertext.size(), plaintext.size());
6917 EXPECT_EQ(message, plaintext);
6918}
6919
6920INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
6921
6922typedef KeyMintAidlTestBase MaxOperationsTest;
6923
6924/*
6925 * MaxOperationsTest.TestLimitAes
6926 *
6927 * Verifies that the max uses per boot tag works correctly with AES keys.
6928 */
6929TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006930 if (SecLevel() == SecurityLevel::STRONGBOX) {
6931 GTEST_SKIP() << "Test not applicable to StrongBox device";
6932 }
Selene Huang31ab4042020-04-29 04:22:39 -07006933
6934 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6935 .Authorization(TAG_NO_AUTH_REQUIRED)
6936 .AesEncryptionKey(128)
6937 .EcbMode()
6938 .Padding(PaddingMode::NONE)
6939 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
6940
6941 string message = "1234567890123456";
6942
6943 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6944
6945 EncryptMessage(message, params);
6946 EncryptMessage(message, params);
6947 EncryptMessage(message, params);
6948
6949 // Fourth time should fail.
6950 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
6951}
6952
6953/*
Qi Wud22ec842020-11-26 13:27:53 +08006954 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07006955 *
6956 * Verifies that the max uses per boot tag works correctly with RSA keys.
6957 */
6958TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006959 if (SecLevel() == SecurityLevel::STRONGBOX) {
6960 GTEST_SKIP() << "Test not applicable to StrongBox device";
6961 }
Selene Huang31ab4042020-04-29 04:22:39 -07006962
6963 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6964 .Authorization(TAG_NO_AUTH_REQUIRED)
6965 .RsaSigningKey(1024, 65537)
6966 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006967 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
6968 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006969
6970 string message = "1234567890123456";
6971
6972 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6973
6974 SignMessage(message, params);
6975 SignMessage(message, params);
6976 SignMessage(message, params);
6977
6978 // Fourth time should fail.
6979 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
6980}
6981
6982INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
6983
Qi Wud22ec842020-11-26 13:27:53 +08006984typedef KeyMintAidlTestBase UsageCountLimitTest;
6985
6986/*
Qi Wubeefae42021-01-28 23:16:37 +08006987 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006988 *
Qi Wubeefae42021-01-28 23:16:37 +08006989 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006990 */
Qi Wubeefae42021-01-28 23:16:37 +08006991TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006992 if (SecLevel() == SecurityLevel::STRONGBOX) {
6993 GTEST_SKIP() << "Test not applicable to StrongBox device";
6994 }
Qi Wud22ec842020-11-26 13:27:53 +08006995
6996 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6997 .Authorization(TAG_NO_AUTH_REQUIRED)
6998 .AesEncryptionKey(128)
6999 .EcbMode()
7000 .Padding(PaddingMode::NONE)
7001 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7002
7003 // Check the usage count limit tag appears in the authorizations.
7004 AuthorizationSet auths;
7005 for (auto& entry : key_characteristics_) {
7006 auths.push_back(AuthorizationSet(entry.authorizations));
7007 }
7008 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7009 << "key usage count limit " << 1U << " missing";
7010
7011 string message = "1234567890123456";
7012 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7013
Qi Wubeefae42021-01-28 23:16:37 +08007014 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7015 AuthorizationSet keystore_auths =
7016 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7017
Qi Wud22ec842020-11-26 13:27:53 +08007018 // First usage of AES key should work.
7019 EncryptMessage(message, params);
7020
Qi Wud22ec842020-11-26 13:27:53 +08007021 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7022 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7023 // must be invalidated from secure storage (such as RPMB partition).
7024 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7025 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007026 // Usage count limit tag is enforced by keystore, keymint does nothing.
7027 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007028 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007029 }
7030}
7031
7032/*
Qi Wubeefae42021-01-28 23:16:37 +08007033 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007034 *
Qi Wubeefae42021-01-28 23:16:37 +08007035 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007036 */
Qi Wubeefae42021-01-28 23:16:37 +08007037TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007038 if (SecLevel() == SecurityLevel::STRONGBOX) {
7039 GTEST_SKIP() << "Test not applicable to StrongBox device";
7040 }
Qi Wubeefae42021-01-28 23:16:37 +08007041
7042 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7043 .Authorization(TAG_NO_AUTH_REQUIRED)
7044 .AesEncryptionKey(128)
7045 .EcbMode()
7046 .Padding(PaddingMode::NONE)
7047 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7048
7049 // Check the usage count limit tag appears in the authorizations.
7050 AuthorizationSet auths;
7051 for (auto& entry : key_characteristics_) {
7052 auths.push_back(AuthorizationSet(entry.authorizations));
7053 }
7054 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7055 << "key usage count limit " << 3U << " missing";
7056
7057 string message = "1234567890123456";
7058 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7059
7060 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7061 AuthorizationSet keystore_auths =
7062 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7063
7064 EncryptMessage(message, params);
7065 EncryptMessage(message, params);
7066 EncryptMessage(message, params);
7067
7068 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7069 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7070 // must be invalidated from secure storage (such as RPMB partition).
7071 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7072 } else {
7073 // Usage count limit tag is enforced by keystore, keymint does nothing.
7074 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007075 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007076 }
7077}
7078
7079/*
7080 * UsageCountLimitTest.TestSingleUseRsa
7081 *
7082 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7083 */
7084TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007085 if (SecLevel() == SecurityLevel::STRONGBOX) {
7086 GTEST_SKIP() << "Test not applicable to StrongBox device";
7087 }
Qi Wud22ec842020-11-26 13:27:53 +08007088
7089 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7090 .Authorization(TAG_NO_AUTH_REQUIRED)
7091 .RsaSigningKey(1024, 65537)
7092 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007093 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7094 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007095
7096 // Check the usage count limit tag appears in the authorizations.
7097 AuthorizationSet auths;
7098 for (auto& entry : key_characteristics_) {
7099 auths.push_back(AuthorizationSet(entry.authorizations));
7100 }
7101 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7102 << "key usage count limit " << 1U << " missing";
7103
7104 string message = "1234567890123456";
7105 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7106
Qi Wubeefae42021-01-28 23:16:37 +08007107 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7108 AuthorizationSet keystore_auths =
7109 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7110
Qi Wud22ec842020-11-26 13:27:53 +08007111 // First usage of RSA key should work.
7112 SignMessage(message, params);
7113
Qi Wud22ec842020-11-26 13:27:53 +08007114 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7115 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7116 // must be invalidated from secure storage (such as RPMB partition).
7117 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7118 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007119 // Usage count limit tag is enforced by keystore, keymint does nothing.
7120 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007121 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007122 }
7123}
7124
7125/*
7126 * UsageCountLimitTest.TestLimitUseRsa
7127 *
7128 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7129 */
7130TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007131 if (SecLevel() == SecurityLevel::STRONGBOX) {
7132 GTEST_SKIP() << "Test not applicable to StrongBox device";
7133 }
Qi Wubeefae42021-01-28 23:16:37 +08007134
7135 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7136 .Authorization(TAG_NO_AUTH_REQUIRED)
7137 .RsaSigningKey(1024, 65537)
7138 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007139 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7140 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007141
7142 // Check the usage count limit tag appears in the authorizations.
7143 AuthorizationSet auths;
7144 for (auto& entry : key_characteristics_) {
7145 auths.push_back(AuthorizationSet(entry.authorizations));
7146 }
7147 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7148 << "key usage count limit " << 3U << " missing";
7149
7150 string message = "1234567890123456";
7151 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7152
7153 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7154 AuthorizationSet keystore_auths =
7155 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7156
7157 SignMessage(message, params);
7158 SignMessage(message, params);
7159 SignMessage(message, params);
7160
7161 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7162 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7163 // must be invalidated from secure storage (such as RPMB partition).
7164 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7165 } else {
7166 // Usage count limit tag is enforced by keystore, keymint does nothing.
7167 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007168 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007169 }
7170}
7171
Qi Wu8e727f72021-02-11 02:49:33 +08007172/*
7173 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7174 *
7175 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7176 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7177 * in hardware.
7178 */
7179TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01007180 if (SecLevel() == SecurityLevel::STRONGBOX) {
7181 GTEST_SKIP() << "Test not applicable to StrongBox device";
7182 }
Qi Wu8e727f72021-02-11 02:49:33 +08007183
7184 auto error = GenerateKey(AuthorizationSetBuilder()
7185 .RsaSigningKey(2048, 65537)
7186 .Digest(Digest::NONE)
7187 .Padding(PaddingMode::NONE)
7188 .Authorization(TAG_NO_AUTH_REQUIRED)
7189 .Authorization(TAG_ROLLBACK_RESISTANCE)
7190 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007191 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7192 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007193 }
David Drysdale513bf122021-10-06 11:53:13 +01007194
7195 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7196 ASSERT_EQ(ErrorCode::OK, error);
7197 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7198 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7199 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7200
7201 // The KeyMint should also enforce single use key in hardware when it supports rollback
7202 // resistance.
7203 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7204 .Authorization(TAG_NO_AUTH_REQUIRED)
7205 .RsaSigningKey(1024, 65537)
7206 .NoDigestOrPadding()
7207 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7208 .SetDefaultValidity()));
7209
7210 // Check the usage count limit tag appears in the hardware authorizations.
7211 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7212 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7213 << "key usage count limit " << 1U << " missing";
7214
7215 string message = "1234567890123456";
7216 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7217
7218 // First usage of RSA key should work.
7219 SignMessage(message, params);
7220
7221 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7222 // must be invalidated from secure storage (such as RPMB partition).
7223 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007224}
7225
Qi Wud22ec842020-11-26 13:27:53 +08007226INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7227
David Drysdale7de9feb2021-03-05 14:56:19 +00007228typedef KeyMintAidlTestBase GetHardwareInfoTest;
7229
7230TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7231 // Retrieving hardware info should give the same result each time.
7232 KeyMintHardwareInfo info;
7233 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7234 KeyMintHardwareInfo info2;
7235 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7236 EXPECT_EQ(info, info2);
7237}
7238
7239INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7240
Selene Huang31ab4042020-04-29 04:22:39 -07007241typedef KeyMintAidlTestBase AddEntropyTest;
7242
7243/*
7244 * AddEntropyTest.AddEntropy
7245 *
7246 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7247 * is actually added.
7248 */
7249TEST_P(AddEntropyTest, AddEntropy) {
7250 string data = "foo";
7251 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7252}
7253
7254/*
7255 * AddEntropyTest.AddEmptyEntropy
7256 *
7257 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7258 */
7259TEST_P(AddEntropyTest, AddEmptyEntropy) {
7260 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7261}
7262
7263/*
7264 * AddEntropyTest.AddLargeEntropy
7265 *
7266 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7267 */
7268TEST_P(AddEntropyTest, AddLargeEntropy) {
7269 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7270}
7271
David Drysdalebb3d85e2021-04-13 11:15:51 +01007272/*
7273 * AddEntropyTest.AddTooLargeEntropy
7274 *
7275 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7276 */
7277TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7278 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7279 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7280}
7281
Selene Huang31ab4042020-04-29 04:22:39 -07007282INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7283
Selene Huang31ab4042020-04-29 04:22:39 -07007284typedef KeyMintAidlTestBase KeyDeletionTest;
7285
7286/**
7287 * KeyDeletionTest.DeleteKey
7288 *
7289 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7290 * valid key blob.
7291 */
7292TEST_P(KeyDeletionTest, DeleteKey) {
7293 auto error = GenerateKey(AuthorizationSetBuilder()
7294 .RsaSigningKey(2048, 65537)
7295 .Digest(Digest::NONE)
7296 .Padding(PaddingMode::NONE)
7297 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007298 .Authorization(TAG_ROLLBACK_RESISTANCE)
7299 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007300 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7301 GTEST_SKIP() << "Rollback resistance not supported";
7302 }
Selene Huang31ab4042020-04-29 04:22:39 -07007303
7304 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007305 ASSERT_EQ(ErrorCode::OK, error);
7306 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7307 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007308
David Drysdale513bf122021-10-06 11:53:13 +01007309 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007310
David Drysdale513bf122021-10-06 11:53:13 +01007311 string message = "12345678901234567890123456789012";
7312 AuthorizationSet begin_out_params;
7313 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7314 Begin(KeyPurpose::SIGN, key_blob_,
7315 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7316 &begin_out_params));
7317 AbortIfNeeded();
7318 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007319}
7320
7321/**
7322 * KeyDeletionTest.DeleteInvalidKey
7323 *
7324 * This test checks that the HAL excepts invalid key blobs..
7325 */
7326TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7327 // Generate key just to check if rollback protection is implemented
7328 auto error = GenerateKey(AuthorizationSetBuilder()
7329 .RsaSigningKey(2048, 65537)
7330 .Digest(Digest::NONE)
7331 .Padding(PaddingMode::NONE)
7332 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007333 .Authorization(TAG_ROLLBACK_RESISTANCE)
7334 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007335 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7336 GTEST_SKIP() << "Rollback resistance not supported";
7337 }
Selene Huang31ab4042020-04-29 04:22:39 -07007338
7339 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007340 ASSERT_EQ(ErrorCode::OK, error);
7341 AuthorizationSet enforced(SecLevelAuthorizations());
7342 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007343
David Drysdale513bf122021-10-06 11:53:13 +01007344 // Delete the key we don't care about the result at this point.
7345 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007346
David Drysdale513bf122021-10-06 11:53:13 +01007347 // Now create an invalid key blob and delete it.
7348 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007349
David Drysdale513bf122021-10-06 11:53:13 +01007350 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007351}
7352
7353/**
7354 * KeyDeletionTest.DeleteAllKeys
7355 *
7356 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7357 *
7358 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7359 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7360 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7361 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7362 * credentials stored in Keystore/Keymint.
7363 */
7364TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007365 if (!arm_deleteAllKeys) {
7366 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7367 return;
7368 }
Selene Huang31ab4042020-04-29 04:22:39 -07007369 auto error = GenerateKey(AuthorizationSetBuilder()
7370 .RsaSigningKey(2048, 65537)
7371 .Digest(Digest::NONE)
7372 .Padding(PaddingMode::NONE)
7373 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007374 .Authorization(TAG_ROLLBACK_RESISTANCE)
7375 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007376 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7377 GTEST_SKIP() << "Rollback resistance not supported";
7378 }
Selene Huang31ab4042020-04-29 04:22:39 -07007379
7380 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007381 ASSERT_EQ(ErrorCode::OK, error);
7382 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7383 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007384
David Drysdale513bf122021-10-06 11:53:13 +01007385 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007386
David Drysdale513bf122021-10-06 11:53:13 +01007387 string message = "12345678901234567890123456789012";
7388 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07007389
David Drysdale513bf122021-10-06 11:53:13 +01007390 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7391 Begin(KeyPurpose::SIGN, key_blob_,
7392 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7393 &begin_out_params));
7394 AbortIfNeeded();
7395 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007396}
7397
7398INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
7399
David Drysdaled2cc8c22021-04-15 13:29:45 +01007400typedef KeyMintAidlTestBase KeyUpgradeTest;
7401
7402/**
7403 * KeyUpgradeTest.UpgradeInvalidKey
7404 *
7405 * This test checks that the HAL excepts invalid key blobs..
7406 */
7407TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
7408 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
7409
7410 std::vector<uint8_t> new_blob;
7411 Status result = keymint_->upgradeKey(key_blob,
7412 AuthorizationSetBuilder()
7413 .Authorization(TAG_APPLICATION_ID, "clientid")
7414 .Authorization(TAG_APPLICATION_DATA, "appdata")
7415 .vector_data(),
7416 &new_blob);
7417 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
7418}
7419
7420INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
7421
Selene Huang31ab4042020-04-29 04:22:39 -07007422using UpgradeKeyTest = KeyMintAidlTestBase;
7423
7424/*
7425 * UpgradeKeyTest.UpgradeKey
7426 *
7427 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
7428 */
7429TEST_P(UpgradeKeyTest, UpgradeKey) {
7430 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7431 .AesEncryptionKey(128)
7432 .Padding(PaddingMode::NONE)
7433 .Authorization(TAG_NO_AUTH_REQUIRED)));
7434
7435 auto result = UpgradeKey(key_blob_);
7436
7437 // Key doesn't need upgrading. Should get okay, but no new key blob.
7438 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
7439}
7440
7441INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
7442
7443using ClearOperationsTest = KeyMintAidlTestBase;
7444
7445/*
7446 * ClearSlotsTest.TooManyOperations
7447 *
7448 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
7449 * operations are started without being finished or aborted. Also verifies
7450 * that aborting the operations clears the operations.
7451 *
7452 */
7453TEST_P(ClearOperationsTest, TooManyOperations) {
7454 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7455 .Authorization(TAG_NO_AUTH_REQUIRED)
7456 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08007457 .Padding(PaddingMode::NONE)
7458 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007459
7460 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
7461 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08007462 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07007463 AuthorizationSet out_params;
7464 ErrorCode result;
7465 size_t i;
7466
7467 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00007468 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07007469 if (ErrorCode::OK != result) {
7470 break;
7471 }
7472 }
7473 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
7474 // Try again just in case there's a weird overflow bug
7475 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00007476 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007477 for (size_t j = 0; j < i; j++) {
7478 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
7479 << "Aboort failed for i = " << j << std::endl;
7480 }
David Drysdale7fc26b92022-05-13 09:54:24 +01007481 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007482 AbortIfNeeded();
7483}
7484
7485INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
7486
7487typedef KeyMintAidlTestBase TransportLimitTest;
7488
7489/*
David Drysdale7de9feb2021-03-05 14:56:19 +00007490 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07007491 *
7492 * Verifies that passing input data to finish succeeds as expected.
7493 */
7494TEST_P(TransportLimitTest, LargeFinishInput) {
7495 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7496 .Authorization(TAG_NO_AUTH_REQUIRED)
7497 .AesEncryptionKey(128)
7498 .BlockMode(BlockMode::ECB)
7499 .Padding(PaddingMode::NONE)));
7500
7501 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
7502 auto cipher_params =
7503 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7504
7505 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007506 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007507
7508 string plain_message = std::string(1 << msg_size, 'x');
7509 string encrypted_message;
7510 auto rc = Finish(plain_message, &encrypted_message);
7511
7512 EXPECT_EQ(ErrorCode::OK, rc);
7513 EXPECT_EQ(plain_message.size(), encrypted_message.size())
7514 << "Encrypt finish returned OK, but did not consume all of the given input";
7515 cipher_params.push_back(out_params);
7516
David Drysdale7fc26b92022-05-13 09:54:24 +01007517 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007518
7519 string decrypted_message;
7520 rc = Finish(encrypted_message, &decrypted_message);
7521 EXPECT_EQ(ErrorCode::OK, rc);
7522 EXPECT_EQ(plain_message.size(), decrypted_message.size())
7523 << "Decrypt finish returned OK, did not consume all of the given input";
7524 }
7525}
7526
7527INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
7528
Seth Moored79a0ec2021-12-13 20:03:33 +00007529static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05007530 switch (curve) {
7531 case EcCurve::P_224:
7532 return NID_secp224r1;
7533 case EcCurve::P_256:
7534 return NID_X9_62_prime256v1;
7535 case EcCurve::P_384:
7536 return NID_secp384r1;
7537 case EcCurve::P_521:
7538 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00007539 case EcCurve::CURVE_25519:
7540 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05007541 }
7542}
7543
David Drysdale42fe1892021-10-14 14:43:46 +01007544class KeyAgreementTest : public KeyMintAidlTestBase {
7545 protected:
7546 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
7547 std::vector<uint8_t>* localPublicKey) {
7548 // Generate EC key locally (with access to private key material)
7549 if (localCurve == EcCurve::CURVE_25519) {
7550 uint8_t privKeyData[32];
7551 uint8_t pubKeyData[32];
7552 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01007553 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
7554 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
7555 } else {
7556 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
7557 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
7558 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
7559 ASSERT_NE(group, nullptr);
7560 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
7561 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
7562 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
7563 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01007564 }
David Drysdalea410b772022-05-09 16:44:13 +01007565
7566 // Get encoded form of the public part of the locally generated key...
7567 unsigned char* p = nullptr;
7568 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
7569 ASSERT_GT(localPublicKeySize, 0);
7570 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
7571 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
7572 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01007573 }
7574
7575 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
7576 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00007577 auto builder = AuthorizationSetBuilder()
7578 .Authorization(TAG_NO_AUTH_REQUIRED)
7579 .Authorization(TAG_EC_CURVE, curve)
7580 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7581 .Authorization(TAG_ALGORITHM, Algorithm::EC)
7582 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
7583 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
7584 .SetDefaultValidity();
7585 ErrorCode result = GenerateKey(builder);
7586
7587 if (SecLevel() == SecurityLevel::STRONGBOX) {
7588 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
7589 result = GenerateKeyWithSelfSignedAttestKey(
7590 AuthorizationSetBuilder()
7591 .EcdsaKey(EcCurve::P_256)
7592 .AttestKey()
7593 .SetDefaultValidity(), /* attest key params */
7594 builder, &key_blob_, &key_characteristics_, &cert_chain_);
7595 }
7596 }
David Drysdale42fe1892021-10-14 14:43:46 +01007597 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
7598 ASSERT_GT(cert_chain_.size(), 0);
7599 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7600 ASSERT_NE(kmKeyCert, nullptr);
7601 // Check that keyAgreement (bit 4) is set in KeyUsage
7602 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
7603 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
7604 ASSERT_NE(*kmPubKey, nullptr);
7605 if (dump_Attestations) {
7606 for (size_t n = 0; n < cert_chain_.size(); n++) {
7607 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
7608 }
7609 }
7610 }
7611
7612 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
7613 const std::vector<uint8_t>& localPublicKey) {
7614 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7615 string ZabFromKeyMintStr;
7616 ASSERT_EQ(ErrorCode::OK,
7617 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
7618 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
7619 vector<uint8_t> ZabFromTest;
7620
7621 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
7622 size_t kmPubKeySize = 32;
7623 uint8_t kmPubKeyData[32];
7624 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7625 ASSERT_EQ(kmPubKeySize, 32);
7626
7627 uint8_t localPrivKeyData[32];
7628 size_t localPrivKeySize = 32;
7629 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
7630 &localPrivKeySize));
7631 ASSERT_EQ(localPrivKeySize, 32);
7632
7633 uint8_t sharedKey[32];
7634 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
7635 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
7636 } else {
7637 // Perform local ECDH between the two keys so we can check if we get the same Zab..
7638 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
7639 ASSERT_NE(ctx, nullptr);
7640 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
7641 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
7642 size_t ZabFromTestLen = 0;
7643 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
7644 ZabFromTest.resize(ZabFromTestLen);
7645 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
7646 }
7647 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
7648 }
7649};
7650
David Zeuthene0c40892021-01-08 12:54:11 -05007651/*
7652 * KeyAgreementTest.Ecdh
7653 *
David Drysdale42fe1892021-10-14 14:43:46 +01007654 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05007655 */
7656TEST_P(KeyAgreementTest, Ecdh) {
7657 // Because it's possible to use this API with keys on different curves, we
7658 // check all N^2 combinations where N is the number of supported
7659 // curves.
7660 //
7661 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
7662 // lot more curves we can be smart about things and just pick |otherCurve| so
7663 // it's not |curve| and that way we end up with only 2*N runs
7664 //
7665 for (auto curve : ValidCurves()) {
7666 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01007667 SCOPED_TRACE(testing::Message()
7668 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
7669
David Zeuthene0c40892021-01-08 12:54:11 -05007670 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007671 EVP_PKEY_Ptr localPrivKey;
7672 vector<uint8_t> localPublicKey;
7673 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007674
7675 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007676 EVP_PKEY_Ptr kmPubKey;
7677 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007678
7679 // Now that we have the two keys, we ask KeyMint to perform ECDH...
7680 if (curve != localCurve) {
7681 // If the keys are using different curves KeyMint should fail with
7682 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01007683 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05007684 string ZabFromKeyMintStr;
7685 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01007686 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05007687 &ZabFromKeyMintStr));
7688
7689 } else {
7690 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01007691 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007692 }
7693
7694 CheckedDeleteKey();
7695 }
7696 }
7697}
7698
David Drysdale42fe1892021-10-14 14:43:46 +01007699/*
7700 * KeyAgreementTest.EcdhCurve25519
7701 *
7702 * Verifies that ECDH works for curve25519. This is also covered by the general
7703 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
7704 * KeyMint 1.0.
7705 */
7706TEST_P(KeyAgreementTest, EcdhCurve25519) {
7707 if (!Curve25519Supported()) {
7708 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7709 }
7710
7711 // Generate EC key in KeyMint (only access to public key material)
7712 EcCurve curve = EcCurve::CURVE_25519;
7713 EVP_PKEY_Ptr kmPubKey = nullptr;
7714 GenerateKeyMintEcKey(curve, &kmPubKey);
7715
7716 // Generate EC key on same curve locally (with access to private key material).
7717 EVP_PKEY_Ptr privKey;
7718 vector<uint8_t> encodedPublicKey;
7719 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7720
7721 // Agree on a key between local and KeyMint and check it.
7722 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7723
7724 CheckedDeleteKey();
7725}
7726
7727/*
7728 * KeyAgreementTest.EcdhCurve25519Imported
7729 *
7730 * Verifies that ECDH works for an imported curve25519 key.
7731 */
7732TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
7733 if (!Curve25519Supported()) {
7734 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7735 }
7736
7737 // Import x25519 key into KeyMint.
7738 EcCurve curve = EcCurve::CURVE_25519;
7739 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
7740 .Authorization(TAG_NO_AUTH_REQUIRED)
7741 .EcdsaKey(EcCurve::CURVE_25519)
7742 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7743 .SetDefaultValidity(),
7744 KeyFormat::PKCS8, x25519_pkcs8_key));
7745 ASSERT_GT(cert_chain_.size(), 0);
7746 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7747 ASSERT_NE(kmKeyCert, nullptr);
7748 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
7749 ASSERT_NE(kmPubKey.get(), nullptr);
7750
7751 // Expect the import to emit corresponding public key data.
7752 size_t kmPubKeySize = 32;
7753 uint8_t kmPubKeyData[32];
7754 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7755 ASSERT_EQ(kmPubKeySize, 32);
7756 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
7757 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
7758
7759 // Generate EC key on same curve locally (with access to private key material).
7760 EVP_PKEY_Ptr privKey;
7761 vector<uint8_t> encodedPublicKey;
7762 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7763
7764 // Agree on a key between local and KeyMint and check it.
7765 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7766
7767 CheckedDeleteKey();
7768}
7769
7770/*
7771 * KeyAgreementTest.EcdhCurve25519InvalidSize
7772 *
7773 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
7774 */
7775TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
7776 if (!Curve25519Supported()) {
7777 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7778 }
7779
7780 // Generate EC key in KeyMint (only access to public key material)
7781 EcCurve curve = EcCurve::CURVE_25519;
7782 EVP_PKEY_Ptr kmPubKey = nullptr;
7783 GenerateKeyMintEcKey(curve, &kmPubKey);
7784
7785 // Generate EC key on same curve locally (with access to private key material).
7786 EVP_PKEY_Ptr privKey;
7787 vector<uint8_t> encodedPublicKey;
7788 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7789
7790 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7791 string ZabFromKeyMintStr;
7792 // Send in an incomplete public key.
7793 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
7794 &ZabFromKeyMintStr));
7795
7796 CheckedDeleteKey();
7797}
7798
7799/*
7800 * KeyAgreementTest.EcdhCurve25519Mismatch
7801 *
7802 * Verifies that ECDH fails between curve25519 and other curves.
7803 */
7804TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
7805 if (!Curve25519Supported()) {
7806 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7807 }
7808
7809 // Generate EC key in KeyMint (only access to public key material)
7810 EcCurve curve = EcCurve::CURVE_25519;
7811 EVP_PKEY_Ptr kmPubKey = nullptr;
7812 GenerateKeyMintEcKey(curve, &kmPubKey);
7813
7814 for (auto localCurve : ValidCurves()) {
7815 if (localCurve == curve) {
7816 continue;
7817 }
7818 // Generate EC key on a different curve locally (with access to private key material).
7819 EVP_PKEY_Ptr privKey;
7820 vector<uint8_t> encodedPublicKey;
7821 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
7822
David Drysdale7fc26b92022-05-13 09:54:24 +01007823 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01007824 string ZabFromKeyMintStr;
7825 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
7826 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
7827 &ZabFromKeyMintStr));
7828 }
7829
7830 CheckedDeleteKey();
7831}
7832
David Zeuthene0c40892021-01-08 12:54:11 -05007833INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
7834
David Drysdaled2cc8c22021-04-15 13:29:45 +01007835using DestroyAttestationIdsTest = KeyMintAidlTestBase;
7836
7837// This is a problematic test, as it can render the device under test permanently unusable.
7838// Re-enable and run at your own risk.
7839TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
7840 auto result = DestroyAttestationIds();
7841 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
7842}
7843
7844INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
7845
Shawn Willdend659c7c2021-02-19 14:51:51 -07007846using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007847
David Drysdaledb0dcf52021-05-18 11:43:31 +01007848/*
7849 * EarlyBootKeyTest.CreateEarlyBootKeys
7850 *
7851 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
7852 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007853TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01007854 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007855 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7856 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7857
David Drysdaleadfe6112021-05-27 12:00:53 +01007858 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
7859 ASSERT_GT(keyData.blob.size(), 0U);
7860 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7861 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7862 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007863 CheckedDeleteKey(&aesKeyData.blob);
7864 CheckedDeleteKey(&hmacKeyData.blob);
7865 CheckedDeleteKey(&rsaKeyData.blob);
7866 CheckedDeleteKey(&ecdsaKeyData.blob);
7867}
7868
David Drysdaledb0dcf52021-05-18 11:43:31 +01007869/*
David Drysdaleadfe6112021-05-27 12:00:53 +01007870 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
7871 *
7872 * Verifies that creating an early boot key with attestation succeeds.
7873 */
7874TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
7875 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
7876 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
7877 builder->AttestationChallenge("challenge");
7878 builder->AttestationApplicationId("app_id");
7879 });
7880
7881 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00007882 // Strongbox may not support factory attestation. Key creation might fail with
7883 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
7884 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
7885 continue;
7886 }
David Drysdaleadfe6112021-05-27 12:00:53 +01007887 ASSERT_GT(keyData.blob.size(), 0U);
7888 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7889 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7890 }
7891 CheckedDeleteKey(&aesKeyData.blob);
7892 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00007893 if (rsaKeyData.blob.size() != 0U) {
7894 CheckedDeleteKey(&rsaKeyData.blob);
7895 }
7896 if (ecdsaKeyData.blob.size() != 0U) {
7897 CheckedDeleteKey(&ecdsaKeyData.blob);
7898 }
David Drysdaleadfe6112021-05-27 12:00:53 +01007899}
7900
7901/*
7902 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01007903 *
7904 * Verifies that using early boot keys at a later stage fails.
7905 */
7906TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
7907 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7908 .Authorization(TAG_NO_AUTH_REQUIRED)
7909 .Authorization(TAG_EARLY_BOOT_ONLY)
7910 .HmacKey(128)
7911 .Digest(Digest::SHA_2_256)
7912 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
7913 AuthorizationSet output_params;
7914 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
7915 AuthorizationSetBuilder()
7916 .Digest(Digest::SHA_2_256)
7917 .Authorization(TAG_MAC_LENGTH, 256),
7918 &output_params));
7919}
7920
7921/*
7922 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
7923 *
7924 * Verifies that importing early boot keys fails.
7925 */
7926TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
7927 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
7928 .Authorization(TAG_NO_AUTH_REQUIRED)
7929 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01007930 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01007931 .Digest(Digest::SHA_2_256)
7932 .SetDefaultValidity(),
7933 KeyFormat::PKCS8, ec_256_key));
7934}
7935
David Drysdaled2cc8c22021-04-15 13:29:45 +01007936// 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 +00007937// boot stage, which no proper Android device is by the time we can run VTS. To use this,
7938// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
7939// early boot, so you'll have to reboot between runs.
7940TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
7941 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7942 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7943 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
7944 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7945 EXPECT_TRUE(
7946 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7947 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7948 EXPECT_TRUE(
7949 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7950
7951 // Should be able to use keys, since early boot has not ended
7952 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7953 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
7954 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
7955 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
7956
7957 // End early boot
7958 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
7959 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
7960
7961 // Should not be able to use already-created keys.
7962 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
7963 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
7964 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
7965 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
7966
7967 CheckedDeleteKey(&aesKeyData.blob);
7968 CheckedDeleteKey(&hmacKeyData.blob);
7969 CheckedDeleteKey(&rsaKeyData.blob);
7970 CheckedDeleteKey(&ecdsaKeyData.blob);
7971
7972 // Should not be able to create new keys
7973 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
7974 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
7975
7976 CheckedDeleteKey(&aesKeyData.blob);
7977 CheckedDeleteKey(&hmacKeyData.blob);
7978 CheckedDeleteKey(&rsaKeyData.blob);
7979 CheckedDeleteKey(&ecdsaKeyData.blob);
7980}
Shawn Willdend659c7c2021-02-19 14:51:51 -07007981
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007982INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
7983
Shawn Willdend659c7c2021-02-19 14:51:51 -07007984using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007985
7986// This may be a problematic test. It can't be run repeatedly without unlocking the device in
7987// between runs... and on most test devices there are no enrolled credentials so it can't be
7988// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
7989// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
7990// a manual test process, which includes unlocking between runs, which is why it's included here.
7991// Well, that and the fact that it's the only test we can do without also making calls into the
7992// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
7993// implications might be, so that may or may not be a solution.
7994TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
7995 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7996 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
7997
7998 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7999 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8000 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8001 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8002
8003 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008004 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008005 ASSERT_EQ(ErrorCode::OK, rc);
8006 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8007 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8008 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8009 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
8010
8011 CheckedDeleteKey(&aesKeyData.blob);
8012 CheckedDeleteKey(&hmacKeyData.blob);
8013 CheckedDeleteKey(&rsaKeyData.blob);
8014 CheckedDeleteKey(&ecdsaKeyData.blob);
8015}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008016
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008017INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8018
Shawn Willden22fb9c12022-06-02 14:04:33 -06008019using VsrRequirementTest = KeyMintAidlTestBase;
8020
8021TEST_P(VsrRequirementTest, Vsr13Test) {
8022 int vsr_api_level = get_vsr_api_level();
8023 if (vsr_api_level < 33) {
8024 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8025 }
8026 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8027}
8028
8029INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8030
Janis Danisevskis24c04702020-12-16 18:28:39 -08008031} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008032
8033int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008034 std::cout << "Testing ";
8035 auto halInstances =
8036 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8037 std::cout << "HAL instances:\n";
8038 for (auto& entry : halInstances) {
8039 std::cout << " " << entry << '\n';
8040 }
8041
Selene Huang31ab4042020-04-29 04:22:39 -07008042 ::testing::InitGoogleTest(&argc, argv);
8043 for (int i = 1; i < argc; ++i) {
8044 if (argv[i][0] == '-') {
8045 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008046 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8047 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008048 }
8049 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008050 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8051 dump_Attestations = true;
8052 } else {
8053 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008054 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008055 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8056 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8057 // be run in emulated environments that don't have the normal bootloader
8058 // interactions.
8059 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8060 }
Selene Huang31ab4042020-04-29 04:22:39 -07008061 }
8062 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008063 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008064}