blob: fa7dccb9fd31588025a3df0b83dcb803f470be2a [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
David Drysdale37af4b32021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Drysdale42fe1892021-10-14 14:43:46 +010025#include <openssl/curve25519.h>
David Zeuthene0c40892021-01-08 12:54:11 -050026#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070027#include <openssl/evp.h>
28#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050029#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070030
31#include <cutils/properties.h>
32
David Drysdale4dc01072021-04-01 12:17:35 +010033#include <android/binder_manager.h>
34
35#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080036#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070037
Shawn Willden08a7e432020-12-11 13:05:27 +000038#include <keymint_support/key_param_output.h>
39#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070040
41#include "KeyMintAidlTestBase.h"
42
Janis Danisevskis24c04702020-12-16 18:28:39 -080043using aidl::android::hardware::security::keymint::AuthorizationSet;
44using aidl::android::hardware::security::keymint::KeyCharacteristics;
45using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070046
Selene Huang31ab4042020-04-29 04:22:39 -070047namespace std {
48
Janis Danisevskis24c04702020-12-16 18:28:39 -080049using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070050
51template <>
52struct std::equal_to<KeyCharacteristics> {
53 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070054 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070055
Shawn Willden7f424372021-01-10 18:06:50 -070056 // this isn't very efficient. Oh, well.
57 AuthorizationSet a_auths(a.authorizations);
58 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070059
Shawn Willden7f424372021-01-10 18:06:50 -070060 a_auths.Sort();
61 b_auths.Sort();
62
63 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070064 }
65};
66
67} // namespace std
68
Janis Danisevskis24c04702020-12-16 18:28:39 -080069namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000070
Selene Huang31ab4042020-04-29 04:22:39 -070071namespace {
72
David Drysdalefeab5d92022-01-06 15:46:23 +000073// Maximum supported Ed25519 message size.
74const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
75
David Drysdaledbbbe2e2021-12-02 07:44:23 +000076// Whether to check that BOOT_PATCHLEVEL is populated.
77bool check_boot_pl = true;
78
Seth Moore7a55ae32021-06-23 14:28:11 -070079// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000080// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070081// is a small (roughly 1/256) chance that corrupting ciphertext still results
82// in valid PKCS7 padding.
83constexpr size_t kMaxPaddingCorruptionRetries = 8;
84
Selene Huang31ab4042020-04-29 04:22:39 -070085template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000086bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
87 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070088 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080089 if (auto p = authorizationValue(ttag, param)) {
90 return *p == expected_value;
91 }
92 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070093 });
94 return (it != set.end());
95}
96
97template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000098bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070099 auto it = std::find_if(set.begin(), set.end(),
100 [&](const KeyParameter& param) { return param.tag == tag; });
101 return (it != set.end());
102}
103
104constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
108 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
110 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
111 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
114 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
115 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
117 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
120
121string hex2str(string a) {
122 string b;
123 size_t num = a.size() / 2;
124 b.resize(num);
125 for (size_t i = 0; i < num; i++) {
126 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
127 }
128 return b;
129}
130
David Drysdaled2cc8c22021-04-15 13:29:45 +0100131string rsa_key = hex2str(
132 // RFC 5208 s5
133 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
134 "020100" // INTEGER length 1 value 0x00 (version)
135 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
136 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
137 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
138 "0500" // NULL (parameters)
139 // } end SEQUENCE (AlgorithmIdentifier)
140 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
141 // RFC 8017 A.1.2
142 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
143 "020100" // INTEGER length 1 value 0x00 (version)
144 "028181" // INTEGER length 0x81 value (modulus) ...
145 "00c6095409047d8634812d5a218176e4"
146 "5c41d60a75b13901f234226cffe77652"
147 "1c5a77b9e389417b71c0b6a44d13afe4"
148 "e4a2805d46c9da2935adb1ff0c1f24ea"
149 "06e62b20d776430a4d435157233c6f91"
150 "6783c30e310fcbd89b85c2d567711697"
151 "85ac12bca244abda72bfb19fc44d27c8"
152 "1e1d92de284f4061edfd99280745ea6d"
153 "25"
154 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
155 "028180" // INTEGER length 0x80 (privateExponent) value...
156 "1be0f04d9cae3718691f035338308e91"
157 "564b55899ffb5084d2460e6630257e05"
158 "b3ceab02972dfabcd6ce5f6ee2589eb6"
159 "7911ed0fac16e43a444b8c861e544a05"
160 "93365772f8baf6b22fc9e3c5f1024b06"
161 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
162 "ace7240290bef16c0b3f7f3cdd64ce3a"
163 "b5912cf6e32f39ab188358afcccd8081"
164 "0241" // INTEGER length 0x41 (prime1)
165 "00e4b49ef50f765d3b24dde01aceaaf1"
166 "30f2c76670a91a61ae08af497b4a82be"
167 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
168 "8c92bfab137fba2285227b83c342ff7c"
169 "55"
170 "0241" // INTEGER length 0x41 (prime2)
171 "00ddabb5839c4c7f6bf3d4183231f005"
172 "b31aa58affdda5c79e4cce217f6bc930"
173 "dbe563d480706c24e9ebfcab28a6cdef"
174 "d324b77e1bf7251b709092c24ff501fd"
175 "91"
176 "0240" // INTEGER length 0x40 (exponent1)
177 "23d4340eda3445d8cd26c14411da6fdc"
178 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
179 "842c1d280405bc2f6c1bea214a1d742a"
180 "b996b35b63a82a5e470fa88dbf823cdd"
181 "0240" // INTEGER length 0x40 (exponent2)
182 "1b7b57449ad30d1518249a5f56bb9829"
183 "4d4b6ac12ffc86940497a5a5837a6cf9"
184 "46262b494526d328c11e1126380fde04"
185 "c24f916dec250892db09a6d77cdba351"
186 "0240" // INTEGER length 0x40 (coefficient)
187 "7762cd8f4d050da56bd591adb515d24d"
188 "7ccd32cca0d05f866d583514bd7324d5"
189 "f33645e8ed8b4a1cb3cc4a1d67987399"
190 "f2a09f5b3fb68c88d5e5d90ac33492d6"
191 // } end SEQUENCE (PrivateKey)
192 // } end SEQUENCE (PrivateKeyInfo)
193);
Selene Huang31ab4042020-04-29 04:22:39 -0700194
Selene Huange5727e62021-04-13 22:41:20 -0700195/*
196 * DER-encoded PKCS#8 format RSA key. Generated using:
197 *
198 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
199 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100200string rsa_2048_key = hex2str(
201 // RFC 5208 s5
202 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
203 "020100" // INTEGER length 1 value 0x00 (version)
204 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
205 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
206 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
207 "0500" // NULL (parameters)
208 // } end SEQUENCE (AlgorithmIdentifier)
209 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
210 // RFC 8017 A.1.2
211 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
212 "020100" // INTEGER length 1 value 0x00 (version)
213 "02820101" // INTEGER length 0x101 value (modulus) ...
214 "00BEBC342B56D443B1299F9A6A7056E8"
215 "0A897E318476A5A18029E63B2ED739A6"
216 "1791D339F58DC763D9D14911F2EDEC38"
217 "3DEE11F6319B44510E7A3ECD9B79B973"
218 "82E49500ACF8117DC89CAF0E621F7775"
219 "6554A2FD4664BFE7AB8B59AB48340DBF"
220 "A27B93B5A81F6ECDEB02D0759307128D"
221 "F3E3BAD4055C8B840216DFAA5700670E"
222 "6C5126F0962FCB70FF308F25049164CC"
223 "F76CC2DA66A7DD9A81A714C2809D6918"
224 "6133D29D84568E892B6FFBF3199BDB14"
225 "383EE224407F190358F111A949552ABA"
226 "6714227D1BD7F6B20DD0CB88F9467B71"
227 "9339F33BFF35B3870B3F62204E4286B0"
228 "948EA348B524544B5F9838F29EE643B0"
229 "79EEF8A713B220D7806924CDF7295070"
230 "C5"
231 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
232 "02820100" // INTEGER length 0x100 (privateExponent) value...
233 "69F377F35F2F584EF075353CCD1CA997"
234 "38DB3DBC7C7FF35F9366CE176DFD1B13"
235 "5AB10030344ABF5FBECF1D4659FDEF1C"
236 "0FC430834BE1BE3911951377BB3D563A"
237 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
238 "2686C7B4B3C09A7B8354133E6F93F790"
239 "D59EAEB92E84C9A4339302CCE28FDF04"
240 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
241 "6AB706645BF074A4E4090D06FB163124"
242 "365FD5EE7A20D350E9958CC30D91326E"
243 "1B292E9EF5DB408EC42DAF737D201497"
244 "04D0A678A0FB5B5446863B099228A352"
245 "D604BA8091A164D01D5AB05397C71EAD"
246 "20BE2A08FC528FE442817809C787FEE4"
247 "AB97F97B9130D022153EDC6EB6CBE7B0"
248 "F8E3473F2E901209B5DB10F93604DB01"
249 "028181" // INTEGER length 0x81 (prime1)
250 "00E83C0998214941EA4F9293F1B77E2E"
251 "99E6CF305FAF358238E126124FEAF2EB"
252 "9724B2EA7B78E6032343821A80E55D1D"
253 "88FB12D220C3F41A56142FEC85796D19"
254 "17F1E8C774F142B67D3D6E7B7E6B4383"
255 "E94DB5929089DBB346D5BDAB40CC2D96"
256 "EE0409475E175C63BF78CFD744136740"
257 "838127EA723FF3FE7FA368C1311B4A4E"
258 "05"
259 "028181" // INTEGER length 0x81 (prime2)
260 "00D240FCC0F5D7715CDE21CB2DC86EA1"
261 "46132EA3B06F61FF2AF54BF38473F59D"
262 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
263 "B1B58C39F95E4798CCBB43E83D0119AC"
264 "F532F359CA743C85199F0286610E2009"
265 "97D7312917179AC9B67558773212EC96"
266 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
267 "94D94E066A0900B7B70E82A44FB30053"
268 "C1"
269 "028181" // INTEGER length 0x81 (exponent1)
270 "00AD15DA1CBD6A492B66851BA8C316D3"
271 "8AB700E2CFDDD926A658003513C54BAA"
272 "152B30021D667D20078F500F8AD3E7F3"
273 "945D74A891ED1A28EAD0FEEAEC8C14A8"
274 "E834CF46A13D1378C99D18940823CFDD"
275 "27EC5810D59339E0C34198AC638E09C8"
276 "7CBB1B634A9864AE9F4D5EB2D53514F6"
277 "7B4CAEC048C8AB849A02E397618F3271"
278 "35"
279 "028180" // INTEGER length 0x80 (exponent2)
280 "1FA2C1A5331880A92D8F3E281C617108"
281 "BF38244F16E352E69ED417C7153F9EC3"
282 "18F211839C643DCF8B4DD67CE2AC312E"
283 "95178D5D952F06B1BF779F4916924B70"
284 "F582A23F11304E02A5E7565AE22A35E7"
285 "4FECC8B6FDC93F92A1A37703E4CF0E63"
286 "783BD02EB716A7ECBBFA606B10B74D01"
287 "579522E7EF84D91FC522292108D902C1"
288 "028180" // INTEGER length 0x80 (coefficient)
289 "796FE3825F9DCC85DF22D58690065D93"
290 "898ACD65C087BEA8DA3A63BF4549B795"
291 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
292 "0D74F40DED8E1102C52152A31B6165F8"
293 "3A6722AECFCC35A493D7634664B888A0"
294 "8D3EB034F12EA28BFEE346E205D33482"
295 "7F778B16ED40872BD29FCB36536B6E93"
296 "FFB06778696B4A9D81BB0A9423E63DE5"
297 // } end SEQUENCE (PrivateKey)
298 // } end SEQUENCE (PrivateKeyInfo)
299);
Selene Huange5727e62021-04-13 22:41:20 -0700300
David Drysdaled2cc8c22021-04-15 13:29:45 +0100301string ec_256_key = hex2str(
302 // RFC 5208 s5
303 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
304 "020100" // INTEGER length 1 value 0 (version)
305 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
306 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
307 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
308 "0608" // OBJECT IDENTIFIER length 8 (param)
309 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
310 // } end SEQUENCE (AlgorithmIdentifier)
311 "046d" // OCTET STRING length 0x6d (privateKey) holding...
312 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
313 "020101" // INTEGER length 1 value 1 (version)
314 "0420" // OCTET STRING length 0x20 (privateKey)
315 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
316 "941eed09366bc03299986481f3a4d859"
317 "a144" // TAG [1] len 0x44 (publicKey) {
318 "03420004bf85d7720d07c25461683bc6"
319 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
320 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
321 "bcc41c6eb00083cf3376d11fd44949e0"
322 "b2183bfe"
323 // } end SEQUENCE (ECPrivateKey)
324 // } end SEQUENCE (PrivateKeyInfo)
325);
Selene Huang31ab4042020-04-29 04:22:39 -0700326
David Drysdaled2cc8c22021-04-15 13:29:45 +0100327string ec_521_key = hex2str(
328 // RFC 5208 s5
329 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
330 "020100" // INTEGER length 1 value 0 (version)
331 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
332 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
333 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
334 "0605" // OBJECT IDENTIFIER length 5 (param)
335 "2B81040023" // 1.3.132.0.35 (secp521r1)
336 // } end SEQUENCE (AlgorithmIdentifier)
337 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
338 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
339 "020101" // INTEGER length 1 value 1 (version)
340 "0442" // OCTET STRING length 0x42 (privateKey)
341 "0011458C586DB5DAA92AFAB03F4FE46A"
342 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
343 "9D18D7D08B5BCFA0E53C75B064AD51C4"
344 "49BAE0258D54B94B1E885DED08ED4FB2"
345 "5CE9"
346 "A18189" // TAG [1] len 0x89 (publicKey) {
347 "03818600040149EC11C6DF0FA122C6A9"
348 "AFD9754A4FA9513A627CA329E349535A"
349 "5629875A8ADFBE27DCB932C051986377"
350 "108D054C28C6F39B6F2C9AF81802F9F3"
351 "26B842FF2E5F3C00AB7635CFB36157FC"
352 "0882D574A10D839C1A0C049DC5E0D775"
353 "E2EE50671A208431BB45E78E70BEFE93"
354 "0DB34818EE4D5C26259F5C6B8E28A652"
355 "950F9F88D7B4B2C9D9"
356 // } end SEQUENCE (ECPrivateKey)
357 // } end SEQUENCE (PrivateKeyInfo)
358);
Selene Huang31ab4042020-04-29 04:22:39 -0700359
David Drysdaled2cc8c22021-04-15 13:29:45 +0100360string ec_256_key_rfc5915 = hex2str(
361 // RFC 5208 s5
362 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
363 "020100" // INTEGER length 1 value 0 (version)
364 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
365 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
366 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
367 "0608" // OBJECT IDENTIFIER length 8 (param)
368 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
369 // } end SEQUENCE (AlgorithmIdentifier)
370 "0479" // OCTET STRING length 0x79 (privateKey) holding...
371 // RFC 5915 s3
372 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
373 "020101" // INTEGER length 1 value 1 (version)
374 "0420" // OCTET STRING length 0x42 (privateKey)
375 "782370a8c8ce5537baadd04dcff079c8"
376 "158cfa9c67b818b38e8d21c9fa750c1d"
377 "a00a" // TAG [0] length 0xa (parameters)
378 "0608" // OBJECT IDENTIFIER length 8
379 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
380 // } end TAG [0]
381 "a144" // TAG [1] length 0x44 (publicKey) {
382 "0342" // BIT STRING length 0x42
383 "00" // no pad bits
384 "04e2cc561ee701da0ad0ef0d176bb0c9"
385 "19d42e79c393fdc1bd6c4010d85cf2cf"
386 "8e68c905464666f98dad4f01573ba810"
387 "78b3428570a439ba3229fbc026c55068"
388 "2f"
389 // } end SEQUENCE (ECPrivateKey)
390 // } end SEQUENCE (PrivateKeyInfo)
391);
Selene Huang31ab4042020-04-29 04:22:39 -0700392
David Drysdaled2cc8c22021-04-15 13:29:45 +0100393string ec_256_key_sec1 = hex2str(
394 // RFC 5208 s5
395 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
396 "020100" // INTEGER length 1 value 0 (version)
397 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
398 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
399 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
400 "0608" // OBJECT IDENTIFIER length 8 (param)
401 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
402 // } end SEQUENCE (AlgorithmIdentifier)
403 "046d" // OCTET STRING length 0x6d (privateKey) holding...
404 // SEC1-v2 C.4
405 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
406 "020101" // INTEGER length 1 value 0x01 (version)
407 "0420" // OCTET STRING length 0x20 (privateKey)
408 "782370a8c8ce5537baadd04dcff079c8"
409 "158cfa9c67b818b38e8d21c9fa750c1d"
410 "a144" // TAG [1] length 0x44 (publicKey) {
411 "0342" // BIT STRING length 0x42
412 "00" // no pad bits
413 "04e2cc561ee701da0ad0ef0d176bb0c9"
414 "19d42e79c393fdc1bd6c4010d85cf2cf"
415 "8e68c905464666f98dad4f01573ba810"
416 "78b3428570a439ba3229fbc026c55068"
417 "2f"
418 // } end TAG [1] (publicKey)
419 // } end SEQUENCE (PrivateKeyInfo)
420);
Selene Huang31ab4042020-04-29 04:22:39 -0700421
David Drysdale42fe1892021-10-14 14:43:46 +0100422/**
423 * Ed25519 key pair generated as follows:
424 * ```
425 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
426 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
427 * Generating a ED25519 private key writing new private key to
428 * 'ed25519_priv.key'
429 * -----
430 * % cat ed25519_priv.key
431 * -----BEGIN PRIVATE KEY-----
432 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
433 * -----END PRIVATE KEY-----
434 * % der2ascii -pem -i ed25519_priv.key
435 * SEQUENCE {
436 * INTEGER { 0 }
437 * SEQUENCE {
438 * # ed25519
439 * OBJECT_IDENTIFIER { 1.3.101.112 }
440 * }
441 * OCTET_STRING {
442 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
443 * }
444 * }
445 * % cat ed25519.pem
446 * -----BEGIN CERTIFICATE-----
447 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
448 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
449 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
450 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
451 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
452 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
453 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
454 * -----END CERTIFICATE-----
455 * % openssl x509 -in ed25519.pem -text -noout
456 * Certificate:
457 * Data:
458 * Version: 3 (0x2)
459 * Serial Number:
460 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
461 * Signature Algorithm: ED25519
462 * Issuer: CN = fake.ed25519.com
463 * Validity
464 * Not Before: Oct 20 08:27:42 2021 GMT
465 * Not After : Sep 20 08:27:42 2023 GMT
466 * Subject: CN = fake.ed25519.com
467 * Subject Public Key Info:
468 * Public Key Algorithm: ED25519
469 * ED25519 Public-Key:
470 * pub:
471 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
472 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
473 * 56:91
474 * X509v3 extensions:
475 * X509v3 Subject Key Identifier:
476 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
477 * X509v3 Authority Key Identifier:
478 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
479 *
480 * X509v3 Basic Constraints: critical
481 * CA:TRUE
482 * Signature Algorithm: ED25519
483 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
484 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
485 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
486 * e7:07:32:60:32:8d:bb:eb:f6:0f
487 * ```
488 */
489string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
490string ed25519_pkcs8_key = hex2str(
491 // RFC 5208 s5
492 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
493 "0201" // INTEGER length 1 (Version)
494 "00" // version 0
495 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
496 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
497 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
498 // } end SEQUENCE (AlgorithmIdentifier)
499 "0422" // OCTET STRING length 0x22 (PrivateKey)
500 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
501 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
502 // } end SEQUENCE (PrivateKeyInfo)
503);
504string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
505
506/**
507 * X25519 key pair generated as follows:
508 * ```
509 * % openssl genpkey -algorithm X25519 > x25519_priv.key
510 * % cat x25519_priv.key
511 * -----BEGIN PRIVATE KEY-----
512 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
513 * -----END PRIVATE KEY-----
514 * % der2ascii -pem -i x25519_priv.key
515 * SEQUENCE {
516 * INTEGER { 0 }
517 * SEQUENCE {
518 * # x25519
519 * OBJECT_IDENTIFIER { 1.3.101.110 }
520 * }
521 * OCTET_STRING {
522 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
523 * }
524 * }
525 * ```
526 */
527
528string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
529string x25519_pkcs8_key = hex2str(
530 // RFC 5208 s5
531 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
532 "0201" // INTEGER length 1 (Version)
533 "00" // version 0
534 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
535 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
536 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
537 "0422" // OCTET STRING length 0x22 (PrivateKey)
538 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
539 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
540string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
541
Selene Huang31ab4042020-04-29 04:22:39 -0700542struct RSA_Delete {
543 void operator()(RSA* p) { RSA_free(p); }
544};
545
Selene Huang31ab4042020-04-29 04:22:39 -0700546std::string make_string(const uint8_t* data, size_t length) {
547 return std::string(reinterpret_cast<const char*>(data), length);
548}
549
550template <size_t N>
551std::string make_string(const uint8_t (&a)[N]) {
552 return make_string(a, N);
553}
554
555class AidlBuf : public vector<uint8_t> {
556 typedef vector<uint8_t> super;
557
558 public:
559 AidlBuf() {}
560 AidlBuf(const super& other) : super(other) {}
561 AidlBuf(super&& other) : super(std::move(other)) {}
562 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
563
564 AidlBuf& operator=(const super& other) {
565 super::operator=(other);
566 return *this;
567 }
568
569 AidlBuf& operator=(super&& other) {
570 super::operator=(std::move(other));
571 return *this;
572 }
573
574 AidlBuf& operator=(const string& other) {
575 resize(other.size());
576 for (size_t i = 0; i < other.size(); ++i) {
577 (*this)[i] = static_cast<uint8_t>(other[i]);
578 }
579 return *this;
580 }
581
582 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
583};
584
David Drysdale4dc01072021-04-01 12:17:35 +0100585string device_suffix(const string& name) {
586 size_t pos = name.find('/');
587 if (pos == string::npos) {
588 return name;
589 }
590 return name.substr(pos + 1);
591}
592
593bool matching_rp_instance(const string& km_name,
594 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
595 string km_suffix = device_suffix(km_name);
596
597 vector<string> rp_names =
598 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
599 for (const string& rp_name : rp_names) {
600 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
601 // KeyMint instance, assume they match.
602 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
603 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
604 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
605 return true;
606 }
607 }
608 return false;
609}
610
Selene Huang31ab4042020-04-29 04:22:39 -0700611} // namespace
612
613class NewKeyGenerationTest : public KeyMintAidlTestBase {
614 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700615 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000616 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
Selene Huang31ab4042020-04-29 04:22:39 -0700617 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700618
Selene Huang31ab4042020-04-29 04:22:39 -0700619 // Check that some unexpected tags/values are NOT present.
620 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
621 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000622 }
623
624 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000625 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
David Drysdale7de9feb2021-03-05 14:56:19 +0000626 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
627 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
628
629 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000630 }
631
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000632 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics,
633 const KeyOrigin expectedKeyOrigin) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000634 // TODO(swillden): Distinguish which params should be in which auth list.
635 AuthorizationSet auths;
636 for (auto& entry : keyCharacteristics) {
637 auths.push_back(AuthorizationSet(entry.authorizations));
638 }
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000639 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, expectedKeyOrigin));
David Drysdale7de9feb2021-03-05 14:56:19 +0000640
641 // Verify that App data, ROT and auth timeout are NOT included.
642 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
643 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700644 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
645
David Drysdaled2cc8c22021-04-15 13:29:45 +0100646 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
647 // never adds it.
648 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
649
David Drysdale7de9feb2021-03-05 14:56:19 +0000650 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700651 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000652 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700653 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700654 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000655 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700656 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000657
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000658 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100659 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
660 EXPECT_TRUE(vendor_pl);
661 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000662
663 // Should include boot patchlevel (but there are some test scenarios where this is not
664 // possible).
665 if (check_boot_pl) {
666 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
667 EXPECT_TRUE(boot_pl);
668 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100669
David Drysdale7de9feb2021-03-05 14:56:19 +0000670 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700671 }
672};
673
674/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000675 * NewKeyGenerationTest.Aes
676 *
677 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
678 * have correct characteristics.
679 */
680TEST_P(NewKeyGenerationTest, Aes) {
681 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
682 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
683 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
684 SCOPED_TRACE(testing::Message()
685 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
686 vector<uint8_t> key_blob;
687 vector<KeyCharacteristics> key_characteristics;
688 auto builder = AuthorizationSetBuilder()
689 .AesEncryptionKey(key_size)
690 .BlockMode(block_mode)
691 .Padding(padding_mode)
692 .SetDefaultValidity();
693 if (block_mode == BlockMode::GCM) {
694 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
695 }
696 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
697
698 EXPECT_GT(key_blob.size(), 0U);
699 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100700 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000701
702 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
703
704 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
705 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
706 << "Key size " << key_size << "missing";
707
708 CheckedDeleteKey(&key_blob);
709 }
710 }
711 }
712}
713
714/*
715 * NewKeyGenerationTest.AesInvalidSize
716 *
717 * Verifies that specifying an invalid key size for AES key generation returns
718 * UNSUPPORTED_KEY_SIZE.
719 */
720TEST_P(NewKeyGenerationTest, AesInvalidSize) {
721 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
722 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
723 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
724 SCOPED_TRACE(testing::Message()
725 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
726 vector<uint8_t> key_blob;
727 vector<KeyCharacteristics> key_characteristics;
728 auto builder = AuthorizationSetBuilder()
729 .AesEncryptionKey(key_size)
730 .BlockMode(block_mode)
731 .Padding(padding_mode)
732 .SetDefaultValidity();
733 if (block_mode == BlockMode::GCM) {
734 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
735 }
736 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
737 GenerateKey(builder, &key_blob, &key_characteristics));
738 }
739 }
740 }
741
742 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
743 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
744 vector<uint8_t> key_blob;
745 vector<KeyCharacteristics> key_characteristics;
746 // No key size specified
747 auto builder = AuthorizationSetBuilder()
748 .Authorization(TAG_ALGORITHM, Algorithm::AES)
749 .BlockMode(block_mode)
750 .Padding(padding_mode)
751 .SetDefaultValidity();
752 if (block_mode == BlockMode::GCM) {
753 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
754 }
755 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
756 GenerateKey(builder, &key_blob, &key_characteristics));
757 }
758 }
759}
760
761/*
762 * NewKeyGenerationTest.AesInvalidPadding
763 *
764 * Verifies that specifying an invalid padding on AES keys gives a failure
765 * somewhere along the way.
766 */
767TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
768 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
769 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
770 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
771 SCOPED_TRACE(testing::Message()
772 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000773 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800774 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000775 .AesEncryptionKey(key_size)
776 .BlockMode(block_mode)
777 .Padding(padding_mode)
778 .SetDefaultValidity();
779 if (block_mode == BlockMode::GCM) {
780 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
781 }
782
Tommy Chiu3950b452021-05-03 22:01:46 +0800783 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000784 if (result == ErrorCode::OK) {
785 // Key creation was OK but has generated a key that cannot be used.
786 auto params =
787 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800788 if (block_mode == BlockMode::GCM) {
789 params.Authorization(TAG_MAC_LENGTH, 128);
790 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000791 auto result = Begin(KeyPurpose::ENCRYPT, params);
792 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100793 result == ErrorCode::INVALID_KEY_BLOB)
794 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000795 } else {
796 // The KeyMint implementation detected that the generated key
797 // is unusable.
798 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
799 }
800 }
801 }
802 }
803}
804
805/*
806 * NewKeyGenerationTest.AesGcmMissingMinMac
807 *
808 * Verifies that specifying an invalid key size for AES key generation returns
809 * UNSUPPORTED_KEY_SIZE.
810 */
811TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
812 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
813 BlockMode block_mode = BlockMode::GCM;
814 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
815 SCOPED_TRACE(testing::Message()
816 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
817 vector<uint8_t> key_blob;
818 vector<KeyCharacteristics> key_characteristics;
819 // No MIN_MAC_LENGTH provided.
820 auto builder = AuthorizationSetBuilder()
821 .AesEncryptionKey(key_size)
822 .BlockMode(block_mode)
823 .Padding(padding_mode)
824 .SetDefaultValidity();
825 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
826 GenerateKey(builder, &key_blob, &key_characteristics));
827 }
828 }
829}
830
831/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100832 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
833 *
834 * Verifies that specifying an invalid min MAC size for AES key generation returns
835 * UNSUPPORTED_MIN_MAC_LENGTH.
836 */
837TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
838 for (size_t min_mac_len : {88, 136}) {
839 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
840 BlockMode block_mode = BlockMode::GCM;
841 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
842 SCOPED_TRACE(testing::Message()
843 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
844 vector<uint8_t> key_blob;
845 vector<KeyCharacteristics> key_characteristics;
846 auto builder = AuthorizationSetBuilder()
847 .AesEncryptionKey(key_size)
848 .BlockMode(block_mode)
849 .Padding(padding_mode)
850 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
851 .SetDefaultValidity();
852 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
853 GenerateKey(builder, &key_blob, &key_characteristics));
854 }
855 }
856 }
857}
858
859/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000860 * NewKeyGenerationTest.TripleDes
861 *
862 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
863 * have correct characteristics.
864 */
865TEST_P(NewKeyGenerationTest, TripleDes) {
866 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
867 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
868 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
869 SCOPED_TRACE(testing::Message()
870 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
871 vector<uint8_t> key_blob;
872 vector<KeyCharacteristics> key_characteristics;
873 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
874 .TripleDesEncryptionKey(key_size)
875 .BlockMode(block_mode)
876 .Padding(padding_mode)
877 .Authorization(TAG_NO_AUTH_REQUIRED)
878 .SetDefaultValidity(),
879 &key_blob, &key_characteristics));
880
881 EXPECT_GT(key_blob.size(), 0U);
882 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100883 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000884
885 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
886
887 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
888 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
889 << "Key size " << key_size << "missing";
890
891 CheckedDeleteKey(&key_blob);
892 }
893 }
894 }
895}
896
897/*
898 * NewKeyGenerationTest.TripleDesWithAttestation
899 *
900 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
901 * have correct characteristics.
902 *
903 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
904 * put in a certificate) but which isn't an error.
905 */
906TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
907 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
908 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
909 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
910 SCOPED_TRACE(testing::Message()
911 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
912
913 auto challenge = "hello";
914 auto app_id = "foo";
915
916 vector<uint8_t> key_blob;
917 vector<KeyCharacteristics> key_characteristics;
918 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
919 .TripleDesEncryptionKey(key_size)
920 .BlockMode(block_mode)
921 .Padding(padding_mode)
922 .Authorization(TAG_NO_AUTH_REQUIRED)
923 .AttestationChallenge(challenge)
924 .AttestationApplicationId(app_id)
925 .SetDefaultValidity(),
926 &key_blob, &key_characteristics));
927
928 EXPECT_GT(key_blob.size(), 0U);
929 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100930 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000931
932 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
933
934 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
935 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
936 << "Key size " << key_size << "missing";
937
938 CheckedDeleteKey(&key_blob);
939 }
940 }
941 }
942}
943
944/*
945 * NewKeyGenerationTest.TripleDesInvalidSize
946 *
947 * Verifies that specifying an invalid key size for 3-DES key generation returns
948 * UNSUPPORTED_KEY_SIZE.
949 */
950TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
951 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
952 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
953 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
954 SCOPED_TRACE(testing::Message()
955 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
956 vector<uint8_t> key_blob;
957 vector<KeyCharacteristics> key_characteristics;
958 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
959 GenerateKey(AuthorizationSetBuilder()
960 .TripleDesEncryptionKey(key_size)
961 .BlockMode(block_mode)
962 .Padding(padding_mode)
963 .Authorization(TAG_NO_AUTH_REQUIRED)
964 .SetDefaultValidity(),
965 &key_blob, &key_characteristics));
966 }
967 }
968 }
969
970 // Omitting the key size fails.
971 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
972 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
973 SCOPED_TRACE(testing::Message()
974 << "3DES-default-" << block_mode << "-" << padding_mode);
975 vector<uint8_t> key_blob;
976 vector<KeyCharacteristics> key_characteristics;
977 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
978 GenerateKey(AuthorizationSetBuilder()
979 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
980 .BlockMode(block_mode)
981 .Padding(padding_mode)
982 .Authorization(TAG_NO_AUTH_REQUIRED)
983 .SetDefaultValidity(),
984 &key_blob, &key_characteristics));
985 }
986 }
987}
988
989/*
Selene Huang31ab4042020-04-29 04:22:39 -0700990 * NewKeyGenerationTest.Rsa
991 *
992 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
993 * have correct characteristics.
994 */
995TEST_P(NewKeyGenerationTest, Rsa) {
996 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
997 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700998 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700999 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1000 .RsaSigningKey(key_size, 65537)
1001 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001002 .Padding(PaddingMode::NONE)
1003 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001004 &key_blob, &key_characteristics));
1005
1006 ASSERT_GT(key_blob.size(), 0U);
1007 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001008 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001009
Shawn Willden7f424372021-01-10 18:06:50 -07001010 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001011
1012 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1013 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1014 << "Key size " << key_size << "missing";
1015 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1016
1017 CheckedDeleteKey(&key_blob);
1018 }
1019}
1020
1021/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001022 * NewKeyGenerationTest.RsaWithMissingValidity
1023 *
1024 * Verifies that keymint returns an error while generating asymmetric key
1025 * without providing NOT_BEFORE and NOT_AFTER parameters.
1026 */
1027TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
1028 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1029 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1030 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1031
1032 vector<uint8_t> key_blob;
1033 vector<KeyCharacteristics> key_characteristics;
1034 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1035 GenerateKey(AuthorizationSetBuilder()
1036 .RsaSigningKey(2048, 65537)
1037 .Digest(Digest::NONE)
1038 .Padding(PaddingMode::NONE)
1039 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1040 kUndefinedExpirationDateTime),
1041 &key_blob, &key_characteristics));
1042
1043 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1044 GenerateKey(AuthorizationSetBuilder()
1045 .RsaSigningKey(2048, 65537)
1046 .Digest(Digest::NONE)
1047 .Padding(PaddingMode::NONE)
1048 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1049 &key_blob, &key_characteristics));
1050}
1051
1052/*
Qi Wud22ec842020-11-26 13:27:53 +08001053 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001054 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001055 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1056 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001057 */
1058TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001059 auto challenge = "hello";
1060 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001061
Selene Huang6e46f142021-04-20 19:20:11 -07001062 auto subject = "cert subj 2";
1063 vector<uint8_t> subject_der(make_name_from_str(subject));
1064
1065 uint64_t serial_int = 66;
1066 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1067
Selene Huang4f64c222021-04-13 19:54:36 -07001068 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001069 vector<uint8_t> key_blob;
1070 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001071 auto builder = AuthorizationSetBuilder()
1072 .RsaSigningKey(key_size, 65537)
1073 .Digest(Digest::NONE)
1074 .Padding(PaddingMode::NONE)
1075 .AttestationChallenge(challenge)
1076 .AttestationApplicationId(app_id)
1077 .Authorization(TAG_NO_AUTH_REQUIRED)
1078 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1079 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1080 .SetDefaultValidity();
1081
1082 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001083 // Strongbox may not support factory provisioned attestation key.
1084 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001085 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1086 result = GenerateKeyWithSelfSignedAttestKey(
1087 AuthorizationSetBuilder()
1088 .RsaKey(key_size, 65537)
1089 .AttestKey()
1090 .SetDefaultValidity(), /* attest key params */
1091 builder, &key_blob, &key_characteristics);
1092 }
subrahmanyaman05642492022-02-05 07:10:56 +00001093 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001094 ASSERT_EQ(ErrorCode::OK, result);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001095 ASSERT_GT(key_blob.size(), 0U);
1096 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001097 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001098
1099 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1100
1101 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1102 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1103 << "Key size " << key_size << "missing";
1104 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1105
David Drysdalea8a888e2022-06-08 12:43:56 +01001106 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001107 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001108 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001109
1110 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1111 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001112 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001113 sw_enforced, hw_enforced, SecLevel(),
1114 cert_chain_[0].encodedCertificate));
1115
1116 CheckedDeleteKey(&key_blob);
1117 }
1118}
1119
1120/*
David Drysdale4dc01072021-04-01 12:17:35 +01001121 * NewKeyGenerationTest.RsaWithRpkAttestation
1122 *
1123 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
1124 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale0fce69d2021-04-13 17:22:13 +01001125 *
1126 * This test is disabled because the KeyMint specification does not require that implementations
1127 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
1128 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +01001129 */
David Drysdale0fce69d2021-04-13 17:22:13 +01001130TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +01001131 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
1132 // instance.
1133 std::shared_ptr<IRemotelyProvisionedComponent> rp;
1134 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
1135 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
1136
1137 // Generate a P-256 keypair to use as an attestation key.
1138 MacedPublicKey macedPubKey;
1139 std::vector<uint8_t> privateKeyBlob;
1140 auto status =
1141 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1142 ASSERT_TRUE(status.isOk());
1143 vector<uint8_t> coseKeyData;
1144 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1145
1146 AttestationKey attestation_key;
1147 attestation_key.keyBlob = std::move(privateKeyBlob);
1148 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1149
1150 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1151 auto challenge = "hello";
1152 auto app_id = "foo";
1153
1154 vector<uint8_t> key_blob;
1155 vector<KeyCharacteristics> key_characteristics;
1156 ASSERT_EQ(ErrorCode::OK,
1157 GenerateKey(AuthorizationSetBuilder()
1158 .RsaSigningKey(key_size, 65537)
1159 .Digest(Digest::NONE)
1160 .Padding(PaddingMode::NONE)
1161 .AttestationChallenge(challenge)
1162 .AttestationApplicationId(app_id)
1163 .Authorization(TAG_NO_AUTH_REQUIRED)
1164 .SetDefaultValidity(),
1165 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1166
1167 ASSERT_GT(key_blob.size(), 0U);
1168 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001169 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001170
1171 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1172
1173 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1174 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1175 << "Key size " << key_size << "missing";
1176 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1177
1178 // Attestation by itself is not valid (last entry is not self-signed).
1179 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1180
1181 // The signature over the attested key should correspond to the P256 public key.
David Drysdalea8a888e2022-06-08 12:43:56 +01001182 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale4dc01072021-04-01 12:17:35 +01001183 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1184 ASSERT_TRUE(key_cert.get());
1185 EVP_PKEY_Ptr signing_pubkey;
1186 p256_pub_key(coseKeyData, &signing_pubkey);
1187 ASSERT_TRUE(signing_pubkey.get());
1188
1189 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1190 << "Verification of attested certificate failed "
1191 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1192
1193 CheckedDeleteKey(&key_blob);
1194 }
1195}
1196
1197/*
Selene Huang4f64c222021-04-13 19:54:36 -07001198 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1199 *
1200 * Verifies that keymint attestation for RSA encryption keys with challenge and
1201 * app id is also successful.
1202 */
1203TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1204 auto key_size = 2048;
1205 auto challenge = "hello";
1206 auto app_id = "foo";
1207
Selene Huang6e46f142021-04-20 19:20:11 -07001208 auto subject = "subj 2";
1209 vector<uint8_t> subject_der(make_name_from_str(subject));
1210
1211 uint64_t serial_int = 111166;
1212 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1213
Selene Huang4f64c222021-04-13 19:54:36 -07001214 vector<uint8_t> key_blob;
1215 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001216 auto builder = AuthorizationSetBuilder()
1217 .RsaEncryptionKey(key_size, 65537)
1218 .Padding(PaddingMode::NONE)
1219 .AttestationChallenge(challenge)
1220 .AttestationApplicationId(app_id)
1221 .Authorization(TAG_NO_AUTH_REQUIRED)
1222 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1223 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1224 .SetDefaultValidity();
1225
1226 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001227 // Strongbox may not support factory provisioned attestation key.
1228 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001229 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1230 result = GenerateKeyWithSelfSignedAttestKey(
1231 AuthorizationSetBuilder()
1232 .RsaKey(key_size, 65537)
1233 .AttestKey()
1234 .SetDefaultValidity(), /* attest key params */
1235 builder, &key_blob, &key_characteristics);
1236 }
subrahmanyaman05642492022-02-05 07:10:56 +00001237 }
1238 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001239
1240 ASSERT_GT(key_blob.size(), 0U);
1241 AuthorizationSet auths;
1242 for (auto& entry : key_characteristics) {
1243 auths.push_back(AuthorizationSet(entry.authorizations));
1244 }
1245
1246 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1247 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1248
1249 // Verify that App data and ROT are NOT included.
1250 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1251 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1252
1253 // Check that some unexpected tags/values are NOT present.
1254 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1255 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1256
1257 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1258
1259 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1260 ASSERT_TRUE(os_ver);
1261 EXPECT_EQ(*os_ver, os_version());
1262
1263 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1264
1265 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1266 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1267 << "Key size " << key_size << "missing";
1268 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1269
David Drysdalea8a888e2022-06-08 12:43:56 +01001270 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001271 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001272 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001273
1274 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1275 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001276 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001277 sw_enforced, hw_enforced, SecLevel(),
1278 cert_chain_[0].encodedCertificate));
1279
1280 CheckedDeleteKey(&key_blob);
1281}
1282
1283/*
1284 * NewKeyGenerationTest.RsaWithSelfSign
1285 *
1286 * Verifies that attesting to RSA key generation is successful, and returns
1287 * self signed certificate if no challenge is provided. And signing etc
1288 * works as expected.
1289 */
1290TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001291 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1292 vector<uint8_t> subject_der(make_name_from_str(subject));
1293
1294 uint64_t serial_int = 0;
1295 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1296
Selene Huang4f64c222021-04-13 19:54:36 -07001297 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1298 vector<uint8_t> key_blob;
1299 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001300 ASSERT_EQ(ErrorCode::OK,
1301 GenerateKey(AuthorizationSetBuilder()
1302 .RsaSigningKey(key_size, 65537)
1303 .Digest(Digest::NONE)
1304 .Padding(PaddingMode::NONE)
1305 .Authorization(TAG_NO_AUTH_REQUIRED)
1306 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1307 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1308 .SetDefaultValidity(),
1309 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001310
1311 ASSERT_GT(key_blob.size(), 0U);
1312 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001313 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001314
1315 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1316
1317 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1318 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1319 << "Key size " << key_size << "missing";
1320 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1321
David Drysdalea8a888e2022-06-08 12:43:56 +01001322 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang6e46f142021-04-20 19:20:11 -07001323 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001324 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001325
1326 CheckedDeleteKey(&key_blob);
1327 }
1328}
1329
1330/*
1331 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1332 *
1333 * Verifies that attesting to RSA checks for missing app ID.
1334 */
1335TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1336 auto challenge = "hello";
1337 vector<uint8_t> key_blob;
1338 vector<KeyCharacteristics> key_characteristics;
1339
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001340 auto builder = AuthorizationSetBuilder()
1341 .RsaSigningKey(2048, 65537)
1342 .Digest(Digest::NONE)
1343 .Padding(PaddingMode::NONE)
1344 .AttestationChallenge(challenge)
1345 .Authorization(TAG_NO_AUTH_REQUIRED)
1346 .SetDefaultValidity();
1347
1348 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001349 // Strongbox may not support factory provisioned attestation key.
1350 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001351 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1352 result = GenerateKeyWithSelfSignedAttestKey(
1353 AuthorizationSetBuilder()
1354 .RsaKey(2048, 65537)
1355 .AttestKey()
1356 .SetDefaultValidity(), /* attest key params */
1357 builder, &key_blob, &key_characteristics);
1358 }
subrahmanyaman05642492022-02-05 07:10:56 +00001359 }
1360 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001361}
1362
1363/*
1364 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1365 *
1366 * Verifies that attesting to RSA ignores app id if challenge is missing.
1367 */
1368TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1369 auto key_size = 2048;
1370 auto app_id = "foo";
1371
Selene Huang6e46f142021-04-20 19:20:11 -07001372 auto subject = "cert subj 2";
1373 vector<uint8_t> subject_der(make_name_from_str(subject));
1374
1375 uint64_t serial_int = 1;
1376 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1377
Selene Huang4f64c222021-04-13 19:54:36 -07001378 vector<uint8_t> key_blob;
1379 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001380 ASSERT_EQ(ErrorCode::OK,
1381 GenerateKey(AuthorizationSetBuilder()
1382 .RsaSigningKey(key_size, 65537)
1383 .Digest(Digest::NONE)
1384 .Padding(PaddingMode::NONE)
1385 .AttestationApplicationId(app_id)
1386 .Authorization(TAG_NO_AUTH_REQUIRED)
1387 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1388 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1389 .SetDefaultValidity(),
1390 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001391
1392 ASSERT_GT(key_blob.size(), 0U);
1393 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001394 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001395
1396 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1397
1398 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1399 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1400 << "Key size " << key_size << "missing";
1401 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1402
David Drysdalea8a888e2022-06-08 12:43:56 +01001403 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001404 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001405 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1406 ASSERT_EQ(cert_chain_.size(), 1);
1407
1408 CheckedDeleteKey(&key_blob);
1409}
1410
1411/*
Qi Wud22ec842020-11-26 13:27:53 +08001412 * NewKeyGenerationTest.LimitedUsageRsa
1413 *
1414 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1415 * resulting keys have correct characteristics.
1416 */
1417TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1418 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1419 vector<uint8_t> key_blob;
1420 vector<KeyCharacteristics> key_characteristics;
1421 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1422 .RsaSigningKey(key_size, 65537)
1423 .Digest(Digest::NONE)
1424 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001425 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1426 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001427 &key_blob, &key_characteristics));
1428
1429 ASSERT_GT(key_blob.size(), 0U);
1430 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001431 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001432
1433 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1434
1435 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1436 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1437 << "Key size " << key_size << "missing";
1438 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1439
1440 // Check the usage count limit tag appears in the authorizations.
1441 AuthorizationSet auths;
1442 for (auto& entry : key_characteristics) {
1443 auths.push_back(AuthorizationSet(entry.authorizations));
1444 }
1445 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1446 << "key usage count limit " << 1U << " missing";
1447
1448 CheckedDeleteKey(&key_blob);
1449 }
1450}
1451
1452/*
Qi Wubeefae42021-01-28 23:16:37 +08001453 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1454 *
1455 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1456 * resulting keys have correct characteristics and attestation.
1457 */
1458TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001459 auto challenge = "hello";
1460 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001461
Selene Huang6e46f142021-04-20 19:20:11 -07001462 auto subject = "cert subj 2";
1463 vector<uint8_t> subject_der(make_name_from_str(subject));
1464
1465 uint64_t serial_int = 66;
1466 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1467
Selene Huang4f64c222021-04-13 19:54:36 -07001468 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001469 vector<uint8_t> key_blob;
1470 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001471 auto builder = AuthorizationSetBuilder()
1472 .RsaSigningKey(key_size, 65537)
1473 .Digest(Digest::NONE)
1474 .Padding(PaddingMode::NONE)
1475 .AttestationChallenge(challenge)
1476 .AttestationApplicationId(app_id)
1477 .Authorization(TAG_NO_AUTH_REQUIRED)
1478 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1479 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1480 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1481 .SetDefaultValidity();
1482
1483 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001484 // Strongbox may not support factory provisioned attestation key.
1485 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001486 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1487 result = GenerateKeyWithSelfSignedAttestKey(
1488 AuthorizationSetBuilder()
1489 .RsaKey(key_size, 65537)
1490 .AttestKey()
1491 .SetDefaultValidity(), /* attest key params */
1492 builder, &key_blob, &key_characteristics);
1493 }
subrahmanyaman05642492022-02-05 07:10:56 +00001494 }
1495 ASSERT_EQ(ErrorCode::OK, result);
Qi Wubeefae42021-01-28 23:16:37 +08001496
1497 ASSERT_GT(key_blob.size(), 0U);
1498 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001499 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001500
1501 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1502
1503 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1504 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1505 << "Key size " << key_size << "missing";
1506 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1507
1508 // Check the usage count limit tag appears in the authorizations.
1509 AuthorizationSet auths;
1510 for (auto& entry : key_characteristics) {
1511 auths.push_back(AuthorizationSet(entry.authorizations));
1512 }
1513 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1514 << "key usage count limit " << 1U << " missing";
1515
1516 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001517 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001518 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001519 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001520
1521 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1522 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001523 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001524 sw_enforced, hw_enforced, SecLevel(),
1525 cert_chain_[0].encodedCertificate));
1526
1527 CheckedDeleteKey(&key_blob);
1528 }
1529}
1530
1531/*
Selene Huang31ab4042020-04-29 04:22:39 -07001532 * NewKeyGenerationTest.NoInvalidRsaSizes
1533 *
1534 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1535 */
1536TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1537 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1538 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001539 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001540 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1541 GenerateKey(AuthorizationSetBuilder()
1542 .RsaSigningKey(key_size, 65537)
1543 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001544 .Padding(PaddingMode::NONE)
1545 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001546 &key_blob, &key_characteristics));
1547 }
1548}
1549
1550/*
1551 * NewKeyGenerationTest.RsaNoDefaultSize
1552 *
1553 * Verifies that failing to specify a key size for RSA key generation returns
1554 * UNSUPPORTED_KEY_SIZE.
1555 */
1556TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1557 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1558 GenerateKey(AuthorizationSetBuilder()
1559 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1560 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001561 .SigningKey()
1562 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001563}
1564
1565/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001566 * NewKeyGenerationTest.RsaMissingParams
1567 *
1568 * Verifies that omitting optional tags works.
1569 */
1570TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1571 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1572 ASSERT_EQ(ErrorCode::OK,
1573 GenerateKey(
1574 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1575 CheckedDeleteKey();
1576 }
1577}
1578
1579/*
Selene Huang31ab4042020-04-29 04:22:39 -07001580 * NewKeyGenerationTest.Ecdsa
1581 *
David Drysdale42fe1892021-10-14 14:43:46 +01001582 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001583 * have correct characteristics.
1584 */
1585TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001586 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001587 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001588 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001589 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001590 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001591 .Digest(Digest::NONE)
1592 .SetDefaultValidity(),
1593 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001594 ASSERT_GT(key_blob.size(), 0U);
1595 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001596 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001597
Shawn Willden7f424372021-01-10 18:06:50 -07001598 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001599
1600 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001601 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001602
1603 CheckedDeleteKey(&key_blob);
1604 }
1605}
1606
1607/*
David Drysdale42fe1892021-10-14 14:43:46 +01001608 * NewKeyGenerationTest.EcdsaCurve25519
1609 *
1610 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1611 * has correct characteristics.
1612 */
1613TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1614 if (!Curve25519Supported()) {
1615 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1616 }
1617
1618 EcCurve curve = EcCurve::CURVE_25519;
1619 vector<uint8_t> key_blob;
1620 vector<KeyCharacteristics> key_characteristics;
1621 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1622 .EcdsaSigningKey(curve)
1623 .Digest(Digest::NONE)
1624 .SetDefaultValidity(),
1625 &key_blob, &key_characteristics);
1626 ASSERT_EQ(result, ErrorCode::OK);
1627 ASSERT_GT(key_blob.size(), 0U);
1628
1629 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1630 ASSERT_GT(cert_chain_.size(), 0);
1631
1632 CheckBaseParams(key_characteristics);
1633 CheckCharacteristics(key_blob, key_characteristics);
1634
1635 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1636
1637 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1638 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1639
1640 CheckedDeleteKey(&key_blob);
1641}
1642
1643/*
1644 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1645 *
1646 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1647 * SIGN and AGREE_KEY.
1648 */
1649TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1650 if (!Curve25519Supported()) {
1651 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1652 }
1653
1654 EcCurve curve = EcCurve::CURVE_25519;
1655 vector<uint8_t> key_blob;
1656 vector<KeyCharacteristics> key_characteristics;
1657 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1658 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1659 .EcdsaSigningKey(curve)
1660 .Digest(Digest::NONE)
1661 .SetDefaultValidity(),
1662 &key_blob, &key_characteristics);
1663 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1664}
1665
1666/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001667 * NewKeyGenerationTest.EcdsaWithMissingValidity
1668 *
1669 * Verifies that keymint returns an error while generating asymmetric key
1670 * without providing NOT_BEFORE and NOT_AFTER parameters.
1671 */
1672TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
1673 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1674 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1675 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1676
1677 vector<uint8_t> key_blob;
1678 vector<KeyCharacteristics> key_characteristics;
1679 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1680 GenerateKey(AuthorizationSetBuilder()
1681 .EcdsaSigningKey(EcCurve::P_256)
1682 .Digest(Digest::NONE)
1683 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1684 kUndefinedExpirationDateTime),
1685 &key_blob, &key_characteristics));
1686
1687 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1688 GenerateKey(AuthorizationSetBuilder()
1689 .EcdsaSigningKey(EcCurve::P_256)
1690 .Digest(Digest::NONE)
1691 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1692 &key_blob, &key_characteristics));
1693}
1694
1695/*
Selene Huang4f64c222021-04-13 19:54:36 -07001696 * NewKeyGenerationTest.EcdsaAttestation
1697 *
1698 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1699 * an attestation will be generated.
1700 */
1701TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1702 auto challenge = "hello";
1703 auto app_id = "foo";
1704
Selene Huang6e46f142021-04-20 19:20:11 -07001705 auto subject = "cert subj 2";
1706 vector<uint8_t> subject_der(make_name_from_str(subject));
1707
1708 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1709 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1710
David Drysdaledf09e542021-06-08 15:46:11 +01001711 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001712 vector<uint8_t> key_blob;
1713 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001714 auto builder = AuthorizationSetBuilder()
1715 .Authorization(TAG_NO_AUTH_REQUIRED)
1716 .EcdsaSigningKey(curve)
1717 .Digest(Digest::NONE)
1718 .AttestationChallenge(challenge)
1719 .AttestationApplicationId(app_id)
1720 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1721 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1722 .SetDefaultValidity();
1723
1724 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001725 // Strongbox may not support factory provisioned attestation key.
1726 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001727 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1728 result = GenerateKeyWithSelfSignedAttestKey(
1729 AuthorizationSetBuilder()
1730 .EcdsaKey(curve)
1731 .AttestKey()
1732 .SetDefaultValidity(), /* attest key params */
1733 builder, &key_blob, &key_characteristics);
1734 }
subrahmanyaman05642492022-02-05 07:10:56 +00001735 }
1736 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001737 ASSERT_GT(key_blob.size(), 0U);
1738 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001739 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001740
1741 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1742
1743 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001744 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001745
1746 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1747 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001748 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001749
1750 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1751 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001752 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001753 sw_enforced, hw_enforced, SecLevel(),
1754 cert_chain_[0].encodedCertificate));
1755
1756 CheckedDeleteKey(&key_blob);
1757 }
1758}
1759
1760/*
David Drysdale42fe1892021-10-14 14:43:46 +01001761 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1762 *
1763 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1764 * an attestation will be generated.
1765 */
1766TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1767 if (!Curve25519Supported()) {
1768 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1769 }
1770
1771 EcCurve curve = EcCurve::CURVE_25519;
1772 auto challenge = "hello";
1773 auto app_id = "foo";
1774
1775 auto subject = "cert subj 2";
1776 vector<uint8_t> subject_der(make_name_from_str(subject));
1777
1778 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1779 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1780
1781 vector<uint8_t> key_blob;
1782 vector<KeyCharacteristics> key_characteristics;
1783 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1784 .Authorization(TAG_NO_AUTH_REQUIRED)
1785 .EcdsaSigningKey(curve)
1786 .Digest(Digest::NONE)
1787 .AttestationChallenge(challenge)
1788 .AttestationApplicationId(app_id)
1789 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1790 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1791 .SetDefaultValidity(),
1792 &key_blob, &key_characteristics);
1793 ASSERT_EQ(ErrorCode::OK, result);
1794 ASSERT_GT(key_blob.size(), 0U);
1795 CheckBaseParams(key_characteristics);
1796 CheckCharacteristics(key_blob, key_characteristics);
1797
1798 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1799
1800 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1801 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1802
1803 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1804 ASSERT_GT(cert_chain_.size(), 0);
1805 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1806
1807 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1808 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1809 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1810 sw_enforced, hw_enforced, SecLevel(),
1811 cert_chain_[0].encodedCertificate));
1812
1813 CheckedDeleteKey(&key_blob);
1814}
1815
1816/*
David Drysdale37af4b32021-05-14 16:46:59 +01001817 * NewKeyGenerationTest.EcdsaAttestationTags
1818 *
1819 * Verifies that creation of an attested ECDSA key includes various tags in the
1820 * attestation extension.
1821 */
1822TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1823 auto challenge = "hello";
1824 auto app_id = "foo";
1825 auto subject = "cert subj 2";
1826 vector<uint8_t> subject_der(make_name_from_str(subject));
1827 uint64_t serial_int = 0x1010;
1828 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1829 const AuthorizationSetBuilder base_builder =
1830 AuthorizationSetBuilder()
1831 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001832 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001833 .Digest(Digest::NONE)
1834 .AttestationChallenge(challenge)
1835 .AttestationApplicationId(app_id)
1836 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1837 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1838 .SetDefaultValidity();
1839
1840 // Various tags that map to fields in the attestation extension ASN.1 schema.
1841 auto extra_tags = AuthorizationSetBuilder()
1842 .Authorization(TAG_ROLLBACK_RESISTANCE)
1843 .Authorization(TAG_EARLY_BOOT_ONLY)
1844 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1845 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1846 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1847 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1848 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1849 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1850 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1851 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1852 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1853 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001854
David Drysdale37af4b32021-05-14 16:46:59 +01001855 for (const KeyParameter& tag : extra_tags) {
1856 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1857 vector<uint8_t> key_blob;
1858 vector<KeyCharacteristics> key_characteristics;
1859 AuthorizationSetBuilder builder = base_builder;
1860 builder.push_back(tag);
1861 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1862 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1863 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1864 continue;
1865 }
Seth Mooreb393b082021-07-12 14:18:28 -07001866 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1867 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001868 continue;
1869 }
subrahmanyaman05642492022-02-05 07:10:56 +00001870 // Strongbox may not support factory provisioned attestation key.
1871 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001872 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1873 result = GenerateKeyWithSelfSignedAttestKey(
1874 AuthorizationSetBuilder()
1875 .EcdsaKey(EcCurve::P_256)
1876 .AttestKey()
1877 .SetDefaultValidity(), /* attest key params */
1878 builder, &key_blob, &key_characteristics);
1879 }
subrahmanyaman05642492022-02-05 07:10:56 +00001880 }
David Drysdale37af4b32021-05-14 16:46:59 +01001881 ASSERT_EQ(result, ErrorCode::OK);
1882 ASSERT_GT(key_blob.size(), 0U);
1883
1884 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1885 ASSERT_GT(cert_chain_.size(), 0);
1886 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1887
1888 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1889 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001890 // Some tags are optional, so don't require them to be in the enforcements.
1891 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001892 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1893 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1894 }
1895
1896 // Verifying the attestation record will check for the specific tag because
1897 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001898 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1899 hw_enforced, SecLevel(),
1900 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01001901
1902 CheckedDeleteKey(&key_blob);
1903 }
1904
David Drysdalec53b7d92021-10-11 12:35:58 +01001905 // Collection of invalid attestation ID tags.
1906 auto invalid_tags =
1907 AuthorizationSetBuilder()
1908 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1909 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1910 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1911 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1912 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
1913 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
1914 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
1915 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01001916 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01001917 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01001918 vector<uint8_t> key_blob;
1919 vector<KeyCharacteristics> key_characteristics;
1920 AuthorizationSetBuilder builder =
1921 AuthorizationSetBuilder()
1922 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001923 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001924 .Digest(Digest::NONE)
1925 .AttestationChallenge(challenge)
1926 .AttestationApplicationId(app_id)
1927 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1928 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1929 .SetDefaultValidity();
1930 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001931
1932 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
1933 // Strongbox may not support factory provisioned attestation key.
1934 if (SecLevel() == SecurityLevel::STRONGBOX) {
1935 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1936 error = GenerateKeyWithSelfSignedAttestKey(
1937 AuthorizationSetBuilder()
1938 .EcdsaKey(EcCurve::P_256)
1939 .AttestKey()
1940 .SetDefaultValidity(), /* attest key params */
1941 builder, &key_blob, &key_characteristics);
1942 }
1943 }
1944 ASSERT_EQ(error, ErrorCode::CANNOT_ATTEST_IDS);
David Drysdale37af4b32021-05-14 16:46:59 +01001945 }
1946}
1947
1948/*
David Drysdalec53b7d92021-10-11 12:35:58 +01001949 * NewKeyGenerationTest.EcdsaAttestationIdTags
1950 *
1951 * Verifies that creation of an attested ECDSA key includes various ID tags in the
1952 * attestation extension.
1953 */
1954TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
David Drysdale555ba002022-05-03 18:48:57 +01001955 if (is_gsi_image()) {
1956 // GSI sets up a standard set of device identifiers that may not match
1957 // the device identifiers held by the device.
1958 GTEST_SKIP() << "Test not applicable under GSI";
1959 }
David Drysdalec53b7d92021-10-11 12:35:58 +01001960 auto challenge = "hello";
1961 auto app_id = "foo";
1962 auto subject = "cert subj 2";
1963 vector<uint8_t> subject_der(make_name_from_str(subject));
1964 uint64_t serial_int = 0x1010;
1965 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1966 const AuthorizationSetBuilder base_builder =
1967 AuthorizationSetBuilder()
1968 .Authorization(TAG_NO_AUTH_REQUIRED)
1969 .EcdsaSigningKey(EcCurve::P_256)
1970 .Digest(Digest::NONE)
1971 .AttestationChallenge(challenge)
1972 .AttestationApplicationId(app_id)
1973 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1974 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1975 .SetDefaultValidity();
1976
1977 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
1978 auto extra_tags = AuthorizationSetBuilder();
1979 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
1980 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
1981 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
1982 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
1983 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
1984 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
1985
1986 for (const KeyParameter& tag : extra_tags) {
1987 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1988 vector<uint8_t> key_blob;
1989 vector<KeyCharacteristics> key_characteristics;
1990 AuthorizationSetBuilder builder = base_builder;
1991 builder.push_back(tag);
1992 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001993 // Strongbox may not support factory provisioned attestation key.
1994 if (SecLevel() == SecurityLevel::STRONGBOX) {
1995 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1996 }
Prashant Patil88ad1892022-03-15 16:31:02 +00001997 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
1998 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01001999 continue;
2000 }
2001 ASSERT_EQ(result, ErrorCode::OK);
2002 ASSERT_GT(key_blob.size(), 0U);
2003
2004 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2005 ASSERT_GT(cert_chain_.size(), 0);
2006 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2007
2008 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2009 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2010
2011 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2012 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2013 // attestation extension should contain them, so make sure the extra tag is added.
2014 hw_enforced.push_back(tag);
2015
2016 // Verifying the attestation record will check for the specific tag because
2017 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002018 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2019 hw_enforced, SecLevel(),
2020 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002021
2022 CheckedDeleteKey(&key_blob);
2023 }
2024}
2025
2026/*
David Drysdale565ccc72021-10-11 12:49:50 +01002027 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2028 *
2029 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2030 */
2031TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2032 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002033 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002034 auto challenge = "hello";
2035 auto subject = "cert subj 2";
2036 vector<uint8_t> subject_der(make_name_from_str(subject));
2037 uint64_t serial_int = 0x1010;
2038 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002039 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002040 AuthorizationSetBuilder()
2041 .Authorization(TAG_NO_AUTH_REQUIRED)
2042 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2043 .EcdsaSigningKey(EcCurve::P_256)
2044 .Digest(Digest::NONE)
2045 .AttestationChallenge(challenge)
2046 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2047 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2048 .AttestationApplicationId(app_id)
2049 .Authorization(TAG_CREATION_DATETIME, datetime)
2050 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002051 if (reset) {
2052 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2053 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002054 auto result = GenerateKey(builder);
2055 if (SecLevel() == SecurityLevel::STRONGBOX) {
2056 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2057 result = GenerateKeyWithSelfSignedAttestKey(
2058 AuthorizationSetBuilder()
2059 .EcdsaKey(EcCurve::P_256)
2060 .AttestKey()
2061 .SetDefaultValidity(), /* attest key params */
2062 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2063 }
2064 }
2065 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002066 ASSERT_GT(key_blob_.size(), 0U);
2067
2068 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2069 ASSERT_GT(cert_chain_.size(), 0);
2070 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2071
2072 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2073 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2074
2075 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002076 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2077 hw_enforced, SecLevel(),
2078 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002079 EXPECT_GT(unique_id->size(), 0);
2080 CheckedDeleteKey();
2081 };
2082
2083 // Generate unique ID
2084 auto app_id = "foo";
2085 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2086 vector<uint8_t> unique_id;
2087 get_unique_id(app_id, cert_date, &unique_id);
2088
2089 // Generating a new key with the same parameters should give the same unique ID.
2090 vector<uint8_t> unique_id2;
2091 get_unique_id(app_id, cert_date, &unique_id2);
2092 EXPECT_EQ(unique_id, unique_id2);
2093
2094 // Generating a new key with a slightly different date should give the same unique ID.
2095 uint64_t rounded_date = cert_date / 2592000000LLU;
2096 uint64_t min_date = rounded_date * 2592000000LLU;
2097 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2098
2099 vector<uint8_t> unique_id3;
2100 get_unique_id(app_id, min_date, &unique_id3);
2101 EXPECT_EQ(unique_id, unique_id3);
2102
2103 vector<uint8_t> unique_id4;
2104 get_unique_id(app_id, max_date, &unique_id4);
2105 EXPECT_EQ(unique_id, unique_id4);
2106
2107 // A different attestation application ID should yield a different unique ID.
2108 auto app_id2 = "different_foo";
2109 vector<uint8_t> unique_id5;
2110 get_unique_id(app_id2, cert_date, &unique_id5);
2111 EXPECT_NE(unique_id, unique_id5);
2112
2113 // A radically different date should yield a different unique ID.
2114 vector<uint8_t> unique_id6;
2115 get_unique_id(app_id, 1611621648000, &unique_id6);
2116 EXPECT_NE(unique_id, unique_id6);
2117
2118 vector<uint8_t> unique_id7;
2119 get_unique_id(app_id, max_date + 1, &unique_id7);
2120 EXPECT_NE(unique_id, unique_id7);
2121
2122 vector<uint8_t> unique_id8;
2123 get_unique_id(app_id, min_date - 1, &unique_id8);
2124 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002125
2126 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2127 vector<uint8_t> unique_id9;
2128 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2129 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002130}
2131
2132/*
David Drysdale37af4b32021-05-14 16:46:59 +01002133 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2134 *
2135 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2136 */
2137TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2138 auto challenge = "hello";
2139 auto attest_app_id = "foo";
2140 auto subject = "cert subj 2";
2141 vector<uint8_t> subject_der(make_name_from_str(subject));
2142 uint64_t serial_int = 0x1010;
2143 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2144
2145 // Earlier versions of the attestation extension schema included a slot:
2146 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2147 // This should never have been included, and should never be filled in.
2148 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2149 // to confirm that this field never makes it into the attestation extension.
2150 vector<uint8_t> key_blob;
2151 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002152 auto builder = AuthorizationSetBuilder()
2153 .Authorization(TAG_NO_AUTH_REQUIRED)
2154 .EcdsaSigningKey(EcCurve::P_256)
2155 .Digest(Digest::NONE)
2156 .AttestationChallenge(challenge)
2157 .AttestationApplicationId(attest_app_id)
2158 .Authorization(TAG_APPLICATION_ID, "client_id")
2159 .Authorization(TAG_APPLICATION_DATA, "appdata")
2160 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2161 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2162 .SetDefaultValidity();
2163
2164 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002165 // Strongbox may not support factory provisioned attestation key.
2166 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002167 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2168 result = GenerateKeyWithSelfSignedAttestKey(
2169 AuthorizationSetBuilder()
2170 .EcdsaKey(EcCurve::P_256)
2171 .AttestKey()
2172 .SetDefaultValidity(), /* attest key params */
2173 builder, &key_blob, &key_characteristics);
2174 }
subrahmanyaman05642492022-02-05 07:10:56 +00002175 }
David Drysdale37af4b32021-05-14 16:46:59 +01002176 ASSERT_EQ(result, ErrorCode::OK);
2177 ASSERT_GT(key_blob.size(), 0U);
2178
2179 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2180 ASSERT_GT(cert_chain_.size(), 0);
2181 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2182
2183 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2184 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002185 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2186 hw_enforced, SecLevel(),
2187 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002188
2189 // Check that the app id is not in the cert.
2190 string app_id = "clientid";
2191 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2192 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2193 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2194 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2195 cert_chain_[0].encodedCertificate.end());
2196
2197 CheckedDeleteKey(&key_blob);
2198}
2199
2200/*
Selene Huang4f64c222021-04-13 19:54:36 -07002201 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2202 *
2203 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2204 * the key will generate a self signed attestation.
2205 */
2206TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002207 auto subject = "cert subj 2";
2208 vector<uint8_t> subject_der(make_name_from_str(subject));
2209
2210 uint64_t serial_int = 0x123456FFF1234;
2211 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2212
David Drysdaledf09e542021-06-08 15:46:11 +01002213 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002214 vector<uint8_t> key_blob;
2215 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002216 ASSERT_EQ(ErrorCode::OK,
2217 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002218 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002219 .Digest(Digest::NONE)
2220 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2221 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2222 .SetDefaultValidity(),
2223 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002224 ASSERT_GT(key_blob.size(), 0U);
2225 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002226 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002227
2228 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2229
2230 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002231 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002232
2233 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2234 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002235 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002236
2237 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2238 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2239
2240 CheckedDeleteKey(&key_blob);
2241 }
2242}
2243
2244/*
2245 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2246 *
2247 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2248 * app id must also be provided or else it will fail.
2249 */
2250TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2251 auto challenge = "hello";
2252 vector<uint8_t> key_blob;
2253 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002254 auto builder = AuthorizationSetBuilder()
2255 .EcdsaSigningKey(EcCurve::P_256)
2256 .Digest(Digest::NONE)
2257 .AttestationChallenge(challenge)
2258 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002259
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002260 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002261 // Strongbox may not support factory provisioned attestation key.
2262 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002263 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2264 result = GenerateKeyWithSelfSignedAttestKey(
2265 AuthorizationSetBuilder()
2266 .EcdsaKey(EcCurve::P_256)
2267 .AttestKey()
2268 .SetDefaultValidity(), /* attest key params */
2269 builder, &key_blob, &key_characteristics);
2270 }
subrahmanyaman05642492022-02-05 07:10:56 +00002271 }
2272 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002273}
2274
2275/*
2276 * NewKeyGenerationTest.EcdsaIgnoreAppId
2277 *
2278 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2279 * any appid will be ignored, and keymint will generate a self sign certificate.
2280 */
2281TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2282 auto app_id = "foo";
2283
David Drysdaledf09e542021-06-08 15:46:11 +01002284 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002285 vector<uint8_t> key_blob;
2286 vector<KeyCharacteristics> key_characteristics;
2287 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002288 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002289 .Digest(Digest::NONE)
2290 .AttestationApplicationId(app_id)
2291 .SetDefaultValidity(),
2292 &key_blob, &key_characteristics));
2293
2294 ASSERT_GT(key_blob.size(), 0U);
2295 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002296 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002297
2298 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2299
2300 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002301 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002302
2303 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2304 ASSERT_EQ(cert_chain_.size(), 1);
2305
2306 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2307 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2308
2309 CheckedDeleteKey(&key_blob);
2310 }
2311}
2312
2313/*
2314 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2315 *
2316 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2317 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2318 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2319 * to specify how many following bytes will be used to encode the length.
2320 */
2321TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2322 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002323 std::vector<uint32_t> app_id_lengths{143, 258};
2324
2325 for (uint32_t length : app_id_lengths) {
2326 const string app_id(length, 'a');
2327 vector<uint8_t> key_blob;
2328 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002329 auto builder = AuthorizationSetBuilder()
2330 .Authorization(TAG_NO_AUTH_REQUIRED)
2331 .EcdsaSigningKey(EcCurve::P_256)
2332 .Digest(Digest::NONE)
2333 .AttestationChallenge(challenge)
2334 .AttestationApplicationId(app_id)
2335 .SetDefaultValidity();
2336
2337 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002338 // Strongbox may not support factory provisioned attestation key.
2339 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002340 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2341 result = GenerateKeyWithSelfSignedAttestKey(
2342 AuthorizationSetBuilder()
2343 .EcdsaKey(EcCurve::P_256)
2344 .AttestKey()
2345 .SetDefaultValidity(), /* attest key params */
2346 builder, &key_blob, &key_characteristics);
2347 }
subrahmanyaman05642492022-02-05 07:10:56 +00002348 }
2349 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002350 ASSERT_GT(key_blob.size(), 0U);
2351 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002352 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002353
2354 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2355
2356 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002357 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002358
2359 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2360 ASSERT_GT(cert_chain_.size(), 0);
2361
2362 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2363 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002364 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002365 sw_enforced, hw_enforced, SecLevel(),
2366 cert_chain_[0].encodedCertificate));
2367
2368 CheckedDeleteKey(&key_blob);
2369 }
2370}
2371
2372/*
Qi Wud22ec842020-11-26 13:27:53 +08002373 * NewKeyGenerationTest.LimitedUsageEcdsa
2374 *
2375 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2376 * resulting keys have correct characteristics.
2377 */
2378TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002379 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08002380 vector<uint8_t> key_blob;
2381 vector<KeyCharacteristics> key_characteristics;
2382 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002383 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002384 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002385 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2386 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002387 &key_blob, &key_characteristics));
2388
2389 ASSERT_GT(key_blob.size(), 0U);
2390 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002391 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002392
2393 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2394
2395 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002396 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002397
2398 // Check the usage count limit tag appears in the authorizations.
2399 AuthorizationSet auths;
2400 for (auto& entry : key_characteristics) {
2401 auths.push_back(AuthorizationSet(entry.authorizations));
2402 }
2403 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2404 << "key usage count limit " << 1U << " missing";
2405
2406 CheckedDeleteKey(&key_blob);
2407 }
2408}
2409
2410/*
Selene Huang31ab4042020-04-29 04:22:39 -07002411 * NewKeyGenerationTest.EcdsaDefaultSize
2412 *
David Drysdaledf09e542021-06-08 15:46:11 +01002413 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002414 * UNSUPPORTED_KEY_SIZE.
2415 */
2416TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2417 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2418 GenerateKey(AuthorizationSetBuilder()
2419 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2420 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002421 .Digest(Digest::NONE)
2422 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002423}
2424
2425/*
David Drysdale42fe1892021-10-14 14:43:46 +01002426 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002427 *
David Drysdale42fe1892021-10-14 14:43:46 +01002428 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002429 * UNSUPPORTED_KEY_SIZE.
2430 */
David Drysdale42fe1892021-10-14 14:43:46 +01002431TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002432 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07002433 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002434 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002435 auto result = GenerateKey(AuthorizationSetBuilder()
2436 .EcdsaSigningKey(curve)
2437 .Digest(Digest::NONE)
2438 .SetDefaultValidity(),
2439 &key_blob, &key_characteristics);
2440 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2441 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002442 }
2443
David Drysdaledf09e542021-06-08 15:46:11 +01002444 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2445 GenerateKey(AuthorizationSetBuilder()
2446 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2447 .Authorization(TAG_KEY_SIZE, 190)
2448 .SigningKey()
2449 .Digest(Digest::NONE)
2450 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002451}
2452
2453/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002454 * NewKeyGenerationTest.EcdsaMissingCurve
2455 *
2456 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
2457 */
2458TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2459 if (AidlVersion() < 2) {
2460 /*
2461 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2462 * However, this was not checked at the time so we can only be strict about checking this
2463 * for implementations of KeyMint version 2 and above.
2464 */
2465 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
2466 }
2467 /* If EC_CURVE not provided, generateKey
2468 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2469 */
2470 auto result = GenerateKey(
2471 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2472 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2473 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2474}
2475
2476/*
Selene Huang31ab4042020-04-29 04:22:39 -07002477 * NewKeyGenerationTest.EcdsaMismatchKeySize
2478 *
2479 * Verifies that specifying mismatched key size and curve for EC key generation returns
2480 * INVALID_ARGUMENT.
2481 */
2482TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002483 if (SecLevel() == SecurityLevel::STRONGBOX) {
2484 GTEST_SKIP() << "Test not applicable to StrongBox device";
2485 }
Selene Huang31ab4042020-04-29 04:22:39 -07002486
David Drysdaledf09e542021-06-08 15:46:11 +01002487 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002488 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002489 .Authorization(TAG_KEY_SIZE, 224)
2490 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002491 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002492 .Digest(Digest::NONE)
2493 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002494 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002495}
2496
2497/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002498 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002499 *
2500 * Verifies that keymint does not support any curve designated as unsupported.
2501 */
2502TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2503 Digest digest;
2504 if (SecLevel() == SecurityLevel::STRONGBOX) {
2505 digest = Digest::SHA_2_256;
2506 } else {
2507 digest = Digest::SHA_2_512;
2508 }
2509 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08002510 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2511 .EcdsaSigningKey(curve)
2512 .Digest(digest)
2513 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002514 << "Failed to generate key on curve: " << curve;
2515 CheckedDeleteKey();
2516 }
2517}
2518
2519/*
2520 * NewKeyGenerationTest.Hmac
2521 *
2522 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2523 * characteristics.
2524 */
2525TEST_P(NewKeyGenerationTest, Hmac) {
2526 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2527 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002528 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002529 constexpr size_t key_size = 128;
2530 ASSERT_EQ(ErrorCode::OK,
2531 GenerateKey(
2532 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2533 TAG_MIN_MAC_LENGTH, 128),
2534 &key_blob, &key_characteristics));
2535
2536 ASSERT_GT(key_blob.size(), 0U);
2537 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002538 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002539
Shawn Willden7f424372021-01-10 18:06:50 -07002540 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2541 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2542 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2543 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002544
2545 CheckedDeleteKey(&key_blob);
2546 }
2547}
2548
2549/*
Selene Huang4f64c222021-04-13 19:54:36 -07002550 * NewKeyGenerationTest.HmacNoAttestation
2551 *
2552 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2553 * and app id are provided.
2554 */
2555TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2556 auto challenge = "hello";
2557 auto app_id = "foo";
2558
2559 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2560 vector<uint8_t> key_blob;
2561 vector<KeyCharacteristics> key_characteristics;
2562 constexpr size_t key_size = 128;
2563 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2564 .HmacKey(key_size)
2565 .Digest(digest)
2566 .AttestationChallenge(challenge)
2567 .AttestationApplicationId(app_id)
2568 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2569 &key_blob, &key_characteristics));
2570
2571 ASSERT_GT(key_blob.size(), 0U);
2572 ASSERT_EQ(cert_chain_.size(), 0);
2573 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002574 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002575
2576 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2577 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2578 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2579 << "Key size " << key_size << "missing";
2580
2581 CheckedDeleteKey(&key_blob);
2582 }
2583}
2584
2585/*
Qi Wud22ec842020-11-26 13:27:53 +08002586 * NewKeyGenerationTest.LimitedUsageHmac
2587 *
2588 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2589 * resulting keys have correct characteristics.
2590 */
2591TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2592 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2593 vector<uint8_t> key_blob;
2594 vector<KeyCharacteristics> key_characteristics;
2595 constexpr size_t key_size = 128;
2596 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2597 .HmacKey(key_size)
2598 .Digest(digest)
2599 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2600 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2601 &key_blob, &key_characteristics));
2602
2603 ASSERT_GT(key_blob.size(), 0U);
2604 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002605 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002606
2607 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2608 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2609 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2610 << "Key size " << key_size << "missing";
2611
2612 // Check the usage count limit tag appears in the authorizations.
2613 AuthorizationSet auths;
2614 for (auto& entry : key_characteristics) {
2615 auths.push_back(AuthorizationSet(entry.authorizations));
2616 }
2617 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2618 << "key usage count limit " << 1U << " missing";
2619
2620 CheckedDeleteKey(&key_blob);
2621 }
2622}
2623
2624/*
Selene Huang31ab4042020-04-29 04:22:39 -07002625 * NewKeyGenerationTest.HmacCheckKeySizes
2626 *
2627 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2628 */
2629TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2630 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2631 if (key_size < 64 || key_size % 8 != 0) {
2632 // To keep this test from being very slow, we only test a random fraction of
2633 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2634 // them, we expect to run ~40 of them in each run.
2635 if (key_size % 8 == 0 || random() % 10 == 0) {
2636 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2637 GenerateKey(AuthorizationSetBuilder()
2638 .HmacKey(key_size)
2639 .Digest(Digest::SHA_2_256)
2640 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2641 << "HMAC key size " << key_size << " invalid";
2642 }
2643 } else {
2644 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2645 .HmacKey(key_size)
2646 .Digest(Digest::SHA_2_256)
2647 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2648 << "Failed to generate HMAC key of size " << key_size;
2649 CheckedDeleteKey();
2650 }
2651 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002652 if (SecLevel() == SecurityLevel::STRONGBOX) {
2653 // STRONGBOX devices must not support keys larger than 512 bits.
2654 size_t key_size = 520;
2655 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2656 GenerateKey(AuthorizationSetBuilder()
2657 .HmacKey(key_size)
2658 .Digest(Digest::SHA_2_256)
2659 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2660 << "HMAC key size " << key_size << " unexpectedly valid";
2661 }
Selene Huang31ab4042020-04-29 04:22:39 -07002662}
2663
2664/*
2665 * NewKeyGenerationTest.HmacCheckMinMacLengths
2666 *
2667 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2668 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2669 * specific MAC length that failed, so reproducing a failed run will be easy.
2670 */
2671TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2672 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2673 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2674 // To keep this test from being very long, we only test a random fraction of
2675 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2676 // we expect to run ~17 of them in each run.
2677 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2678 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2679 GenerateKey(AuthorizationSetBuilder()
2680 .HmacKey(128)
2681 .Digest(Digest::SHA_2_256)
2682 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2683 << "HMAC min mac length " << min_mac_length << " invalid.";
2684 }
2685 } else {
2686 EXPECT_EQ(ErrorCode::OK,
2687 GenerateKey(AuthorizationSetBuilder()
2688 .HmacKey(128)
2689 .Digest(Digest::SHA_2_256)
2690 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2691 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2692 CheckedDeleteKey();
2693 }
2694 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002695
2696 // Minimum MAC length must be no more than 512 bits.
2697 size_t min_mac_length = 520;
2698 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2699 GenerateKey(AuthorizationSetBuilder()
2700 .HmacKey(128)
2701 .Digest(Digest::SHA_2_256)
2702 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2703 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002704}
2705
2706/*
2707 * NewKeyGenerationTest.HmacMultipleDigests
2708 *
2709 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2710 */
2711TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002712 if (SecLevel() == SecurityLevel::STRONGBOX) {
2713 GTEST_SKIP() << "Test not applicable to StrongBox device";
2714 }
Selene Huang31ab4042020-04-29 04:22:39 -07002715
2716 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2717 GenerateKey(AuthorizationSetBuilder()
2718 .HmacKey(128)
2719 .Digest(Digest::SHA1)
2720 .Digest(Digest::SHA_2_256)
2721 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2722}
2723
2724/*
2725 * NewKeyGenerationTest.HmacDigestNone
2726 *
2727 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2728 */
2729TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2730 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2731 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2732 128)));
2733
2734 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2735 GenerateKey(AuthorizationSetBuilder()
2736 .HmacKey(128)
2737 .Digest(Digest::NONE)
2738 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2739}
2740
Selene Huang4f64c222021-04-13 19:54:36 -07002741/*
2742 * NewKeyGenerationTest.AesNoAttestation
2743 *
2744 * Verifies that attestation parameters to AES keys are ignored and generateKey
2745 * will succeed.
2746 */
2747TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2748 auto challenge = "hello";
2749 auto app_id = "foo";
2750
2751 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2752 .Authorization(TAG_NO_AUTH_REQUIRED)
2753 .AesEncryptionKey(128)
2754 .EcbMode()
2755 .Padding(PaddingMode::PKCS7)
2756 .AttestationChallenge(challenge)
2757 .AttestationApplicationId(app_id)));
2758
2759 ASSERT_EQ(cert_chain_.size(), 0);
2760}
2761
2762/*
2763 * NewKeyGenerationTest.TripleDesNoAttestation
2764 *
2765 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2766 * will be successful. No attestation should be generated.
2767 */
2768TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2769 auto challenge = "hello";
2770 auto app_id = "foo";
2771
2772 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2773 .TripleDesEncryptionKey(168)
2774 .BlockMode(BlockMode::ECB)
2775 .Authorization(TAG_NO_AUTH_REQUIRED)
2776 .Padding(PaddingMode::NONE)
2777 .AttestationChallenge(challenge)
2778 .AttestationApplicationId(app_id)));
2779 ASSERT_EQ(cert_chain_.size(), 0);
2780}
2781
Selene Huang31ab4042020-04-29 04:22:39 -07002782INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2783
2784typedef KeyMintAidlTestBase SigningOperationsTest;
2785
2786/*
2787 * SigningOperationsTest.RsaSuccess
2788 *
2789 * Verifies that raw RSA signature operations succeed.
2790 */
2791TEST_P(SigningOperationsTest, RsaSuccess) {
2792 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2793 .RsaSigningKey(2048, 65537)
2794 .Digest(Digest::NONE)
2795 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002796 .Authorization(TAG_NO_AUTH_REQUIRED)
2797 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002798 string message = "12345678901234567890123456789012";
2799 string signature = SignMessage(
2800 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002801 LocalVerifyMessage(message, signature,
2802 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2803}
2804
2805/*
2806 * SigningOperationsTest.RsaAllPaddingsAndDigests
2807 *
2808 * Verifies RSA signature/verification for all padding modes and digests.
2809 */
2810TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2811 auto authorizations = AuthorizationSetBuilder()
2812 .Authorization(TAG_NO_AUTH_REQUIRED)
2813 .RsaSigningKey(2048, 65537)
2814 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2815 .Padding(PaddingMode::NONE)
2816 .Padding(PaddingMode::RSA_PSS)
2817 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2818 .SetDefaultValidity();
2819
2820 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2821
2822 string message(128, 'a');
2823 string corrupt_message(message);
2824 ++corrupt_message[corrupt_message.size() / 2];
2825
2826 for (auto padding :
2827 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2828 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2829 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2830 // Digesting only makes sense with padding.
2831 continue;
2832 }
2833
2834 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2835 // PSS requires digesting.
2836 continue;
2837 }
2838
2839 string signature =
2840 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2841 LocalVerifyMessage(message, signature,
2842 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2843 }
2844 }
Selene Huang31ab4042020-04-29 04:22:39 -07002845}
2846
2847/*
2848 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2849 *
Shawn Willden7f424372021-01-10 18:06:50 -07002850 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002851 */
2852TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2853 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2854 .Authorization(TAG_NO_AUTH_REQUIRED)
2855 .RsaSigningKey(2048, 65537)
2856 .Digest(Digest::NONE)
2857 .Padding(PaddingMode::NONE)
2858 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002859 .Authorization(TAG_APPLICATION_DATA, "appdata")
2860 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002861
2862 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2863
Selene Huang31ab4042020-04-29 04:22:39 -07002864 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2865 Begin(KeyPurpose::SIGN,
2866 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2867 AbortIfNeeded();
2868 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2869 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2870 .Digest(Digest::NONE)
2871 .Padding(PaddingMode::NONE)
2872 .Authorization(TAG_APPLICATION_ID, "clientid")));
2873 AbortIfNeeded();
2874 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2875 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2876 .Digest(Digest::NONE)
2877 .Padding(PaddingMode::NONE)
2878 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2879 AbortIfNeeded();
2880 EXPECT_EQ(ErrorCode::OK,
2881 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2882 .Digest(Digest::NONE)
2883 .Padding(PaddingMode::NONE)
2884 .Authorization(TAG_APPLICATION_DATA, "appdata")
2885 .Authorization(TAG_APPLICATION_ID, "clientid")));
2886 AbortIfNeeded();
2887}
2888
2889/*
2890 * SigningOperationsTest.RsaPssSha256Success
2891 *
2892 * Verifies that RSA-PSS signature operations succeed.
2893 */
2894TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2895 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2896 .RsaSigningKey(2048, 65537)
2897 .Digest(Digest::SHA_2_256)
2898 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002899 .Authorization(TAG_NO_AUTH_REQUIRED)
2900 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002901 // Use large message, which won't work without digesting.
2902 string message(1024, 'a');
2903 string signature = SignMessage(
2904 message,
2905 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2906}
2907
2908/*
2909 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2910 *
2911 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2912 * supports only unpadded operations.
2913 */
2914TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2915 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2916 .RsaSigningKey(2048, 65537)
2917 .Digest(Digest::NONE)
2918 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002919 .Padding(PaddingMode::NONE)
2920 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002921 string message = "12345678901234567890123456789012";
2922 string signature;
2923
2924 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2925 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2926 .Digest(Digest::NONE)
2927 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2928}
2929
2930/*
2931 * SigningOperationsTest.NoUserConfirmation
2932 *
2933 * Verifies that keymint rejects signing operations for keys with
2934 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2935 * presented.
2936 */
2937TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002938 if (SecLevel() == SecurityLevel::STRONGBOX) {
2939 GTEST_SKIP() << "Test not applicable to StrongBox device";
2940 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002941 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2942 .RsaSigningKey(1024, 65537)
2943 .Digest(Digest::NONE)
2944 .Padding(PaddingMode::NONE)
2945 .Authorization(TAG_NO_AUTH_REQUIRED)
2946 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2947 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002948
2949 const string message = "12345678901234567890123456789012";
2950 EXPECT_EQ(ErrorCode::OK,
2951 Begin(KeyPurpose::SIGN,
2952 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2953 string signature;
2954 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2955}
2956
2957/*
2958 * SigningOperationsTest.RsaPkcs1Sha256Success
2959 *
2960 * Verifies that digested RSA-PKCS1 signature operations succeed.
2961 */
2962TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2963 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2964 .RsaSigningKey(2048, 65537)
2965 .Digest(Digest::SHA_2_256)
2966 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002967 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2968 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002969 string message(1024, 'a');
2970 string signature = SignMessage(message, AuthorizationSetBuilder()
2971 .Digest(Digest::SHA_2_256)
2972 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2973}
2974
2975/*
2976 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2977 *
2978 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2979 */
2980TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2981 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2982 .RsaSigningKey(2048, 65537)
2983 .Digest(Digest::NONE)
2984 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002985 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2986 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002987 string message(53, 'a');
2988 string signature = SignMessage(message, AuthorizationSetBuilder()
2989 .Digest(Digest::NONE)
2990 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2991}
2992
2993/*
2994 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2995 *
2996 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2997 * given a too-long message.
2998 */
2999TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3000 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3001 .RsaSigningKey(2048, 65537)
3002 .Digest(Digest::NONE)
3003 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003004 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3005 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003006 string message(257, 'a');
3007
3008 EXPECT_EQ(ErrorCode::OK,
3009 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3010 .Digest(Digest::NONE)
3011 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3012 string signature;
3013 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3014}
3015
3016/*
3017 * SigningOperationsTest.RsaPssSha512TooSmallKey
3018 *
3019 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3020 * used with a key that is too small for the message.
3021 *
3022 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3023 * keymint specification requires that salt_size == digest_size, so the message will be
3024 * digest_size * 2 +
3025 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3026 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3027 * for a 1024-bit key.
3028 */
3029TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003030 if (SecLevel() == SecurityLevel::STRONGBOX) {
3031 GTEST_SKIP() << "Test not applicable to StrongBox device";
3032 }
Selene Huang31ab4042020-04-29 04:22:39 -07003033 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3034 .RsaSigningKey(1024, 65537)
3035 .Digest(Digest::SHA_2_512)
3036 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003037 .Padding(PaddingMode::RSA_PSS)
3038 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003039 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3040 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3041 .Digest(Digest::SHA_2_512)
3042 .Padding(PaddingMode::RSA_PSS)));
3043}
3044
3045/*
3046 * SigningOperationsTest.RsaNoPaddingTooLong
3047 *
3048 * Verifies that raw RSA signature operations fail with the correct error code when
3049 * given a too-long message.
3050 */
3051TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3052 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3053 .RsaSigningKey(2048, 65537)
3054 .Digest(Digest::NONE)
3055 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003056 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3057 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003058 // One byte too long
3059 string message(2048 / 8 + 1, 'a');
3060 ASSERT_EQ(ErrorCode::OK,
3061 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3062 .Digest(Digest::NONE)
3063 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3064 string result;
3065 ErrorCode finish_error_code = Finish(message, &result);
3066 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3067 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3068
3069 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3070 message = string(128 * 1024, 'a');
3071 ASSERT_EQ(ErrorCode::OK,
3072 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3073 .Digest(Digest::NONE)
3074 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3075 finish_error_code = Finish(message, &result);
3076 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3077 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3078}
3079
3080/*
3081 * SigningOperationsTest.RsaAbort
3082 *
3083 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3084 * test, but the behavior should be algorithm and purpose-independent.
3085 */
3086TEST_P(SigningOperationsTest, RsaAbort) {
3087 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3088 .RsaSigningKey(2048, 65537)
3089 .Digest(Digest::NONE)
3090 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003091 .Padding(PaddingMode::NONE)
3092 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003093
3094 ASSERT_EQ(ErrorCode::OK,
3095 Begin(KeyPurpose::SIGN,
3096 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3097 EXPECT_EQ(ErrorCode::OK, Abort());
3098
3099 // Another abort should fail
3100 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3101
3102 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003103 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003104}
3105
3106/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003107 * SigningOperationsTest.RsaNonUniqueParams
3108 *
3109 * Verifies that an operation with multiple padding modes is rejected.
3110 */
3111TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3112 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3113 .RsaSigningKey(2048, 65537)
3114 .Digest(Digest::NONE)
3115 .Digest(Digest::SHA1)
3116 .Authorization(TAG_NO_AUTH_REQUIRED)
3117 .Padding(PaddingMode::NONE)
3118 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3119 .SetDefaultValidity()));
3120
3121 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3122 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3123 .Digest(Digest::NONE)
3124 .Padding(PaddingMode::NONE)
3125 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3126
Tommy Chiuc93c4392021-05-11 18:36:50 +08003127 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3128 .Digest(Digest::NONE)
3129 .Digest(Digest::SHA1)
3130 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3131 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003132
3133 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3134 Begin(KeyPurpose::SIGN,
3135 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3136}
3137
3138/*
Selene Huang31ab4042020-04-29 04:22:39 -07003139 * SigningOperationsTest.RsaUnsupportedPadding
3140 *
3141 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3142 * with a padding mode inappropriate for RSA.
3143 */
3144TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3145 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3146 .RsaSigningKey(2048, 65537)
3147 .Authorization(TAG_NO_AUTH_REQUIRED)
3148 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003149 .Padding(PaddingMode::PKCS7)
3150 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003151 ASSERT_EQ(
3152 ErrorCode::UNSUPPORTED_PADDING_MODE,
3153 Begin(KeyPurpose::SIGN,
3154 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003155 CheckedDeleteKey();
3156
3157 ASSERT_EQ(ErrorCode::OK,
3158 GenerateKey(
3159 AuthorizationSetBuilder()
3160 .RsaSigningKey(2048, 65537)
3161 .Authorization(TAG_NO_AUTH_REQUIRED)
3162 .Digest(Digest::SHA_2_256 /* supported digest */)
3163 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3164 .SetDefaultValidity()));
3165 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3166 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3167 .Digest(Digest::SHA_2_256)
3168 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003169}
3170
3171/*
3172 * SigningOperationsTest.RsaPssNoDigest
3173 *
3174 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3175 */
3176TEST_P(SigningOperationsTest, RsaNoDigest) {
3177 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3178 .RsaSigningKey(2048, 65537)
3179 .Authorization(TAG_NO_AUTH_REQUIRED)
3180 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003181 .Padding(PaddingMode::RSA_PSS)
3182 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003183 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3184 Begin(KeyPurpose::SIGN,
3185 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3186
3187 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3188 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3189}
3190
3191/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003192 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003193 *
3194 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3195 * supported in some cases (as validated in other tests), but a mode must be specified.
3196 */
3197TEST_P(SigningOperationsTest, RsaNoPadding) {
3198 // Padding must be specified
3199 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3200 .RsaKey(2048, 65537)
3201 .Authorization(TAG_NO_AUTH_REQUIRED)
3202 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003203 .Digest(Digest::NONE)
3204 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003205 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3206 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3207}
3208
3209/*
3210 * SigningOperationsTest.RsaShortMessage
3211 *
3212 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3213 */
3214TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3215 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3216 .Authorization(TAG_NO_AUTH_REQUIRED)
3217 .RsaSigningKey(2048, 65537)
3218 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003219 .Padding(PaddingMode::NONE)
3220 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003221
3222 // Barely shorter
3223 string message(2048 / 8 - 1, 'a');
3224 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3225
3226 // Much shorter
3227 message = "a";
3228 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3229}
3230
3231/*
3232 * SigningOperationsTest.RsaSignWithEncryptionKey
3233 *
3234 * Verifies that RSA encryption keys cannot be used to sign.
3235 */
3236TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3237 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3238 .Authorization(TAG_NO_AUTH_REQUIRED)
3239 .RsaEncryptionKey(2048, 65537)
3240 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003241 .Padding(PaddingMode::NONE)
3242 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003243 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3244 Begin(KeyPurpose::SIGN,
3245 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3246}
3247
3248/*
3249 * SigningOperationsTest.RsaSignTooLargeMessage
3250 *
3251 * Verifies that attempting a raw signature of a message which is the same length as the key,
3252 * but numerically larger than the public modulus, fails with the correct error.
3253 */
3254TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3255 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3256 .Authorization(TAG_NO_AUTH_REQUIRED)
3257 .RsaSigningKey(2048, 65537)
3258 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003259 .Padding(PaddingMode::NONE)
3260 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003261
3262 // Largest possible message will always be larger than the public modulus.
3263 string message(2048 / 8, static_cast<char>(0xff));
3264 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3265 .Authorization(TAG_NO_AUTH_REQUIRED)
3266 .Digest(Digest::NONE)
3267 .Padding(PaddingMode::NONE)));
3268 string signature;
3269 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3270}
3271
3272/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003273 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3274 *
David Drysdale42fe1892021-10-14 14:43:46 +01003275 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003276 */
3277TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003278
3279 string message = "1234567890";
3280 string corrupt_message = "2234567890";
3281 for (auto curve : ValidCurves()) {
3282 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003283 // Ed25519 only allows Digest::NONE.
3284 auto digests = (curve == EcCurve::CURVE_25519)
3285 ? std::vector<Digest>(1, Digest::NONE)
3286 : ValidDigests(true /* withNone */, false /* withMD5 */);
3287
David Drysdaledf8f52e2021-05-06 08:10:58 +01003288 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3289 .Authorization(TAG_NO_AUTH_REQUIRED)
3290 .EcdsaSigningKey(curve)
3291 .Digest(digests)
3292 .SetDefaultValidity());
3293 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3294 if (error != ErrorCode::OK) {
3295 continue;
3296 }
3297
3298 for (auto digest : digests) {
3299 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3300 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3301 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3302 }
3303
3304 auto rc = DeleteKey();
3305 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3306 }
3307}
3308
3309/*
Selene Huang31ab4042020-04-29 04:22:39 -07003310 * SigningOperationsTest.EcdsaAllCurves
3311 *
David Drysdale42fe1892021-10-14 14:43:46 +01003312 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003313 */
3314TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3315 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003316 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3317 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003318 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3319 .Authorization(TAG_NO_AUTH_REQUIRED)
3320 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003321 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003322 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003323 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3324 if (error != ErrorCode::OK) continue;
3325
3326 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003327 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003328 CheckedDeleteKey();
3329 }
3330}
3331
3332/*
David Drysdale42fe1892021-10-14 14:43:46 +01003333 * SigningOperationsTest.EcdsaCurve25519
3334 *
3335 * Verifies that ECDSA operations succeed with curve25519.
3336 */
3337TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3338 if (!Curve25519Supported()) {
3339 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3340 }
3341
3342 EcCurve curve = EcCurve::CURVE_25519;
3343 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3344 .Authorization(TAG_NO_AUTH_REQUIRED)
3345 .EcdsaSigningKey(curve)
3346 .Digest(Digest::NONE)
3347 .SetDefaultValidity());
3348 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3349
3350 string message(1024, 'a');
3351 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3352 CheckedDeleteKey();
3353}
3354
3355/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003356 * SigningOperationsTest.EcdsaCurve25519MaxSize
3357 *
3358 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3359 */
3360TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3361 if (!Curve25519Supported()) {
3362 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3363 }
3364
3365 EcCurve curve = EcCurve::CURVE_25519;
3366 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3367 .Authorization(TAG_NO_AUTH_REQUIRED)
3368 .EcdsaSigningKey(curve)
3369 .Digest(Digest::NONE)
3370 .SetDefaultValidity());
3371 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3372
3373 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3374
3375 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3376 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3377 string message(msg_size, 'a');
3378
3379 // Attempt to sign via Begin+Finish.
3380 AuthorizationSet out_params;
3381 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3382 EXPECT_TRUE(out_params.empty());
3383 string signature;
3384 auto result = Finish(message, &signature);
3385 EXPECT_EQ(result, ErrorCode::OK);
3386 LocalVerifyMessage(message, signature, params);
3387
3388 // Attempt to sign via Begin+Update+Finish
3389 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3390 EXPECT_TRUE(out_params.empty());
3391 string output;
3392 result = Update(message, &output);
3393 EXPECT_EQ(result, ErrorCode::OK);
3394 EXPECT_EQ(output.size(), 0);
3395 string signature2;
3396 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3397 LocalVerifyMessage(message, signature2, params);
3398 }
3399
3400 CheckedDeleteKey();
3401}
3402
3403/*
3404 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3405 *
3406 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3407 */
3408TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3409 if (!Curve25519Supported()) {
3410 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3411 }
3412
3413 EcCurve curve = EcCurve::CURVE_25519;
3414 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3415 .Authorization(TAG_NO_AUTH_REQUIRED)
3416 .EcdsaSigningKey(curve)
3417 .Digest(Digest::NONE)
3418 .SetDefaultValidity());
3419 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3420
3421 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3422
3423 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3424 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3425 string message(msg_size, 'a');
3426
3427 // Attempt to sign via Begin+Finish.
3428 AuthorizationSet out_params;
3429 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3430 EXPECT_TRUE(out_params.empty());
3431 string signature;
3432 auto result = Finish(message, &signature);
3433 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3434
3435 // Attempt to sign via Begin+Update (but never get to Finish)
3436 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3437 EXPECT_TRUE(out_params.empty());
3438 string output;
3439 result = Update(message, &output);
3440 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3441 }
3442
3443 CheckedDeleteKey();
3444}
3445
3446/*
Selene Huang31ab4042020-04-29 04:22:39 -07003447 * SigningOperationsTest.EcdsaNoDigestHugeData
3448 *
3449 * Verifies that ECDSA operations support very large messages, even without digesting. This
3450 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3451 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3452 * the framework.
3453 */
3454TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3455 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3456 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003457 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003458 .Digest(Digest::NONE)
3459 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003460 string message(1 * 1024, 'a');
3461 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3462}
3463
3464/*
3465 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3466 *
3467 * Verifies that using an EC key requires the correct app ID/data.
3468 */
3469TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3470 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3471 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003472 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003473 .Digest(Digest::NONE)
3474 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003475 .Authorization(TAG_APPLICATION_DATA, "appdata")
3476 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003477
3478 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3479
Selene Huang31ab4042020-04-29 04:22:39 -07003480 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3481 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3482 AbortIfNeeded();
3483 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3484 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3485 .Digest(Digest::NONE)
3486 .Authorization(TAG_APPLICATION_ID, "clientid")));
3487 AbortIfNeeded();
3488 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3489 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3490 .Digest(Digest::NONE)
3491 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3492 AbortIfNeeded();
3493 EXPECT_EQ(ErrorCode::OK,
3494 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3495 .Digest(Digest::NONE)
3496 .Authorization(TAG_APPLICATION_DATA, "appdata")
3497 .Authorization(TAG_APPLICATION_ID, "clientid")));
3498 AbortIfNeeded();
3499}
3500
3501/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003502 * SigningOperationsTest.EcdsaIncompatibleDigest
3503 *
3504 * Verifies that using an EC key requires compatible digest.
3505 */
3506TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3507 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3508 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003509 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003510 .Digest(Digest::NONE)
3511 .Digest(Digest::SHA1)
3512 .SetDefaultValidity()));
3513 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3514 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3515 AbortIfNeeded();
3516}
3517
3518/*
Selene Huang31ab4042020-04-29 04:22:39 -07003519 * SigningOperationsTest.AesEcbSign
3520 *
3521 * Verifies that attempts to use AES keys to sign fail in the correct way.
3522 */
3523TEST_P(SigningOperationsTest, AesEcbSign) {
3524 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3525 .Authorization(TAG_NO_AUTH_REQUIRED)
3526 .SigningKey()
3527 .AesEncryptionKey(128)
3528 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3529
3530 AuthorizationSet out_params;
3531 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3532 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3533 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3534 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3535}
3536
3537/*
3538 * SigningOperationsTest.HmacAllDigests
3539 *
3540 * Verifies that HMAC works with all digests.
3541 */
3542TEST_P(SigningOperationsTest, HmacAllDigests) {
3543 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
3544 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3545 .Authorization(TAG_NO_AUTH_REQUIRED)
3546 .HmacKey(128)
3547 .Digest(digest)
3548 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3549 << "Failed to create HMAC key with digest " << digest;
3550 string message = "12345678901234567890123456789012";
3551 string signature = MacMessage(message, digest, 160);
3552 EXPECT_EQ(160U / 8U, signature.size())
3553 << "Failed to sign with HMAC key with digest " << digest;
3554 CheckedDeleteKey();
3555 }
3556}
3557
3558/*
3559 * SigningOperationsTest.HmacSha256TooLargeMacLength
3560 *
3561 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3562 * digest size.
3563 */
3564TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3565 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3566 .Authorization(TAG_NO_AUTH_REQUIRED)
3567 .HmacKey(128)
3568 .Digest(Digest::SHA_2_256)
3569 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3570 AuthorizationSet output_params;
3571 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3572 AuthorizationSetBuilder()
3573 .Digest(Digest::SHA_2_256)
3574 .Authorization(TAG_MAC_LENGTH, 264),
3575 &output_params));
3576}
3577
3578/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003579 * SigningOperationsTest.HmacSha256InvalidMacLength
3580 *
3581 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3582 * not a multiple of 8.
3583 */
3584TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3585 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3586 .Authorization(TAG_NO_AUTH_REQUIRED)
3587 .HmacKey(128)
3588 .Digest(Digest::SHA_2_256)
3589 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3590 AuthorizationSet output_params;
3591 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3592 AuthorizationSetBuilder()
3593 .Digest(Digest::SHA_2_256)
3594 .Authorization(TAG_MAC_LENGTH, 161),
3595 &output_params));
3596}
3597
3598/*
Selene Huang31ab4042020-04-29 04:22:39 -07003599 * SigningOperationsTest.HmacSha256TooSmallMacLength
3600 *
3601 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3602 * specified minimum MAC length.
3603 */
3604TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3605 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3606 .Authorization(TAG_NO_AUTH_REQUIRED)
3607 .HmacKey(128)
3608 .Digest(Digest::SHA_2_256)
3609 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3610 AuthorizationSet output_params;
3611 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3612 AuthorizationSetBuilder()
3613 .Digest(Digest::SHA_2_256)
3614 .Authorization(TAG_MAC_LENGTH, 120),
3615 &output_params));
3616}
3617
3618/*
3619 * SigningOperationsTest.HmacRfc4231TestCase3
3620 *
3621 * Validates against the test vectors from RFC 4231 test case 3.
3622 */
3623TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3624 string key(20, 0xaa);
3625 string message(50, 0xdd);
3626 uint8_t sha_224_expected[] = {
3627 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3628 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3629 };
3630 uint8_t sha_256_expected[] = {
3631 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3632 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3633 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3634 };
3635 uint8_t sha_384_expected[] = {
3636 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3637 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3638 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3639 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3640 };
3641 uint8_t sha_512_expected[] = {
3642 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3643 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3644 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3645 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3646 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3647 };
3648
3649 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3650 if (SecLevel() != SecurityLevel::STRONGBOX) {
3651 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3652 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3653 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3654 }
3655}
3656
3657/*
3658 * SigningOperationsTest.HmacRfc4231TestCase5
3659 *
3660 * Validates against the test vectors from RFC 4231 test case 5.
3661 */
3662TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3663 string key(20, 0x0c);
3664 string message = "Test With Truncation";
3665
3666 uint8_t sha_224_expected[] = {
3667 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3668 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3669 };
3670 uint8_t sha_256_expected[] = {
3671 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3672 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3673 };
3674 uint8_t sha_384_expected[] = {
3675 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3676 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3677 };
3678 uint8_t sha_512_expected[] = {
3679 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3680 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3681 };
3682
3683 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3684 if (SecLevel() != SecurityLevel::STRONGBOX) {
3685 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3686 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3687 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3688 }
3689}
3690
3691INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3692
3693typedef KeyMintAidlTestBase VerificationOperationsTest;
3694
3695/*
Selene Huang31ab4042020-04-29 04:22:39 -07003696 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3697 *
3698 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3699 */
3700TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3701 string key_material = "HelloThisIsAKey";
3702
3703 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003704 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003705 EXPECT_EQ(ErrorCode::OK,
3706 ImportKey(AuthorizationSetBuilder()
3707 .Authorization(TAG_NO_AUTH_REQUIRED)
3708 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3709 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3710 .Digest(Digest::SHA_2_256)
3711 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3712 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3713 EXPECT_EQ(ErrorCode::OK,
3714 ImportKey(AuthorizationSetBuilder()
3715 .Authorization(TAG_NO_AUTH_REQUIRED)
3716 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3717 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3718 .Digest(Digest::SHA_2_256)
3719 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3720 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3721
3722 string message = "This is a message.";
3723 string signature = SignMessage(
3724 signing_key, message,
3725 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3726
3727 // Signing key should not work.
3728 AuthorizationSet out_params;
3729 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3730 Begin(KeyPurpose::VERIFY, signing_key,
3731 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3732
3733 // Verification key should work.
3734 VerifyMessage(verification_key, message, signature,
3735 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3736
3737 CheckedDeleteKey(&signing_key);
3738 CheckedDeleteKey(&verification_key);
3739}
3740
Prashant Patildec9fdc2021-12-08 15:25:47 +00003741/*
3742 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3743 *
3744 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3745 */
3746TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3747 string key_material = "HelloThisIsAKey";
3748
3749 vector<uint8_t> signing_key, verification_key;
3750 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3751 EXPECT_EQ(ErrorCode::OK,
3752 ImportKey(AuthorizationSetBuilder()
3753 .Authorization(TAG_NO_AUTH_REQUIRED)
3754 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3755 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3756 .Digest(Digest::SHA_2_256)
3757 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3758 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3759 EXPECT_EQ(ErrorCode::OK,
3760 ImportKey(AuthorizationSetBuilder()
3761 .Authorization(TAG_NO_AUTH_REQUIRED)
3762 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3763 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3764 .Digest(Digest::SHA_2_256)
3765 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3766 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3767
3768 string message = "This is a message.";
3769 string signature = SignMessage(
3770 signing_key, message,
3771 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3772
3773 AuthorizationSet begin_out_params;
3774 ASSERT_EQ(ErrorCode::OK,
3775 Begin(KeyPurpose::VERIFY, verification_key,
3776 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3777
3778 string corruptMessage = "This is b message."; // Corrupted message
3779 string output;
3780 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3781
3782 ASSERT_EQ(ErrorCode::OK,
3783 Begin(KeyPurpose::VERIFY, verification_key,
3784 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3785
3786 signature[0] += 1; // Corrupt a signature
3787 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3788
3789 CheckedDeleteKey(&signing_key);
3790 CheckedDeleteKey(&verification_key);
3791}
3792
Selene Huang31ab4042020-04-29 04:22:39 -07003793INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3794
3795typedef KeyMintAidlTestBase ExportKeyTest;
3796
3797/*
3798 * ExportKeyTest.RsaUnsupportedKeyFormat
3799 *
3800 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3801 */
3802// TODO(seleneh) add ExportKey to GenerateKey
3803// check result
3804
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003805class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003806 public:
3807 template <TagType tag_type, Tag tag, typename ValueT>
3808 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3809 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003810 for (auto& entry : key_characteristics_) {
3811 if (entry.securityLevel == SecLevel()) {
3812 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3813 << "Tag " << tag << " with value " << expected
3814 << " not found at security level" << entry.securityLevel;
3815 } else {
3816 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3817 << "Tag " << tag << " found at security level " << entry.securityLevel;
3818 }
Selene Huang31ab4042020-04-29 04:22:39 -07003819 }
3820 }
3821
3822 void CheckOrigin() {
3823 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003824 // Origin isn't a crypto param, but it always lives with them.
3825 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003826 }
3827};
3828
3829/*
3830 * ImportKeyTest.RsaSuccess
3831 *
3832 * Verifies that importing and using an RSA key pair works correctly.
3833 */
3834TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003835 uint32_t key_size;
3836 string key;
3837
3838 if (SecLevel() == SecurityLevel::STRONGBOX) {
3839 key_size = 2048;
3840 key = rsa_2048_key;
3841 } else {
3842 key_size = 1024;
3843 key = rsa_key;
3844 }
3845
Selene Huang31ab4042020-04-29 04:22:39 -07003846 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3847 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003848 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003849 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003850 .Padding(PaddingMode::RSA_PSS)
3851 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003852 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003853
3854 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003855 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003856 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3857 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3858 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3859 CheckOrigin();
3860
3861 string message(1024 / 8, 'a');
3862 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3863 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003864 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003865}
3866
3867/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003868 * ImportKeyTest.RsaSuccessWithoutParams
3869 *
3870 * Verifies that importing and using an RSA key pair without specifying parameters
3871 * works correctly.
3872 */
3873TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3874 uint32_t key_size;
3875 string key;
3876
3877 if (SecLevel() == SecurityLevel::STRONGBOX) {
3878 key_size = 2048;
3879 key = rsa_2048_key;
3880 } else {
3881 key_size = 1024;
3882 key = rsa_key;
3883 }
3884
3885 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3886 .Authorization(TAG_NO_AUTH_REQUIRED)
3887 .SigningKey()
3888 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3889 .Digest(Digest::SHA_2_256)
3890 .Padding(PaddingMode::RSA_PSS)
3891 .SetDefaultValidity(),
3892 KeyFormat::PKCS8, key));
3893
3894 // Key size and public exponent are determined from the imported key material.
3895 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3896 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3897
3898 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3899 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3900 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3901 CheckOrigin();
3902
3903 string message(1024 / 8, 'a');
3904 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3905 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003906 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003907}
3908
3909/*
Selene Huang31ab4042020-04-29 04:22:39 -07003910 * ImportKeyTest.RsaKeySizeMismatch
3911 *
3912 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3913 * correct way.
3914 */
3915TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3916 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3917 ImportKey(AuthorizationSetBuilder()
3918 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3919 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003920 .Padding(PaddingMode::NONE)
3921 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003922 KeyFormat::PKCS8, rsa_key));
3923}
3924
3925/*
3926 * ImportKeyTest.RsaPublicExponentMismatch
3927 *
3928 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3929 * fails in the correct way.
3930 */
3931TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3932 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3933 ImportKey(AuthorizationSetBuilder()
3934 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3935 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003936 .Padding(PaddingMode::NONE)
3937 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003938 KeyFormat::PKCS8, rsa_key));
3939}
3940
3941/*
David Drysdalee60248c2021-10-04 12:54:13 +01003942 * ImportKeyTest.RsaAttestMultiPurposeFail
3943 *
3944 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
3945 */
3946TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00003947 if (AidlVersion() < 2) {
3948 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
3949 // with other key purposes. However, this was not checked at the time
3950 // so we can only be strict about checking this for implementations of KeyMint
3951 // version 2 and above.
3952 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
3953 }
David Drysdalee60248c2021-10-04 12:54:13 +01003954 uint32_t key_size = 2048;
3955 string key = rsa_2048_key;
3956
3957 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3958 ImportKey(AuthorizationSetBuilder()
3959 .Authorization(TAG_NO_AUTH_REQUIRED)
3960 .RsaSigningKey(key_size, 65537)
3961 .AttestKey()
3962 .Digest(Digest::SHA_2_256)
3963 .Padding(PaddingMode::RSA_PSS)
3964 .SetDefaultValidity(),
3965 KeyFormat::PKCS8, key));
3966}
3967
3968/*
Selene Huang31ab4042020-04-29 04:22:39 -07003969 * ImportKeyTest.EcdsaSuccess
3970 *
3971 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3972 */
3973TEST_P(ImportKeyTest, EcdsaSuccess) {
3974 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3975 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003976 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003977 .Digest(Digest::SHA_2_256)
3978 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003979 KeyFormat::PKCS8, ec_256_key));
3980
3981 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003982 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3983 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3984
3985 CheckOrigin();
3986
3987 string message(32, 'a');
3988 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3989 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003990 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003991}
3992
3993/*
3994 * ImportKeyTest.EcdsaP256RFC5915Success
3995 *
3996 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3997 * correctly.
3998 */
3999TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4000 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4001 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004002 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004003 .Digest(Digest::SHA_2_256)
4004 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004005 KeyFormat::PKCS8, ec_256_key_rfc5915));
4006
4007 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004008 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4009 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4010
4011 CheckOrigin();
4012
4013 string message(32, 'a');
4014 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4015 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004016 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004017}
4018
4019/*
4020 * ImportKeyTest.EcdsaP256SEC1Success
4021 *
4022 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4023 */
4024TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4025 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4026 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004027 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004028 .Digest(Digest::SHA_2_256)
4029 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004030 KeyFormat::PKCS8, ec_256_key_sec1));
4031
4032 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004033 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4034 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4035
4036 CheckOrigin();
4037
4038 string message(32, 'a');
4039 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4040 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004041 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004042}
4043
4044/*
4045 * ImportKeyTest.Ecdsa521Success
4046 *
4047 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4048 */
4049TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004050 if (SecLevel() == SecurityLevel::STRONGBOX) {
4051 GTEST_SKIP() << "Test not applicable to StrongBox device";
4052 }
Selene Huang31ab4042020-04-29 04:22:39 -07004053 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4054 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004055 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004056 .Digest(Digest::SHA_2_256)
4057 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004058 KeyFormat::PKCS8, ec_521_key));
4059
4060 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004061 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4062 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4063 CheckOrigin();
4064
4065 string message(32, 'a');
4066 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4067 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004068 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004069}
4070
4071/*
Selene Huang31ab4042020-04-29 04:22:39 -07004072 * ImportKeyTest.EcdsaCurveMismatch
4073 *
4074 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4075 * the correct way.
4076 */
4077TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4078 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4079 ImportKey(AuthorizationSetBuilder()
4080 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004081 .Digest(Digest::NONE)
4082 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004083 KeyFormat::PKCS8, ec_256_key));
4084}
4085
4086/*
David Drysdalee60248c2021-10-04 12:54:13 +01004087 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4088 *
4089 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4090 */
4091TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004092 if (AidlVersion() < 2) {
4093 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4094 // with other key purposes. However, this was not checked at the time
4095 // so we can only be strict about checking this for implementations of KeyMint
4096 // version 2 and above.
4097 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4098 }
David Drysdalee60248c2021-10-04 12:54:13 +01004099 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4100 ImportKey(AuthorizationSetBuilder()
4101 .Authorization(TAG_NO_AUTH_REQUIRED)
4102 .EcdsaSigningKey(EcCurve::P_256)
4103 .AttestKey()
4104 .Digest(Digest::SHA_2_256)
4105 .SetDefaultValidity(),
4106 KeyFormat::PKCS8, ec_256_key));
4107}
4108
4109/*
David Drysdale42fe1892021-10-14 14:43:46 +01004110 * ImportKeyTest.Ed25519RawSuccess
4111 *
4112 * Verifies that importing and using a raw Ed25519 private key works correctly.
4113 */
4114TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4115 if (!Curve25519Supported()) {
4116 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4117 }
4118
4119 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4120 .Authorization(TAG_NO_AUTH_REQUIRED)
4121 .EcdsaSigningKey(EcCurve::CURVE_25519)
4122 .Digest(Digest::NONE)
4123 .SetDefaultValidity(),
4124 KeyFormat::RAW, ed25519_key));
4125 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4126 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4127 CheckOrigin();
4128
4129 // The returned cert should hold the correct public key.
4130 ASSERT_GT(cert_chain_.size(), 0);
4131 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4132 ASSERT_NE(kmKeyCert, nullptr);
4133 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4134 ASSERT_NE(kmPubKey.get(), nullptr);
4135 size_t kmPubKeySize = 32;
4136 uint8_t kmPubKeyData[32];
4137 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4138 ASSERT_EQ(kmPubKeySize, 32);
4139 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4140
4141 string message(32, 'a');
4142 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4143 string signature = SignMessage(message, params);
4144 LocalVerifyMessage(message, signature, params);
4145}
4146
4147/*
4148 * ImportKeyTest.Ed25519Pkcs8Success
4149 *
4150 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4151 */
4152TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4153 if (!Curve25519Supported()) {
4154 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4155 }
4156
4157 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4158 .Authorization(TAG_NO_AUTH_REQUIRED)
4159 .EcdsaSigningKey(EcCurve::CURVE_25519)
4160 .Digest(Digest::NONE)
4161 .SetDefaultValidity(),
4162 KeyFormat::PKCS8, ed25519_pkcs8_key));
4163 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4164 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4165 CheckOrigin();
4166
4167 // The returned cert should hold the correct public key.
4168 ASSERT_GT(cert_chain_.size(), 0);
4169 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4170 ASSERT_NE(kmKeyCert, nullptr);
4171 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4172 ASSERT_NE(kmPubKey.get(), nullptr);
4173 size_t kmPubKeySize = 32;
4174 uint8_t kmPubKeyData[32];
4175 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4176 ASSERT_EQ(kmPubKeySize, 32);
4177 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4178
4179 string message(32, 'a');
4180 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4181 string signature = SignMessage(message, params);
4182 LocalVerifyMessage(message, signature, params);
4183}
4184
4185/*
4186 * ImportKeyTest.Ed25519CurveMismatch
4187 *
4188 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4189 * the correct way.
4190 */
4191TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4192 if (!Curve25519Supported()) {
4193 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4194 }
4195
4196 ASSERT_NE(ErrorCode::OK,
4197 ImportKey(AuthorizationSetBuilder()
4198 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4199 .Digest(Digest::NONE)
4200 .SetDefaultValidity(),
4201 KeyFormat::RAW, ed25519_key));
4202}
4203
4204/*
4205 * ImportKeyTest.Ed25519FormatMismatch
4206 *
4207 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4208 */
4209TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4210 if (!Curve25519Supported()) {
4211 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4212 }
4213
4214 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4215 .EcdsaSigningKey(EcCurve::CURVE_25519)
4216 .Digest(Digest::NONE)
4217 .SetDefaultValidity(),
4218 KeyFormat::PKCS8, ed25519_key));
4219 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4220 .EcdsaSigningKey(EcCurve::CURVE_25519)
4221 .Digest(Digest::NONE)
4222 .SetDefaultValidity(),
4223 KeyFormat::RAW, ed25519_pkcs8_key));
4224}
4225
4226/*
4227 * ImportKeyTest.Ed25519PurposeMismatch
4228 *
4229 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4230 */
4231TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4232 if (!Curve25519Supported()) {
4233 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4234 }
4235
4236 // Can't have both SIGN and ATTEST_KEY
4237 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4238 .EcdsaSigningKey(EcCurve::CURVE_25519)
4239 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4240 .Digest(Digest::NONE)
4241 .SetDefaultValidity(),
4242 KeyFormat::RAW, ed25519_key));
4243 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4244 // PKCS#8 format and so includes an OID).
4245 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4246 .EcdsaKey(EcCurve::CURVE_25519)
4247 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4248 .Digest(Digest::NONE)
4249 .SetDefaultValidity(),
4250 KeyFormat::PKCS8, ed25519_pkcs8_key));
4251}
4252
4253/*
4254 * ImportKeyTest.X25519RawSuccess
4255 *
4256 * Verifies that importing and using a raw X25519 private key works correctly.
4257 */
4258TEST_P(ImportKeyTest, X25519RawSuccess) {
4259 if (!Curve25519Supported()) {
4260 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4261 }
4262
4263 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4264 .Authorization(TAG_NO_AUTH_REQUIRED)
4265 .EcdsaKey(EcCurve::CURVE_25519)
4266 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4267 .SetDefaultValidity(),
4268 KeyFormat::RAW, x25519_key));
4269
4270 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4271 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4272 CheckOrigin();
4273}
4274
4275/*
4276 * ImportKeyTest.X25519Pkcs8Success
4277 *
4278 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4279 */
4280TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4281 if (!Curve25519Supported()) {
4282 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4283 }
4284
4285 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4286 .Authorization(TAG_NO_AUTH_REQUIRED)
4287 .EcdsaKey(EcCurve::CURVE_25519)
4288 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4289 .SetDefaultValidity(),
4290 KeyFormat::PKCS8, x25519_pkcs8_key));
4291
4292 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4293 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4294 CheckOrigin();
4295}
4296
4297/*
4298 * ImportKeyTest.X25519CurveMismatch
4299 *
4300 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4301 * the correct way.
4302 */
4303TEST_P(ImportKeyTest, X25519CurveMismatch) {
4304 if (!Curve25519Supported()) {
4305 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4306 }
4307
4308 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4309 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4310 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4311 .SetDefaultValidity(),
4312 KeyFormat::RAW, x25519_key));
4313}
4314
4315/*
4316 * ImportKeyTest.X25519FormatMismatch
4317 *
4318 * Verifies that importing an X25519 key with an invalid format fails.
4319 */
4320TEST_P(ImportKeyTest, X25519FormatMismatch) {
4321 if (!Curve25519Supported()) {
4322 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4323 }
4324
4325 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4326 .EcdsaKey(EcCurve::CURVE_25519)
4327 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4328 .SetDefaultValidity(),
4329 KeyFormat::PKCS8, x25519_key));
4330 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4331 .EcdsaKey(EcCurve::CURVE_25519)
4332 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4333 .SetDefaultValidity(),
4334 KeyFormat::RAW, x25519_pkcs8_key));
4335}
4336
4337/*
4338 * ImportKeyTest.X25519PurposeMismatch
4339 *
4340 * Verifies that importing an X25519 key pair with an invalid format fails.
4341 */
4342TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4343 if (!Curve25519Supported()) {
4344 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4345 }
4346
4347 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4348 .EcdsaKey(EcCurve::CURVE_25519)
4349 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4350 .SetDefaultValidity(),
4351 KeyFormat::PKCS8, x25519_pkcs8_key));
4352 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4353 .EcdsaSigningKey(EcCurve::CURVE_25519)
4354 .SetDefaultValidity(),
4355 KeyFormat::PKCS8, x25519_pkcs8_key));
4356}
4357
4358/*
Selene Huang31ab4042020-04-29 04:22:39 -07004359 * ImportKeyTest.AesSuccess
4360 *
4361 * Verifies that importing and using an AES key works.
4362 */
4363TEST_P(ImportKeyTest, AesSuccess) {
4364 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4365 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4366 .Authorization(TAG_NO_AUTH_REQUIRED)
4367 .AesEncryptionKey(key.size() * 8)
4368 .EcbMode()
4369 .Padding(PaddingMode::PKCS7),
4370 KeyFormat::RAW, key));
4371
4372 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4373 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4374 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4375 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4376 CheckOrigin();
4377
4378 string message = "Hello World!";
4379 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4380 string ciphertext = EncryptMessage(message, params);
4381 string plaintext = DecryptMessage(ciphertext, params);
4382 EXPECT_EQ(message, plaintext);
4383}
4384
4385/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004386 * ImportKeyTest.AesFailure
4387 *
4388 * Verifies that importing an invalid AES key fails.
4389 */
4390TEST_P(ImportKeyTest, AesFailure) {
4391 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4392 uint32_t bitlen = key.size() * 8;
4393 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004394 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004395 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004396 .Authorization(TAG_NO_AUTH_REQUIRED)
4397 .AesEncryptionKey(key_size)
4398 .EcbMode()
4399 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004400 KeyFormat::RAW, key);
4401 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004402 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4403 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004404 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004405
4406 // Explicit key size matches that of the provided key, but it's not a valid size.
4407 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4408 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4409 ImportKey(AuthorizationSetBuilder()
4410 .Authorization(TAG_NO_AUTH_REQUIRED)
4411 .AesEncryptionKey(long_key.size() * 8)
4412 .EcbMode()
4413 .Padding(PaddingMode::PKCS7),
4414 KeyFormat::RAW, long_key));
4415 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4416 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4417 ImportKey(AuthorizationSetBuilder()
4418 .Authorization(TAG_NO_AUTH_REQUIRED)
4419 .AesEncryptionKey(short_key.size() * 8)
4420 .EcbMode()
4421 .Padding(PaddingMode::PKCS7),
4422 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004423}
4424
4425/*
4426 * ImportKeyTest.TripleDesSuccess
4427 *
4428 * Verifies that importing and using a 3DES key works.
4429 */
4430TEST_P(ImportKeyTest, TripleDesSuccess) {
4431 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4432 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4433 .Authorization(TAG_NO_AUTH_REQUIRED)
4434 .TripleDesEncryptionKey(168)
4435 .EcbMode()
4436 .Padding(PaddingMode::PKCS7),
4437 KeyFormat::RAW, key));
4438
4439 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4440 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4441 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4442 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4443 CheckOrigin();
4444
4445 string message = "Hello World!";
4446 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4447 string ciphertext = EncryptMessage(message, params);
4448 string plaintext = DecryptMessage(ciphertext, params);
4449 EXPECT_EQ(message, plaintext);
4450}
4451
4452/*
4453 * ImportKeyTest.TripleDesFailure
4454 *
4455 * Verifies that importing an invalid 3DES key fails.
4456 */
4457TEST_P(ImportKeyTest, TripleDesFailure) {
4458 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004459 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004460 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004461 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004462 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004463 .Authorization(TAG_NO_AUTH_REQUIRED)
4464 .TripleDesEncryptionKey(key_size)
4465 .EcbMode()
4466 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004467 KeyFormat::RAW, key);
4468 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004469 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4470 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004471 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004472 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004473 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004474 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4475 ImportKey(AuthorizationSetBuilder()
4476 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004477 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004478 .EcbMode()
4479 .Padding(PaddingMode::PKCS7),
4480 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004481 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004482 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4483 ImportKey(AuthorizationSetBuilder()
4484 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004485 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004486 .EcbMode()
4487 .Padding(PaddingMode::PKCS7),
4488 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004489}
4490
4491/*
4492 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004493 *
4494 * Verifies that importing and using an HMAC key works.
4495 */
4496TEST_P(ImportKeyTest, HmacKeySuccess) {
4497 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4498 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4499 .Authorization(TAG_NO_AUTH_REQUIRED)
4500 .HmacKey(key.size() * 8)
4501 .Digest(Digest::SHA_2_256)
4502 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4503 KeyFormat::RAW, key));
4504
4505 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4506 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4507 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4508 CheckOrigin();
4509
4510 string message = "Hello World!";
4511 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4512 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4513}
4514
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004515/*
4516 * ImportKeyTest.GetKeyCharacteristics
4517 *
4518 * Verifies that imported keys have the correct characteristics.
4519 */
4520TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4521 vector<uint8_t> key_blob;
4522 vector<KeyCharacteristics> key_characteristics;
4523 auto base_builder = AuthorizationSetBuilder()
4524 .Padding(PaddingMode::NONE)
4525 .Authorization(TAG_NO_AUTH_REQUIRED)
4526 .SetDefaultValidity();
4527 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4528 Algorithm::TRIPLE_DES};
4529 ErrorCode result;
4530 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4531 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4532 for (auto alg : algorithms) {
4533 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4534 AuthorizationSetBuilder builder(base_builder);
4535 switch (alg) {
4536 case Algorithm::RSA:
4537 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4538
4539 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4540 &key_characteristics);
4541 break;
4542 case Algorithm::EC:
4543 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4544 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4545 &key_characteristics);
4546 break;
4547 case Algorithm::HMAC:
4548 builder.HmacKey(128)
4549 .Digest(Digest::SHA_2_256)
4550 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4551 result =
4552 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4553 break;
4554 case Algorithm::AES:
4555 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4556 result =
4557 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4558 break;
4559 case Algorithm::TRIPLE_DES:
4560 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4561 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4562 &key_characteristics);
4563 break;
4564 default:
4565 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4566 continue;
4567 }
4568 ASSERT_EQ(ErrorCode::OK, result);
4569 CheckCharacteristics(key_blob, key_characteristics);
4570 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4571 }
4572}
4573
Selene Huang31ab4042020-04-29 04:22:39 -07004574INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4575
4576auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004577 // IKeyMintDevice.aidl
4578 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4579 "020100" // INTEGER length 1 value 0x00 (version)
4580 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4581 "934bf94e2aa28a3f83c9f79297250262"
4582 "fbe3276b5a1c91159bbfa3ef8957aac8"
4583 "4b59b30b455a79c2973480823d8b3863"
4584 "c3deef4a8e243590268d80e18751a0e1"
4585 "30f67ce6a1ace9f79b95e097474febc9"
4586 "81195b1d13a69086c0863f66a7b7fdb4"
4587 "8792227b1ac5e2489febdf087ab54864"
4588 "83033a6f001ca5d1ec1e27f5c30f4cec"
4589 "2642074a39ae68aee552e196627a8e3d"
4590 "867e67a8c01b11e75f13cca0a97ab668"
4591 "b50cda07a8ecb7cd8e3dd7009c963653"
4592 "4f6f239cffe1fc8daa466f78b676c711"
4593 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4594 "99b801597d5220e307eaa5bee507fb94"
4595 "d1fa69f9e519b2de315bac92c36f2ea1"
4596 "fa1df4478c0ddedeae8c70e0233cd098"
4597 "040c" // OCTET STRING length 0x0c (initializationVector)
4598 "d796b02c370f1fa4cc0124f1"
4599 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4600 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4601 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4602 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4603 "3106" // SET length 0x06
4604 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4605 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4606 // } end SET
4607 // } end [1]
4608 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4609 "020120" // INTEGER length 1 value 0x20 (AES)
4610 // } end [2]
4611 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4612 "02020100" // INTEGER length 2 value 0x100
4613 // } end [3]
4614 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4615 "3103" // SET length 0x03 {
4616 "020101" // INTEGER length 1 value 0x01 (ECB)
4617 // } end SET
4618 // } end [4]
4619 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4620 "3103" // SET length 0x03 {
4621 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4622 // } end SET
4623 // } end [5]
4624 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4625 // (noAuthRequired)
4626 "0500" // NULL
4627 // } end [503]
4628 // } end SEQUENCE (AuthorizationList)
4629 // } end SEQUENCE (KeyDescription)
4630 "0420" // OCTET STRING length 0x20 (encryptedKey)
4631 "ccd540855f833a5e1480bfd2d36faf3a"
4632 "eee15df5beabe2691bc82dde2a7aa910"
4633 "0410" // OCTET STRING length 0x10 (tag)
4634 "64c9f689c60ff6223ab6e6999e0eb6e5"
4635 // } SEQUENCE (SecureKeyWrapper)
4636);
Selene Huang31ab4042020-04-29 04:22:39 -07004637
4638auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004639 // IKeyMintDevice.aidl
4640 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4641 "020100" // INTEGER length 1 value 0x00 (version)
4642 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4643 "aad93ed5924f283b4bb5526fbe7a1412"
4644 "f9d9749ec30db9062b29e574a8546f33"
4645 "c88732452f5b8e6a391ee76c39ed1712"
4646 "c61d8df6213dec1cffbc17a8c6d04c7b"
4647 "30893d8daa9b2015213e219468215532"
4648 "07f8f9931c4caba23ed3bee28b36947e"
4649 "47f10e0a5c3dc51c988a628daad3e5e1"
4650 "f4005e79c2d5a96c284b4b8d7e4948f3"
4651 "31e5b85dd5a236f85579f3ea1d1b8484"
4652 "87470bdb0ab4f81a12bee42c99fe0df4"
4653 "bee3759453e69ad1d68a809ce06b949f"
4654 "7694a990429b2fe81e066ff43e56a216"
4655 "02db70757922a4bcc23ab89f1e35da77"
4656 "586775f423e519c2ea394caf48a28d0c"
4657 "8020f1dcf6b3a68ec246f615ae96dae9"
4658 "a079b1f6eb959033c1af5c125fd94168"
4659 "040c" // OCTET STRING length 0x0c (initializationVector)
4660 "6d9721d08589581ab49204a3"
4661 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4662 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4663 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4664 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4665 "3106" // SET length 0x06
4666 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4667 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4668 // } end SET
4669 // } end [1]
4670 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4671 "020120" // INTEGER length 1 value 0x20 (AES)
4672 // } end [2]
4673 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4674 "02020100" // INTEGER length 2 value 0x100
4675 // } end [3]
4676 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4677 "3103" // SET length 0x03 {
4678 "020101" // INTEGER length 1 value 0x01 (ECB)
4679 // } end SET
4680 // } end [4]
4681 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4682 "3103" // SET length 0x03 {
4683 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4684 // } end SET
4685 // } end [5]
4686 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4687 // (noAuthRequired)
4688 "0500" // NULL
4689 // } end [503]
4690 // } end SEQUENCE (AuthorizationList)
4691 // } end SEQUENCE (KeyDescription)
4692 "0420" // OCTET STRING length 0x20 (encryptedKey)
4693 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4694 "c20d1f99a9a024a76f35c8e2cab9b68d"
4695 "0410" // OCTET STRING length 0x10 (tag)
4696 "2560c70109ae67c030f00b98b512a670"
4697 // } SEQUENCE (SecureKeyWrapper)
4698);
Selene Huang31ab4042020-04-29 04:22:39 -07004699
4700auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004701 // RFC 5208 s5
4702 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4703 "020100" // INTEGER length 1 value 0x00 (version)
4704 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4705 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4706 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4707 "0500" // NULL (parameters)
4708 // } SEQUENCE (AlgorithmIdentifier)
4709 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4710 // RFC 8017 A.1.2
4711 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4712 "020100" // INTEGER length 1 value 0x00 (version)
4713 "02820101" // INTEGER length 0x0101 (modulus) value...
4714 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4715 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4716 "7b06e673a837313d56b1c725150a3fef" // 0x30
4717 "86acbddc41bb759c2854eae32d35841e" // 0x40
4718 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4719 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4720 "312d7bd5921ffaea1347c157406fef71" // 0x70
4721 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4722 "f4645c11f5c1374c3886427411c44979" // 0x90
4723 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4724 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4725 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4726 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4727 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4728 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4729 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4730 "55" // 0x101
4731 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4732 "02820100" // INTEGER length 0x100 (privateExponent) value...
4733 "431447b6251908112b1ee76f99f3711a" // 0x10
4734 "52b6630960046c2de70de188d833f8b8" // 0x20
4735 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4736 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4737 "e710b630a03adc683b5d2c43080e52be" // 0x50
4738 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4739 "822bccff087d63c940ba8a45f670feb2" // 0x70
4740 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4741 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4742 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4743 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4744 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4745 "52659d5a5ba05b663737a8696281865b" // 0xd0
4746 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4747 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4748 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4749 "028181" // INTEGER length 0x81 (prime1) value...
4750 "00de392e18d682c829266cc3454e1d61" // 0x10
4751 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4752 "ff841be5bac82a164c5970007047b8c5" // 0x30
4753 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4754 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4755 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4756 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4757 "9e91346130748a6e3c124f9149d71c74" // 0x80
4758 "35"
4759 "028181" // INTEGER length 0x81 (prime2) value...
4760 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4761 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4762 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4763 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4764 "9ed39a2d934c880440aed8832f984316" // 0x50
4765 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4766 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4767 "b880677c068e1be936e81288815252a8" // 0x80
4768 "a1"
4769 "028180" // INTEGER length 0x80 (exponent1) value...
4770 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4771 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4772 "5a063212a4f105a3764743e53281988a" // 0x30
4773 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4774 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4775 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4776 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4777 "4719d6e2b9439823719cd08bcd031781" // 0x80
4778 "028181" // INTEGER length 0x81 (exponent2) value...
4779 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4780 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4781 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4782 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4783 "1254186af30b22c10582a8a43e34fe94" // 0x50
4784 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4785 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4786 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4787 "61"
4788 "028181" // INTEGER length 0x81 (coefficient) value...
4789 "00c931617c77829dfb1270502be9195c" // 0x10
4790 "8f2830885f57dba869536811e6864236" // 0x20
4791 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4792 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4793 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4794 "959356210723287b0affcc9f727044d4" // 0x60
4795 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4796 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4797 "22"
4798 // } SEQUENCE
4799 // } SEQUENCE ()
4800);
Selene Huang31ab4042020-04-29 04:22:39 -07004801
4802string zero_masking_key =
4803 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4804string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4805
4806class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4807
4808TEST_P(ImportWrappedKeyTest, Success) {
4809 auto wrapping_key_desc = AuthorizationSetBuilder()
4810 .RsaEncryptionKey(2048, 65537)
4811 .Digest(Digest::SHA_2_256)
4812 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004813 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4814 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004815
4816 ASSERT_EQ(ErrorCode::OK,
4817 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4818 AuthorizationSetBuilder()
4819 .Digest(Digest::SHA_2_256)
4820 .Padding(PaddingMode::RSA_OAEP)));
4821
4822 string message = "Hello World!";
4823 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4824 string ciphertext = EncryptMessage(message, params);
4825 string plaintext = DecryptMessage(ciphertext, params);
4826 EXPECT_EQ(message, plaintext);
4827}
4828
David Drysdaled2cc8c22021-04-15 13:29:45 +01004829/*
4830 * ImportWrappedKeyTest.SuccessSidsIgnored
4831 *
4832 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
4833 * include Tag:USER_SECURE_ID.
4834 */
4835TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
4836 auto wrapping_key_desc = AuthorizationSetBuilder()
4837 .RsaEncryptionKey(2048, 65537)
4838 .Digest(Digest::SHA_2_256)
4839 .Padding(PaddingMode::RSA_OAEP)
4840 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4841 .SetDefaultValidity();
4842
4843 int64_t password_sid = 42;
4844 int64_t biometric_sid = 24;
4845 ASSERT_EQ(ErrorCode::OK,
4846 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4847 AuthorizationSetBuilder()
4848 .Digest(Digest::SHA_2_256)
4849 .Padding(PaddingMode::RSA_OAEP),
4850 password_sid, biometric_sid));
4851
4852 string message = "Hello World!";
4853 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4854 string ciphertext = EncryptMessage(message, params);
4855 string plaintext = DecryptMessage(ciphertext, params);
4856 EXPECT_EQ(message, plaintext);
4857}
4858
Selene Huang31ab4042020-04-29 04:22:39 -07004859TEST_P(ImportWrappedKeyTest, SuccessMasked) {
4860 auto wrapping_key_desc = AuthorizationSetBuilder()
4861 .RsaEncryptionKey(2048, 65537)
4862 .Digest(Digest::SHA_2_256)
4863 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004864 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4865 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004866
4867 ASSERT_EQ(ErrorCode::OK,
4868 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
4869 AuthorizationSetBuilder()
4870 .Digest(Digest::SHA_2_256)
4871 .Padding(PaddingMode::RSA_OAEP)));
4872}
4873
4874TEST_P(ImportWrappedKeyTest, WrongMask) {
4875 auto wrapping_key_desc = AuthorizationSetBuilder()
4876 .RsaEncryptionKey(2048, 65537)
4877 .Digest(Digest::SHA_2_256)
4878 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004879 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4880 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004881
4882 ASSERT_EQ(
4883 ErrorCode::VERIFICATION_FAILED,
4884 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4885 AuthorizationSetBuilder()
4886 .Digest(Digest::SHA_2_256)
4887 .Padding(PaddingMode::RSA_OAEP)));
4888}
4889
4890TEST_P(ImportWrappedKeyTest, WrongPurpose) {
4891 auto wrapping_key_desc = AuthorizationSetBuilder()
4892 .RsaEncryptionKey(2048, 65537)
4893 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004894 .Padding(PaddingMode::RSA_OAEP)
4895 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004896
4897 ASSERT_EQ(
4898 ErrorCode::INCOMPATIBLE_PURPOSE,
4899 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4900 AuthorizationSetBuilder()
4901 .Digest(Digest::SHA_2_256)
4902 .Padding(PaddingMode::RSA_OAEP)));
4903}
4904
David Drysdaled2cc8c22021-04-15 13:29:45 +01004905TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
4906 auto wrapping_key_desc = AuthorizationSetBuilder()
4907 .RsaEncryptionKey(2048, 65537)
4908 .Digest(Digest::SHA_2_256)
4909 .Padding(PaddingMode::RSA_PSS)
4910 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4911 .SetDefaultValidity();
4912
4913 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
4914 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4915 AuthorizationSetBuilder()
4916 .Digest(Digest::SHA_2_256)
4917 .Padding(PaddingMode::RSA_OAEP)));
4918}
4919
4920TEST_P(ImportWrappedKeyTest, WrongDigest) {
4921 auto wrapping_key_desc = AuthorizationSetBuilder()
4922 .RsaEncryptionKey(2048, 65537)
4923 .Digest(Digest::SHA_2_512)
4924 .Padding(PaddingMode::RSA_OAEP)
4925 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4926 .SetDefaultValidity();
4927
4928 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
4929 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4930 AuthorizationSetBuilder()
4931 .Digest(Digest::SHA_2_256)
4932 .Padding(PaddingMode::RSA_OAEP)));
4933}
4934
Selene Huang31ab4042020-04-29 04:22:39 -07004935INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
4936
4937typedef KeyMintAidlTestBase EncryptionOperationsTest;
4938
4939/*
4940 * EncryptionOperationsTest.RsaNoPaddingSuccess
4941 *
David Drysdale59cae642021-05-12 13:52:03 +01004942 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07004943 */
4944TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00004945 for (uint64_t exponent : ValidExponents()) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01004946 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4947 .Authorization(TAG_NO_AUTH_REQUIRED)
4948 .RsaEncryptionKey(2048, exponent)
4949 .Padding(PaddingMode::NONE)
4950 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004951
David Drysdaled2cc8c22021-04-15 13:29:45 +01004952 string message = string(2048 / 8, 'a');
4953 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004954 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004955 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004956
David Drysdale59cae642021-05-12 13:52:03 +01004957 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004958 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004959
David Drysdaled2cc8c22021-04-15 13:29:45 +01004960 // Unpadded RSA is deterministic
4961 EXPECT_EQ(ciphertext1, ciphertext2);
4962
4963 CheckedDeleteKey();
4964 }
Selene Huang31ab4042020-04-29 04:22:39 -07004965}
4966
4967/*
4968 * EncryptionOperationsTest.RsaNoPaddingShortMessage
4969 *
David Drysdale59cae642021-05-12 13:52:03 +01004970 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07004971 */
4972TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
4973 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4974 .Authorization(TAG_NO_AUTH_REQUIRED)
4975 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004976 .Padding(PaddingMode::NONE)
4977 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004978
4979 string message = "1";
4980 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4981
David Drysdale59cae642021-05-12 13:52:03 +01004982 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004983 EXPECT_EQ(2048U / 8, ciphertext.size());
4984
4985 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
4986 string plaintext = DecryptMessage(ciphertext, params);
4987
4988 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07004989}
4990
4991/*
Selene Huang31ab4042020-04-29 04:22:39 -07004992 * EncryptionOperationsTest.RsaOaepSuccess
4993 *
David Drysdale59cae642021-05-12 13:52:03 +01004994 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07004995 */
4996TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
4997 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4998
4999 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01005000 ASSERT_EQ(ErrorCode::OK,
5001 GenerateKey(AuthorizationSetBuilder()
5002 .Authorization(TAG_NO_AUTH_REQUIRED)
5003 .RsaEncryptionKey(key_size, 65537)
5004 .Padding(PaddingMode::RSA_OAEP)
5005 .Digest(digests)
5006 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
5007 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005008
5009 string message = "Hello";
5010
5011 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005012 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5013
5014 auto params = AuthorizationSetBuilder()
5015 .Digest(digest)
5016 .Padding(PaddingMode::RSA_OAEP)
5017 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5018 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005019 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5020 EXPECT_EQ(key_size / 8, ciphertext1.size());
5021
David Drysdale59cae642021-05-12 13:52:03 +01005022 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005023 EXPECT_EQ(key_size / 8, ciphertext2.size());
5024
5025 // OAEP randomizes padding so every result should be different (with astronomically high
5026 // probability).
5027 EXPECT_NE(ciphertext1, ciphertext2);
5028
5029 string plaintext1 = DecryptMessage(ciphertext1, params);
5030 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5031 string plaintext2 = DecryptMessage(ciphertext2, params);
5032 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5033
5034 // Decrypting corrupted ciphertext should fail.
5035 size_t offset_to_corrupt = random() % ciphertext1.size();
5036 char corrupt_byte;
5037 do {
5038 corrupt_byte = static_cast<char>(random() % 256);
5039 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5040 ciphertext1[offset_to_corrupt] = corrupt_byte;
5041
5042 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5043 string result;
5044 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5045 EXPECT_EQ(0U, result.size());
5046 }
5047}
5048
5049/*
5050 * EncryptionOperationsTest.RsaOaepInvalidDigest
5051 *
David Drysdale59cae642021-05-12 13:52:03 +01005052 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005053 * without a digest.
5054 */
5055TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5056 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5057 .Authorization(TAG_NO_AUTH_REQUIRED)
5058 .RsaEncryptionKey(2048, 65537)
5059 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005060 .Digest(Digest::NONE)
5061 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005062
5063 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005064 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005065}
5066
5067/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005068 * EncryptionOperationsTest.RsaOaepInvalidPadding
5069 *
David Drysdale59cae642021-05-12 13:52:03 +01005070 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005071 * with a padding value that is only suitable for signing/verifying.
5072 */
5073TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5074 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5075 .Authorization(TAG_NO_AUTH_REQUIRED)
5076 .RsaEncryptionKey(2048, 65537)
5077 .Padding(PaddingMode::RSA_PSS)
5078 .Digest(Digest::NONE)
5079 .SetDefaultValidity()));
5080
5081 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005082 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005083}
5084
5085/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005086 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005087 *
David Drysdale59cae642021-05-12 13:52:03 +01005088 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005089 * with a different digest than was used to encrypt.
5090 */
5091TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005092 if (SecLevel() == SecurityLevel::STRONGBOX) {
5093 GTEST_SKIP() << "Test not applicable to StrongBox device";
5094 }
Selene Huang31ab4042020-04-29 04:22:39 -07005095
5096 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5097 .Authorization(TAG_NO_AUTH_REQUIRED)
5098 .RsaEncryptionKey(1024, 65537)
5099 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005100 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5101 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005102 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005103 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005104 message,
5105 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5106
5107 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5108 .Digest(Digest::SHA_2_256)
5109 .Padding(PaddingMode::RSA_OAEP)));
5110 string result;
5111 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5112 EXPECT_EQ(0U, result.size());
5113}
5114
5115/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005116 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5117 *
David Drysdale59cae642021-05-12 13:52:03 +01005118 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005119 * digests.
5120 */
5121TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5122 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5123
5124 size_t key_size = 2048; // Need largish key for SHA-512 test.
5125 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5126 .OaepMGFDigest(digests)
5127 .Authorization(TAG_NO_AUTH_REQUIRED)
5128 .RsaEncryptionKey(key_size, 65537)
5129 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005130 .Digest(Digest::SHA_2_256)
5131 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005132
5133 string message = "Hello";
5134
5135 for (auto digest : digests) {
5136 auto params = AuthorizationSetBuilder()
5137 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5138 .Digest(Digest::SHA_2_256)
5139 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005140 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005141 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5142 EXPECT_EQ(key_size / 8, ciphertext1.size());
5143
David Drysdale59cae642021-05-12 13:52:03 +01005144 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005145 EXPECT_EQ(key_size / 8, ciphertext2.size());
5146
5147 // OAEP randomizes padding so every result should be different (with astronomically high
5148 // probability).
5149 EXPECT_NE(ciphertext1, ciphertext2);
5150
5151 string plaintext1 = DecryptMessage(ciphertext1, params);
5152 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5153 string plaintext2 = DecryptMessage(ciphertext2, params);
5154 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5155
5156 // Decrypting corrupted ciphertext should fail.
5157 size_t offset_to_corrupt = random() % ciphertext1.size();
5158 char corrupt_byte;
5159 do {
5160 corrupt_byte = static_cast<char>(random() % 256);
5161 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5162 ciphertext1[offset_to_corrupt] = corrupt_byte;
5163
5164 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5165 string result;
5166 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5167 EXPECT_EQ(0U, result.size());
5168 }
5169}
5170
5171/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005172 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5173 *
5174 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5175 * specified, defaulting to SHA-1.
5176 */
5177TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5178 size_t key_size = 2048;
5179 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5180 .Authorization(TAG_NO_AUTH_REQUIRED)
5181 .RsaEncryptionKey(key_size, 65537)
5182 .Padding(PaddingMode::RSA_OAEP)
5183 .Digest(Digest::SHA_2_256)
5184 .SetDefaultValidity()));
5185
5186 // Do local RSA encryption using the default MGF digest of SHA-1.
5187 string message = "Hello";
5188 auto params =
5189 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5190 string ciphertext = LocalRsaEncryptMessage(message, params);
5191 EXPECT_EQ(key_size / 8, ciphertext.size());
5192
5193 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5194 string plaintext = DecryptMessage(ciphertext, params);
5195 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5196
5197 // Decrypting corrupted ciphertext should fail.
5198 size_t offset_to_corrupt = random() % ciphertext.size();
5199 char corrupt_byte;
5200 do {
5201 corrupt_byte = static_cast<char>(random() % 256);
5202 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5203 ciphertext[offset_to_corrupt] = corrupt_byte;
5204
5205 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5206 string result;
5207 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5208 EXPECT_EQ(0U, result.size());
5209}
5210
5211/*
5212 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5213 *
5214 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5215 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5216 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5217 */
5218TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5219 size_t key_size = 2048;
5220 ASSERT_EQ(ErrorCode::OK,
5221 GenerateKey(AuthorizationSetBuilder()
5222 .Authorization(TAG_NO_AUTH_REQUIRED)
5223 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5224 .RsaEncryptionKey(key_size, 65537)
5225 .Padding(PaddingMode::RSA_OAEP)
5226 .Digest(Digest::SHA_2_256)
5227 .SetDefaultValidity()));
5228
5229 // Do local RSA encryption using the default MGF digest of SHA-1.
5230 string message = "Hello";
5231 auto params =
5232 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5233 string ciphertext = LocalRsaEncryptMessage(message, params);
5234 EXPECT_EQ(key_size / 8, ciphertext.size());
5235
5236 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5237 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5238 // is checked against those values, and found absent.
5239 auto result = Begin(KeyPurpose::DECRYPT, params);
5240 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5241 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5242}
5243
5244/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005245 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5246 *
David Drysdale59cae642021-05-12 13:52:03 +01005247 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005248 * with incompatible MGF digest.
5249 */
5250TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5251 ASSERT_EQ(ErrorCode::OK,
5252 GenerateKey(AuthorizationSetBuilder()
5253 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5254 .Authorization(TAG_NO_AUTH_REQUIRED)
5255 .RsaEncryptionKey(2048, 65537)
5256 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005257 .Digest(Digest::SHA_2_256)
5258 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005259 string message = "Hello World!";
5260
5261 auto params = AuthorizationSetBuilder()
5262 .Padding(PaddingMode::RSA_OAEP)
5263 .Digest(Digest::SHA_2_256)
5264 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005265 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005266}
5267
5268/*
5269 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5270 *
5271 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5272 * with unsupported MGF digest.
5273 */
5274TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5275 ASSERT_EQ(ErrorCode::OK,
5276 GenerateKey(AuthorizationSetBuilder()
5277 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5278 .Authorization(TAG_NO_AUTH_REQUIRED)
5279 .RsaEncryptionKey(2048, 65537)
5280 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005281 .Digest(Digest::SHA_2_256)
5282 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005283 string message = "Hello World!";
5284
5285 auto params = AuthorizationSetBuilder()
5286 .Padding(PaddingMode::RSA_OAEP)
5287 .Digest(Digest::SHA_2_256)
5288 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005289 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005290}
5291
5292/*
Selene Huang31ab4042020-04-29 04:22:39 -07005293 * EncryptionOperationsTest.RsaPkcs1Success
5294 *
5295 * Verifies that RSA PKCS encryption/decrypts works.
5296 */
5297TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5298 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5299 .Authorization(TAG_NO_AUTH_REQUIRED)
5300 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005301 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5302 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005303
5304 string message = "Hello World!";
5305 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005306 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005307 EXPECT_EQ(2048U / 8, ciphertext1.size());
5308
David Drysdale59cae642021-05-12 13:52:03 +01005309 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005310 EXPECT_EQ(2048U / 8, ciphertext2.size());
5311
5312 // PKCS1 v1.5 randomizes padding so every result should be different.
5313 EXPECT_NE(ciphertext1, ciphertext2);
5314
5315 string plaintext = DecryptMessage(ciphertext1, params);
5316 EXPECT_EQ(message, plaintext);
5317
5318 // Decrypting corrupted ciphertext should fail.
5319 size_t offset_to_corrupt = random() % ciphertext1.size();
5320 char corrupt_byte;
5321 do {
5322 corrupt_byte = static_cast<char>(random() % 256);
5323 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5324 ciphertext1[offset_to_corrupt] = corrupt_byte;
5325
5326 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5327 string result;
5328 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5329 EXPECT_EQ(0U, result.size());
5330}
5331
5332/*
Selene Huang31ab4042020-04-29 04:22:39 -07005333 * EncryptionOperationsTest.EcdsaEncrypt
5334 *
5335 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5336 */
5337TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5338 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5339 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005340 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005341 .Digest(Digest::NONE)
5342 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005343 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5344 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5345 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5346}
5347
5348/*
5349 * EncryptionOperationsTest.HmacEncrypt
5350 *
5351 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5352 */
5353TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5354 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5355 .Authorization(TAG_NO_AUTH_REQUIRED)
5356 .HmacKey(128)
5357 .Digest(Digest::SHA_2_256)
5358 .Padding(PaddingMode::NONE)
5359 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5360 auto params = AuthorizationSetBuilder()
5361 .Digest(Digest::SHA_2_256)
5362 .Padding(PaddingMode::NONE)
5363 .Authorization(TAG_MAC_LENGTH, 128);
5364 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5365 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5366}
5367
5368/*
5369 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5370 *
5371 * Verifies that AES ECB mode works.
5372 */
5373TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5374 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5375 .Authorization(TAG_NO_AUTH_REQUIRED)
5376 .AesEncryptionKey(128)
5377 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5378 .Padding(PaddingMode::NONE)));
5379
5380 ASSERT_GT(key_blob_.size(), 0U);
5381 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5382
5383 // Two-block message.
5384 string message = "12345678901234567890123456789012";
5385 string ciphertext1 = EncryptMessage(message, params);
5386 EXPECT_EQ(message.size(), ciphertext1.size());
5387
5388 string ciphertext2 = EncryptMessage(string(message), params);
5389 EXPECT_EQ(message.size(), ciphertext2.size());
5390
5391 // ECB is deterministic.
5392 EXPECT_EQ(ciphertext1, ciphertext2);
5393
5394 string plaintext = DecryptMessage(ciphertext1, params);
5395 EXPECT_EQ(message, plaintext);
5396}
5397
5398/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005399 * EncryptionOperationsTest.AesEcbUnknownTag
5400 *
5401 * Verifies that AES ECB operations ignore unknown tags.
5402 */
5403TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5404 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5405 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5406 KeyParameter unknown_param;
5407 unknown_param.tag = unknown_tag;
5408
5409 vector<KeyCharacteristics> key_characteristics;
5410 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5411 .Authorization(TAG_NO_AUTH_REQUIRED)
5412 .AesEncryptionKey(128)
5413 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5414 .Padding(PaddingMode::NONE)
5415 .Authorization(unknown_param),
5416 &key_blob_, &key_characteristics));
5417 ASSERT_GT(key_blob_.size(), 0U);
5418
5419 // Unknown tags should not be returned in key characteristics.
5420 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5421 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5422 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5423 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5424
5425 // Encrypt without mentioning the unknown parameter.
5426 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5427 string message = "12345678901234567890123456789012";
5428 string ciphertext = EncryptMessage(message, params);
5429 EXPECT_EQ(message.size(), ciphertext.size());
5430
5431 // Decrypt including the unknown parameter.
5432 auto decrypt_params = AuthorizationSetBuilder()
5433 .BlockMode(BlockMode::ECB)
5434 .Padding(PaddingMode::NONE)
5435 .Authorization(unknown_param);
5436 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5437 EXPECT_EQ(message, plaintext);
5438}
5439
5440/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005441 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005442 *
5443 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5444 */
5445TEST_P(EncryptionOperationsTest, AesWrongMode) {
5446 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5447 .Authorization(TAG_NO_AUTH_REQUIRED)
5448 .AesEncryptionKey(128)
5449 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5450 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005451 ASSERT_GT(key_blob_.size(), 0U);
5452
Selene Huang31ab4042020-04-29 04:22:39 -07005453 EXPECT_EQ(
5454 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5455 Begin(KeyPurpose::ENCRYPT,
5456 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5457}
5458
5459/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005460 * EncryptionOperationsTest.AesWrongPadding
5461 *
5462 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5463 */
5464TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5465 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5466 .Authorization(TAG_NO_AUTH_REQUIRED)
5467 .AesEncryptionKey(128)
5468 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5469 .Padding(PaddingMode::NONE)));
5470 ASSERT_GT(key_blob_.size(), 0U);
5471
5472 EXPECT_EQ(
5473 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5474 Begin(KeyPurpose::ENCRYPT,
5475 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5476}
5477
5478/*
5479 * EncryptionOperationsTest.AesInvalidParams
5480 *
5481 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5482 */
5483TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5484 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5485 .Authorization(TAG_NO_AUTH_REQUIRED)
5486 .AesEncryptionKey(128)
5487 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5488 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5489 .Padding(PaddingMode::NONE)
5490 .Padding(PaddingMode::PKCS7)));
5491 ASSERT_GT(key_blob_.size(), 0U);
5492
5493 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5494 .BlockMode(BlockMode::CBC)
5495 .BlockMode(BlockMode::ECB)
5496 .Padding(PaddingMode::NONE));
5497 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5498 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5499
5500 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5501 .BlockMode(BlockMode::ECB)
5502 .Padding(PaddingMode::NONE)
5503 .Padding(PaddingMode::PKCS7));
5504 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5505 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5506}
5507
5508/*
Selene Huang31ab4042020-04-29 04:22:39 -07005509 * EncryptionOperationsTest.AesWrongPurpose
5510 *
5511 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5512 * specified.
5513 */
5514TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5515 auto err = GenerateKey(AuthorizationSetBuilder()
5516 .Authorization(TAG_NO_AUTH_REQUIRED)
5517 .AesKey(128)
5518 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5519 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5520 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5521 .Padding(PaddingMode::NONE));
5522 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5523 ASSERT_GT(key_blob_.size(), 0U);
5524
5525 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5526 .BlockMode(BlockMode::GCM)
5527 .Padding(PaddingMode::NONE)
5528 .Authorization(TAG_MAC_LENGTH, 128));
5529 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5530
5531 CheckedDeleteKey();
5532
5533 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5534 .Authorization(TAG_NO_AUTH_REQUIRED)
5535 .AesKey(128)
5536 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5537 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5538 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5539 .Padding(PaddingMode::NONE)));
5540
5541 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5542 .BlockMode(BlockMode::GCM)
5543 .Padding(PaddingMode::NONE)
5544 .Authorization(TAG_MAC_LENGTH, 128));
5545 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5546}
5547
5548/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005549 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005550 *
5551 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5552 * multiple of the block size and no padding is specified.
5553 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005554TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5555 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5556 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5557 .Authorization(TAG_NO_AUTH_REQUIRED)
5558 .AesEncryptionKey(128)
5559 .Authorization(TAG_BLOCK_MODE, blockMode)
5560 .Padding(PaddingMode::NONE)));
5561 // Message is slightly shorter than two blocks.
5562 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005563
David Drysdaled2cc8c22021-04-15 13:29:45 +01005564 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5565 AuthorizationSet out_params;
5566 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5567 string ciphertext;
5568 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5569 EXPECT_EQ(0U, ciphertext.size());
5570
5571 CheckedDeleteKey();
5572 }
Selene Huang31ab4042020-04-29 04:22:39 -07005573}
5574
5575/*
5576 * EncryptionOperationsTest.AesEcbPkcs7Padding
5577 *
5578 * Verifies that AES PKCS7 padding works for any message length.
5579 */
5580TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5581 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5582 .Authorization(TAG_NO_AUTH_REQUIRED)
5583 .AesEncryptionKey(128)
5584 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5585 .Padding(PaddingMode::PKCS7)));
5586
5587 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5588
5589 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005590 for (size_t i = 0; i <= 48; i++) {
5591 SCOPED_TRACE(testing::Message() << "i = " << i);
5592 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5593 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005594 string ciphertext = EncryptMessage(message, params);
5595 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5596 string plaintext = DecryptMessage(ciphertext, params);
5597 EXPECT_EQ(message, plaintext);
5598 }
5599}
5600
5601/*
5602 * EncryptionOperationsTest.AesEcbWrongPadding
5603 *
5604 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5605 * specified.
5606 */
5607TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5608 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5609 .Authorization(TAG_NO_AUTH_REQUIRED)
5610 .AesEncryptionKey(128)
5611 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5612 .Padding(PaddingMode::NONE)));
5613
5614 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5615
5616 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005617 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005618 string message(i, 'a');
5619 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5620 }
5621}
5622
5623/*
5624 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5625 *
5626 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5627 */
5628TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5629 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5630 .Authorization(TAG_NO_AUTH_REQUIRED)
5631 .AesEncryptionKey(128)
5632 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5633 .Padding(PaddingMode::PKCS7)));
5634
5635 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5636
5637 string message = "a";
5638 string ciphertext = EncryptMessage(message, params);
5639 EXPECT_EQ(16U, ciphertext.size());
5640 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005641
Seth Moore7a55ae32021-06-23 14:28:11 -07005642 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5643 ++ciphertext[ciphertext.size() / 2];
5644
5645 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5646 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005647 ErrorCode error = Finish(ciphertext, &plaintext);
5648 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005649 // This is the expected error, we can exit the test now.
5650 return;
5651 } else {
5652 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005653 ASSERT_EQ(error, ErrorCode::OK)
5654 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005655 }
5656 }
5657 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005658}
5659
David Drysdaleb8093292022-04-08 12:22:35 +01005660/*
5661 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5662 *
5663 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5664 */
5665TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5666 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5667 .Authorization(TAG_NO_AUTH_REQUIRED)
5668 .AesEncryptionKey(128)
5669 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5670 .Padding(PaddingMode::PKCS7)));
5671
5672 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5673
5674 string message = "a";
5675 string ciphertext = EncryptMessage(message, params);
5676 EXPECT_EQ(16U, ciphertext.size());
5677 EXPECT_NE(ciphertext, message);
5678
5679 // Shorten the ciphertext.
5680 ciphertext.resize(ciphertext.size() - 1);
5681 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5682 string plaintext;
5683 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5684}
5685
Selene Huang31ab4042020-04-29 04:22:39 -07005686vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5687 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005688 EXPECT_TRUE(iv);
5689 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005690}
5691
5692/*
5693 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5694 *
5695 * Verifies that AES CTR mode works.
5696 */
5697TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5698 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5699 .Authorization(TAG_NO_AUTH_REQUIRED)
5700 .AesEncryptionKey(128)
5701 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5702 .Padding(PaddingMode::NONE)));
5703
5704 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5705
5706 string message = "123";
5707 AuthorizationSet out_params;
5708 string ciphertext1 = EncryptMessage(message, params, &out_params);
5709 vector<uint8_t> iv1 = CopyIv(out_params);
5710 EXPECT_EQ(16U, iv1.size());
5711
5712 EXPECT_EQ(message.size(), ciphertext1.size());
5713
5714 out_params.Clear();
5715 string ciphertext2 = EncryptMessage(message, params, &out_params);
5716 vector<uint8_t> iv2 = CopyIv(out_params);
5717 EXPECT_EQ(16U, iv2.size());
5718
5719 // IVs should be random, so ciphertexts should differ.
5720 EXPECT_NE(ciphertext1, ciphertext2);
5721
5722 auto params_iv1 =
5723 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5724 auto params_iv2 =
5725 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5726
5727 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5728 EXPECT_EQ(message, plaintext);
5729 plaintext = DecryptMessage(ciphertext2, params_iv2);
5730 EXPECT_EQ(message, plaintext);
5731
5732 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5733 plaintext = DecryptMessage(ciphertext1, params_iv2);
5734 EXPECT_NE(message, plaintext);
5735 plaintext = DecryptMessage(ciphertext2, params_iv1);
5736 EXPECT_NE(message, plaintext);
5737}
5738
5739/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305740 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07005741 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305742 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07005743 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305744TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5745 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5746}
Selene Huang31ab4042020-04-29 04:22:39 -07005747
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305748/*
5749 * EncryptionOperationsTest.AesCbcIncremental
5750 *
5751 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5752 */
5753TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5754 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5755}
Selene Huang31ab4042020-04-29 04:22:39 -07005756
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305757/*
5758 * EncryptionOperationsTest.AesCtrIncremental
5759 *
5760 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5761 */
5762TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5763 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5764}
Selene Huang31ab4042020-04-29 04:22:39 -07005765
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305766/*
5767 * EncryptionOperationsTest.AesGcmIncremental
5768 *
5769 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5770 */
5771TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5772 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07005773}
5774
Prashant Patildd5f7f02022-07-06 18:58:07 +00005775/*
5776 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
5777 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5778 */
5779TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
5780 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
5781 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
5782 string kat_plaintext =
5783 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
5784 "809FFF37081C22EF278F896AB213A2A631");
5785 string kat_ciphertext =
5786 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
5787 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
5788 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5789 kat_ciphertext);
5790}
5791
5792/*
5793 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
5794 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5795 */
5796TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
5797 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
5798 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
5799 string kat_plaintext =
5800 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
5801 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
5802 string kat_ciphertext =
5803 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
5804 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
5805 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
5806 kat_plaintext, kat_ciphertext);
5807}
5808
5809/*
5810 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
5811 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
5812 */
5813TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
5814 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
5815 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
5816 string kat_plaintext =
5817 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
5818 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
5819 string kat_ciphertext =
5820 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
5821 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
5822 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
5823 kat_ciphertext);
5824}
5825
5826/*
5827 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
5828 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
5829 */
5830TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
5831 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
5832 string kat_plaintext =
5833 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
5834 "7B6168A9A27BCE554BEA94EF26E6C742A0");
5835 string kat_ciphertext =
5836 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
5837 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
5838 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
5839 kat_ciphertext);
5840}
5841
5842/*
5843 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
5844 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
5845 */
5846TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
5847 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
5848 string kat_plaintext =
5849 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
5850 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
5851 string kat_ciphertext =
5852 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
5853 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
5854 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
5855 kat_ciphertext);
5856}
5857
5858/*
5859 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
5860 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
5861 */
5862TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
5863 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
5864 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
5865 string kat_plaintext =
5866 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
5867 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
5868 string kat_ciphertext =
5869 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
5870 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
5871 "bdfcc0cba0");
5872
5873 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
5874 kat_ciphertext);
5875}
5876
5877/*
5878 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
5879 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5880 */
5881TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
5882 if (SecLevel() == SecurityLevel::STRONGBOX) {
5883 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5884 }
5885 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
5886 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
5887 string kat_plaintext =
5888 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
5889 "167f2497c994bd496eb80bfb2ba2c9d5af");
5890 string kat_ciphertext =
5891 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
5892 "72c134552f3a138e726fbe493b3a839598");
5893 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5894 kat_ciphertext);
5895}
5896
5897/*
5898 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
5899 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5900 */
5901TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
5902 if (SecLevel() == SecurityLevel::STRONGBOX) {
5903 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5904 }
5905 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
5906 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
5907 string kat_plaintext =
5908 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
5909 "b170");
5910 string kat_ciphertext =
5911 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
5912 "4e3884138ff403a41fd99818708ada301c");
5913 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
5914 kat_plaintext, kat_ciphertext);
5915}
5916
5917/*
5918 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
5919 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
5920 */
5921TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
5922 if (SecLevel() == SecurityLevel::STRONGBOX) {
5923 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5924 }
5925 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
5926 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
5927 string kat_plaintext =
5928 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
5929 "28091e09cdbbd3b42b");
5930 string kat_ciphertext =
5931 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
5932 "2ae0f90f0c19f42b4a");
5933 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
5934 kat_ciphertext);
5935}
5936
5937/*
5938 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
5939 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
5940 */
5941TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
5942 if (SecLevel() == SecurityLevel::STRONGBOX) {
5943 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5944 }
5945 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
5946 string kat_plaintext =
5947 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
5948 "44ab");
5949 string kat_ciphertext =
5950 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
5951 "2453");
5952 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
5953 kat_ciphertext);
5954}
5955
5956/*
5957 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
5958 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
5959 */
5960TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
5961 if (SecLevel() == SecurityLevel::STRONGBOX) {
5962 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5963 }
5964 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
5965 string kat_plaintext =
5966 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
5967 "e2c7");
5968 string kat_ciphertext =
5969 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
5970 "bb7e3a889dd4a9589098b44acf1056e7aa");
5971 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
5972 kat_ciphertext);
5973}
5974
5975/*
5976 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
5977 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
5978 */
5979TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
5980 if (SecLevel() == SecurityLevel::STRONGBOX) {
5981 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5982 }
5983 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
5984 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
5985 string kat_plaintext =
5986 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
5987 "ff52");
5988 string kat_ciphertext =
5989 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
5990 "1413ad70fb0e1970669095ad77ebb5974ae8");
5991
5992 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
5993 kat_ciphertext);
5994}
5995
5996/*
5997 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
5998 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5999 */
6000TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6001 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6002 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6003 string kat_plaintext =
6004 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6005 "494cb53caca353e4b637ba05687be20f8d");
6006 string kat_ciphertext =
6007 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6008 "6047da1e4fd7c4e1cf2656097f75ae8685");
6009 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6010 kat_ciphertext);
6011}
6012
6013/*
6014 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6015 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6016 */
6017TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6018 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6019 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6020 string kat_plaintext =
6021 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6022 "2545a82b73c48078b9dae62261c65909");
6023 string kat_ciphertext =
6024 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6025 "9403a71987b95124073d69f2a3cb95b0ab");
6026 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6027 kat_plaintext, kat_ciphertext);
6028}
6029
6030/*
6031 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6032 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6033 */
6034TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6035 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6036 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6037 string kat_plaintext =
6038 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6039 "1f6db3c884");
6040 string kat_ciphertext =
6041 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6042 "a7be30d4c3");
6043 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6044 kat_ciphertext);
6045}
6046
6047/*
6048 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6049 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6050 */
6051TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6052 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6053 string kat_plaintext =
6054 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6055 "31a476d6806b8116089c6ec50bb543200f");
6056 string kat_ciphertext =
6057 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6058 "c83e377faf246288931136bef2a07c0be4");
6059 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6060 kat_ciphertext);
6061}
6062
6063/*
6064 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6065 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6066 */
6067TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6068 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6069 string kat_plaintext =
6070 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6071 "6f");
6072 string kat_ciphertext =
6073 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6074 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6075 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6076 kat_ciphertext);
6077}
6078
6079/*
6080 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6081 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6082 */
6083TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6084 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6085 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6086 string kat_plaintext =
6087 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6088 "f0");
6089 string kat_ciphertext =
6090 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6091 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6092
6093 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6094 kat_ciphertext);
6095}
6096
Selene Huang31ab4042020-04-29 04:22:39 -07006097struct AesCtrSp80038aTestVector {
6098 const char* key;
6099 const char* nonce;
6100 const char* plaintext;
6101 const char* ciphertext;
6102};
6103
6104// These test vectors are taken from
6105// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6106static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6107 // AES-128
6108 {
6109 "2b7e151628aed2a6abf7158809cf4f3c",
6110 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6111 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6112 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6113 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6114 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6115 },
6116 // AES-192
6117 {
6118 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6119 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6120 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6121 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6122 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6123 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6124 },
6125 // AES-256
6126 {
6127 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6128 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6129 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6130 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6131 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6132 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6133 },
6134};
6135
6136/*
6137 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6138 *
6139 * Verifies AES CTR implementation against SP800-38A test vectors.
6140 */
6141TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6142 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6143 for (size_t i = 0; i < 3; i++) {
6144 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6145 const string key = hex2str(test.key);
6146 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6147 InvalidSizes.end())
6148 continue;
6149 const string nonce = hex2str(test.nonce);
6150 const string plaintext = hex2str(test.plaintext);
6151 const string ciphertext = hex2str(test.ciphertext);
6152 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6153 }
6154}
6155
6156/*
6157 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6158 *
6159 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6160 */
6161TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6162 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6163 .Authorization(TAG_NO_AUTH_REQUIRED)
6164 .AesEncryptionKey(128)
6165 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6166 .Padding(PaddingMode::PKCS7)));
6167 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6168 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6169}
6170
6171/*
6172 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6173 *
6174 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6175 */
6176TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6177 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6178 .Authorization(TAG_NO_AUTH_REQUIRED)
6179 .AesEncryptionKey(128)
6180 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6181 .Authorization(TAG_CALLER_NONCE)
6182 .Padding(PaddingMode::NONE)));
6183
6184 auto params = AuthorizationSetBuilder()
6185 .BlockMode(BlockMode::CTR)
6186 .Padding(PaddingMode::NONE)
6187 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6188 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6189
6190 params = AuthorizationSetBuilder()
6191 .BlockMode(BlockMode::CTR)
6192 .Padding(PaddingMode::NONE)
6193 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6194 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6195
6196 params = AuthorizationSetBuilder()
6197 .BlockMode(BlockMode::CTR)
6198 .Padding(PaddingMode::NONE)
6199 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6200 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6201}
6202
6203/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006204 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006205 *
6206 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6207 */
6208TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6209 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6210 .Authorization(TAG_NO_AUTH_REQUIRED)
6211 .AesEncryptionKey(128)
6212 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6213 .Padding(PaddingMode::NONE)));
6214 // Two-block message.
6215 string message = "12345678901234567890123456789012";
6216 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6217 AuthorizationSet out_params;
6218 string ciphertext1 = EncryptMessage(message, params, &out_params);
6219 vector<uint8_t> iv1 = CopyIv(out_params);
6220 EXPECT_EQ(message.size(), ciphertext1.size());
6221
6222 out_params.Clear();
6223
6224 string ciphertext2 = EncryptMessage(message, params, &out_params);
6225 vector<uint8_t> iv2 = CopyIv(out_params);
6226 EXPECT_EQ(message.size(), ciphertext2.size());
6227
6228 // IVs should be random, so ciphertexts should differ.
6229 EXPECT_NE(ciphertext1, ciphertext2);
6230
6231 params.push_back(TAG_NONCE, iv1);
6232 string plaintext = DecryptMessage(ciphertext1, params);
6233 EXPECT_EQ(message, plaintext);
6234}
6235
6236/*
Tommy Chiuee705692021-09-23 20:09:13 +08006237 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6238 *
6239 * Verifies that keymaster generates correct output on zero-input with
6240 * NonePadding mode
6241 */
6242TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6243 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6244 .Authorization(TAG_NO_AUTH_REQUIRED)
6245 .AesEncryptionKey(128)
6246 .BlockMode(BlockMode::CBC)
6247 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6248
6249 // Zero input message
6250 string message = "";
6251 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
6252 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6253 AuthorizationSet out_params;
6254 string ciphertext1 = EncryptMessage(message, params, &out_params);
6255 vector<uint8_t> iv1 = CopyIv(out_params);
6256 if (padding == PaddingMode::NONE)
6257 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6258 else
6259 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6260
6261 out_params.Clear();
6262
6263 string ciphertext2 = EncryptMessage(message, params, &out_params);
6264 vector<uint8_t> iv2 = CopyIv(out_params);
6265 if (padding == PaddingMode::NONE)
6266 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6267 else
6268 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6269
6270 // IVs should be random
6271 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6272
6273 params.push_back(TAG_NONCE, iv1);
6274 string plaintext = DecryptMessage(ciphertext1, params);
6275 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6276 }
6277}
6278
6279/*
Selene Huang31ab4042020-04-29 04:22:39 -07006280 * EncryptionOperationsTest.AesCallerNonce
6281 *
6282 * Verifies that AES caller-provided nonces work correctly.
6283 */
6284TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6285 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6286 .Authorization(TAG_NO_AUTH_REQUIRED)
6287 .AesEncryptionKey(128)
6288 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6289 .Authorization(TAG_CALLER_NONCE)
6290 .Padding(PaddingMode::NONE)));
6291
6292 string message = "12345678901234567890123456789012";
6293
6294 // Don't specify nonce, should get a random one.
6295 AuthorizationSetBuilder params =
6296 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6297 AuthorizationSet out_params;
6298 string ciphertext = EncryptMessage(message, params, &out_params);
6299 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006300 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006301
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006302 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006303 string plaintext = DecryptMessage(ciphertext, params);
6304 EXPECT_EQ(message, plaintext);
6305
6306 // Now specify a nonce, should also work.
6307 params = AuthorizationSetBuilder()
6308 .BlockMode(BlockMode::CBC)
6309 .Padding(PaddingMode::NONE)
6310 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6311 out_params.Clear();
6312 ciphertext = EncryptMessage(message, params, &out_params);
6313
6314 // Decrypt with correct nonce.
6315 plaintext = DecryptMessage(ciphertext, params);
6316 EXPECT_EQ(message, plaintext);
6317
6318 // Try with wrong nonce.
6319 params = AuthorizationSetBuilder()
6320 .BlockMode(BlockMode::CBC)
6321 .Padding(PaddingMode::NONE)
6322 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6323 plaintext = DecryptMessage(ciphertext, params);
6324 EXPECT_NE(message, plaintext);
6325}
6326
6327/*
6328 * EncryptionOperationsTest.AesCallerNonceProhibited
6329 *
6330 * Verifies that caller-provided nonces are not permitted when not specified in the key
6331 * authorizations.
6332 */
6333TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6334 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6335 .Authorization(TAG_NO_AUTH_REQUIRED)
6336 .AesEncryptionKey(128)
6337 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6338 .Padding(PaddingMode::NONE)));
6339
6340 string message = "12345678901234567890123456789012";
6341
6342 // Don't specify nonce, should get a random one.
6343 AuthorizationSetBuilder params =
6344 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6345 AuthorizationSet out_params;
6346 string ciphertext = EncryptMessage(message, params, &out_params);
6347 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006348 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006349
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006350 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006351 string plaintext = DecryptMessage(ciphertext, params);
6352 EXPECT_EQ(message, plaintext);
6353
6354 // Now specify a nonce, should fail
6355 params = AuthorizationSetBuilder()
6356 .BlockMode(BlockMode::CBC)
6357 .Padding(PaddingMode::NONE)
6358 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6359 out_params.Clear();
6360 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6361}
6362
6363/*
6364 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6365 *
6366 * Verifies that AES GCM mode works.
6367 */
6368TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6369 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6370 .Authorization(TAG_NO_AUTH_REQUIRED)
6371 .AesEncryptionKey(128)
6372 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6373 .Padding(PaddingMode::NONE)
6374 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6375
6376 string aad = "foobar";
6377 string message = "123456789012345678901234567890123456";
6378
6379 auto begin_params = AuthorizationSetBuilder()
6380 .BlockMode(BlockMode::GCM)
6381 .Padding(PaddingMode::NONE)
6382 .Authorization(TAG_MAC_LENGTH, 128);
6383
Selene Huang31ab4042020-04-29 04:22:39 -07006384 // Encrypt
6385 AuthorizationSet begin_out_params;
6386 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6387 << "Begin encrypt";
6388 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006389 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6390 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006391 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6392
6393 // Grab nonce
6394 begin_params.push_back(begin_out_params);
6395
6396 // Decrypt.
6397 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006398 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006399 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006400 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006401 EXPECT_EQ(message.length(), plaintext.length());
6402 EXPECT_EQ(message, plaintext);
6403}
6404
6405/*
6406 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6407 *
6408 * Verifies that AES GCM mode works, even when there's a long delay
6409 * between operations.
6410 */
6411TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6412 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6413 .Authorization(TAG_NO_AUTH_REQUIRED)
6414 .AesEncryptionKey(128)
6415 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6416 .Padding(PaddingMode::NONE)
6417 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6418
6419 string aad = "foobar";
6420 string message = "123456789012345678901234567890123456";
6421
6422 auto begin_params = AuthorizationSetBuilder()
6423 .BlockMode(BlockMode::GCM)
6424 .Padding(PaddingMode::NONE)
6425 .Authorization(TAG_MAC_LENGTH, 128);
6426
Selene Huang31ab4042020-04-29 04:22:39 -07006427 // Encrypt
6428 AuthorizationSet begin_out_params;
6429 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6430 << "Begin encrypt";
6431 string ciphertext;
6432 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006433 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006434 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006435 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006436
6437 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6438
6439 // Grab nonce
6440 begin_params.push_back(begin_out_params);
6441
6442 // Decrypt.
6443 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6444 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006445 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006446 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006447 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006448 sleep(5);
6449 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6450 EXPECT_EQ(message.length(), plaintext.length());
6451 EXPECT_EQ(message, plaintext);
6452}
6453
6454/*
6455 * EncryptionOperationsTest.AesGcmDifferentNonces
6456 *
6457 * Verifies that encrypting the same data with different nonces produces different outputs.
6458 */
6459TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6460 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6461 .Authorization(TAG_NO_AUTH_REQUIRED)
6462 .AesEncryptionKey(128)
6463 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6464 .Padding(PaddingMode::NONE)
6465 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6466 .Authorization(TAG_CALLER_NONCE)));
6467
6468 string aad = "foobar";
6469 string message = "123456789012345678901234567890123456";
6470 string nonce1 = "000000000000";
6471 string nonce2 = "111111111111";
6472 string nonce3 = "222222222222";
6473
6474 string ciphertext1 =
6475 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6476 string ciphertext2 =
6477 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6478 string ciphertext3 =
6479 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6480
6481 ASSERT_NE(ciphertext1, ciphertext2);
6482 ASSERT_NE(ciphertext1, ciphertext3);
6483 ASSERT_NE(ciphertext2, ciphertext3);
6484}
6485
6486/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006487 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6488 *
6489 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6490 */
6491TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6492 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6493 .Authorization(TAG_NO_AUTH_REQUIRED)
6494 .AesEncryptionKey(128)
6495 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6496 .Padding(PaddingMode::NONE)
6497 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6498
6499 string aad = "foobar";
6500 string message = "123456789012345678901234567890123456";
6501
6502 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6503 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6504 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6505
6506 ASSERT_NE(ciphertext1, ciphertext2);
6507 ASSERT_NE(ciphertext1, ciphertext3);
6508 ASSERT_NE(ciphertext2, ciphertext3);
6509}
6510
6511/*
Selene Huang31ab4042020-04-29 04:22:39 -07006512 * EncryptionOperationsTest.AesGcmTooShortTag
6513 *
6514 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6515 */
6516TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6517 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6518 .Authorization(TAG_NO_AUTH_REQUIRED)
6519 .AesEncryptionKey(128)
6520 .BlockMode(BlockMode::GCM)
6521 .Padding(PaddingMode::NONE)
6522 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6523 string message = "123456789012345678901234567890123456";
6524 auto params = AuthorizationSetBuilder()
6525 .BlockMode(BlockMode::GCM)
6526 .Padding(PaddingMode::NONE)
6527 .Authorization(TAG_MAC_LENGTH, 96);
6528
6529 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6530}
6531
6532/*
6533 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6534 *
6535 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6536 */
6537TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6538 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6539 .Authorization(TAG_NO_AUTH_REQUIRED)
6540 .AesEncryptionKey(128)
6541 .BlockMode(BlockMode::GCM)
6542 .Padding(PaddingMode::NONE)
6543 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6544 string aad = "foobar";
6545 string message = "123456789012345678901234567890123456";
6546 auto params = AuthorizationSetBuilder()
6547 .BlockMode(BlockMode::GCM)
6548 .Padding(PaddingMode::NONE)
6549 .Authorization(TAG_MAC_LENGTH, 128);
6550
Selene Huang31ab4042020-04-29 04:22:39 -07006551 // Encrypt
6552 AuthorizationSet begin_out_params;
6553 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6554 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006555 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006556
6557 AuthorizationSet finish_out_params;
6558 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006559 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6560 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006561
6562 params = AuthorizationSetBuilder()
6563 .Authorizations(begin_out_params)
6564 .BlockMode(BlockMode::GCM)
6565 .Padding(PaddingMode::NONE)
6566 .Authorization(TAG_MAC_LENGTH, 96);
6567
6568 // Decrypt.
6569 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6570}
6571
6572/*
6573 * EncryptionOperationsTest.AesGcmCorruptKey
6574 *
6575 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6576 */
6577TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6578 const uint8_t nonce_bytes[] = {
6579 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6580 };
6581 string nonce = make_string(nonce_bytes);
6582 const uint8_t ciphertext_bytes[] = {
6583 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6584 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6585 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6586 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6587 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6588 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6589 };
6590 string ciphertext = make_string(ciphertext_bytes);
6591
6592 auto params = AuthorizationSetBuilder()
6593 .BlockMode(BlockMode::GCM)
6594 .Padding(PaddingMode::NONE)
6595 .Authorization(TAG_MAC_LENGTH, 128)
6596 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6597
6598 auto import_params = AuthorizationSetBuilder()
6599 .Authorization(TAG_NO_AUTH_REQUIRED)
6600 .AesEncryptionKey(128)
6601 .BlockMode(BlockMode::GCM)
6602 .Padding(PaddingMode::NONE)
6603 .Authorization(TAG_CALLER_NONCE)
6604 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6605
6606 // Import correct key and decrypt
6607 const uint8_t key_bytes[] = {
6608 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6609 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6610 };
6611 string key = make_string(key_bytes);
6612 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6613 string plaintext = DecryptMessage(ciphertext, params);
6614 CheckedDeleteKey();
6615
6616 // Corrupt key and attempt to decrypt
6617 key[0] = 0;
6618 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6619 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6620 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6621 CheckedDeleteKey();
6622}
6623
6624/*
6625 * EncryptionOperationsTest.AesGcmAadNoData
6626 *
6627 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6628 * encrypt.
6629 */
6630TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6631 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6632 .Authorization(TAG_NO_AUTH_REQUIRED)
6633 .AesEncryptionKey(128)
6634 .BlockMode(BlockMode::GCM)
6635 .Padding(PaddingMode::NONE)
6636 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6637
6638 string aad = "1234567890123456";
6639 auto params = AuthorizationSetBuilder()
6640 .BlockMode(BlockMode::GCM)
6641 .Padding(PaddingMode::NONE)
6642 .Authorization(TAG_MAC_LENGTH, 128);
6643
Selene Huang31ab4042020-04-29 04:22:39 -07006644 // Encrypt
6645 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006646 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006647 string ciphertext;
6648 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006649 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6650 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006651 EXPECT_TRUE(finish_out_params.empty());
6652
6653 // Grab nonce
6654 params.push_back(begin_out_params);
6655
6656 // Decrypt.
6657 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006658 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006659 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006660 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006661
6662 EXPECT_TRUE(finish_out_params.empty());
6663
6664 EXPECT_EQ("", plaintext);
6665}
6666
6667/*
6668 * EncryptionOperationsTest.AesGcmMultiPartAad
6669 *
6670 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6671 * chunks.
6672 */
6673TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6674 const size_t tag_bits = 128;
6675 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6676 .Authorization(TAG_NO_AUTH_REQUIRED)
6677 .AesEncryptionKey(128)
6678 .BlockMode(BlockMode::GCM)
6679 .Padding(PaddingMode::NONE)
6680 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6681
6682 string message = "123456789012345678901234567890123456";
6683 auto begin_params = AuthorizationSetBuilder()
6684 .BlockMode(BlockMode::GCM)
6685 .Padding(PaddingMode::NONE)
6686 .Authorization(TAG_MAC_LENGTH, tag_bits);
6687 AuthorizationSet begin_out_params;
6688
David Drysdale7fc26b92022-05-13 09:54:24 +01006689 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006690
6691 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006692 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6693 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006694 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006695 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6696 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006697
Selene Huang31ab4042020-04-29 04:22:39 -07006698 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006699 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006700
6701 // Grab nonce.
6702 begin_params.push_back(begin_out_params);
6703
6704 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01006705 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006706 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006707 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006708 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006709 EXPECT_EQ(message, plaintext);
6710}
6711
6712/*
6713 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6714 *
6715 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6716 */
6717TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6718 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6719 .Authorization(TAG_NO_AUTH_REQUIRED)
6720 .AesEncryptionKey(128)
6721 .BlockMode(BlockMode::GCM)
6722 .Padding(PaddingMode::NONE)
6723 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6724
6725 string message = "123456789012345678901234567890123456";
6726 auto begin_params = AuthorizationSetBuilder()
6727 .BlockMode(BlockMode::GCM)
6728 .Padding(PaddingMode::NONE)
6729 .Authorization(TAG_MAC_LENGTH, 128);
6730 AuthorizationSet begin_out_params;
6731
David Drysdale7fc26b92022-05-13 09:54:24 +01006732 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006733
Shawn Willden92d79c02021-02-19 07:31:55 -07006734 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006735 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006736 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6737 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006738
David Drysdaled2cc8c22021-04-15 13:29:45 +01006739 // The failure should have already cancelled the operation.
6740 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6741
Shawn Willden92d79c02021-02-19 07:31:55 -07006742 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006743}
6744
6745/*
6746 * EncryptionOperationsTest.AesGcmBadAad
6747 *
6748 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6749 */
6750TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6751 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6752 .Authorization(TAG_NO_AUTH_REQUIRED)
6753 .AesEncryptionKey(128)
6754 .BlockMode(BlockMode::GCM)
6755 .Padding(PaddingMode::NONE)
6756 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6757
6758 string message = "12345678901234567890123456789012";
6759 auto begin_params = AuthorizationSetBuilder()
6760 .BlockMode(BlockMode::GCM)
6761 .Padding(PaddingMode::NONE)
6762 .Authorization(TAG_MAC_LENGTH, 128);
6763
Selene Huang31ab4042020-04-29 04:22:39 -07006764 // Encrypt
6765 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006766 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006767 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006768 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006769 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006770
6771 // Grab nonce
6772 begin_params.push_back(begin_out_params);
6773
Selene Huang31ab4042020-04-29 04:22:39 -07006774 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006775 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006776 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006777 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006778 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006779}
6780
6781/*
6782 * EncryptionOperationsTest.AesGcmWrongNonce
6783 *
6784 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6785 */
6786TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6787 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6788 .Authorization(TAG_NO_AUTH_REQUIRED)
6789 .AesEncryptionKey(128)
6790 .BlockMode(BlockMode::GCM)
6791 .Padding(PaddingMode::NONE)
6792 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6793
6794 string message = "12345678901234567890123456789012";
6795 auto begin_params = AuthorizationSetBuilder()
6796 .BlockMode(BlockMode::GCM)
6797 .Padding(PaddingMode::NONE)
6798 .Authorization(TAG_MAC_LENGTH, 128);
6799
Selene Huang31ab4042020-04-29 04:22:39 -07006800 // Encrypt
6801 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006802 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006803 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006804 string ciphertext;
6805 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006806 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006807
6808 // Wrong nonce
6809 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6810
6811 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006812 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006813 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006814 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006815 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006816
6817 // With wrong nonce, should have gotten garbage plaintext (or none).
6818 EXPECT_NE(message, plaintext);
6819}
6820
6821/*
6822 * EncryptionOperationsTest.AesGcmCorruptTag
6823 *
6824 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6825 */
6826TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6827 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6828 .Authorization(TAG_NO_AUTH_REQUIRED)
6829 .AesEncryptionKey(128)
6830 .BlockMode(BlockMode::GCM)
6831 .Padding(PaddingMode::NONE)
6832 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6833
6834 string aad = "1234567890123456";
6835 string message = "123456789012345678901234567890123456";
6836
6837 auto params = AuthorizationSetBuilder()
6838 .BlockMode(BlockMode::GCM)
6839 .Padding(PaddingMode::NONE)
6840 .Authorization(TAG_MAC_LENGTH, 128);
6841
Selene Huang31ab4042020-04-29 04:22:39 -07006842 // Encrypt
6843 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006844 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006845 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006846 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006847 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006848
6849 // Corrupt tag
6850 ++(*ciphertext.rbegin());
6851
6852 // Grab nonce
6853 params.push_back(begin_out_params);
6854
6855 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006856 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006857 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006858 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006859 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006860}
6861
6862/*
6863 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
6864 *
6865 * Verifies that 3DES is basically functional.
6866 */
6867TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
6868 auto auths = AuthorizationSetBuilder()
6869 .TripleDesEncryptionKey(168)
6870 .BlockMode(BlockMode::ECB)
6871 .Authorization(TAG_NO_AUTH_REQUIRED)
6872 .Padding(PaddingMode::NONE);
6873
6874 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
6875 // Two-block message.
6876 string message = "1234567890123456";
6877 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6878 string ciphertext1 = EncryptMessage(message, inParams);
6879 EXPECT_EQ(message.size(), ciphertext1.size());
6880
6881 string ciphertext2 = EncryptMessage(string(message), inParams);
6882 EXPECT_EQ(message.size(), ciphertext2.size());
6883
6884 // ECB is deterministic.
6885 EXPECT_EQ(ciphertext1, ciphertext2);
6886
6887 string plaintext = DecryptMessage(ciphertext1, inParams);
6888 EXPECT_EQ(message, plaintext);
6889}
6890
6891/*
6892 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
6893 *
6894 * Verifies that CBC keys reject ECB usage.
6895 */
6896TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
6897 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6898 .TripleDesEncryptionKey(168)
6899 .BlockMode(BlockMode::CBC)
6900 .Authorization(TAG_NO_AUTH_REQUIRED)
6901 .Padding(PaddingMode::NONE)));
6902
6903 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6904 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
6905}
6906
6907/*
6908 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
6909 *
6910 * Tests ECB mode with PKCS#7 padding, various message sizes.
6911 */
6912TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
6913 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6914 .TripleDesEncryptionKey(168)
6915 .BlockMode(BlockMode::ECB)
6916 .Authorization(TAG_NO_AUTH_REQUIRED)
6917 .Padding(PaddingMode::PKCS7)));
6918
6919 for (size_t i = 0; i < 32; ++i) {
6920 string message(i, 'a');
6921 auto inParams =
6922 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6923 string ciphertext = EncryptMessage(message, inParams);
6924 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6925 string plaintext = DecryptMessage(ciphertext, inParams);
6926 EXPECT_EQ(message, plaintext);
6927 }
6928}
6929
6930/*
6931 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
6932 *
6933 * Verifies that keys configured for no padding reject PKCS7 padding
6934 */
6935TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
6936 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6937 .TripleDesEncryptionKey(168)
6938 .BlockMode(BlockMode::ECB)
6939 .Authorization(TAG_NO_AUTH_REQUIRED)
6940 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00006941 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6942 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07006943}
6944
6945/*
6946 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
6947 *
6948 * Verifies that corrupted padding is detected.
6949 */
6950TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
6951 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6952 .TripleDesEncryptionKey(168)
6953 .BlockMode(BlockMode::ECB)
6954 .Authorization(TAG_NO_AUTH_REQUIRED)
6955 .Padding(PaddingMode::PKCS7)));
6956
6957 string message = "a";
6958 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
6959 EXPECT_EQ(8U, ciphertext.size());
6960 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006961
6962 AuthorizationSetBuilder begin_params;
6963 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
6964 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07006965
6966 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
6967 ++ciphertext[ciphertext.size() / 2];
6968
David Drysdale7fc26b92022-05-13 09:54:24 +01006969 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07006970 string plaintext;
6971 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6972 ErrorCode error = Finish(&plaintext);
6973 if (error == ErrorCode::INVALID_ARGUMENT) {
6974 // This is the expected error, we can exit the test now.
6975 return;
6976 } else {
6977 // Very small chance we got valid decryption, so try again.
6978 ASSERT_EQ(error, ErrorCode::OK);
6979 }
6980 }
6981 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006982}
6983
6984struct TripleDesTestVector {
6985 const char* name;
6986 const KeyPurpose purpose;
6987 const BlockMode block_mode;
6988 const PaddingMode padding_mode;
6989 const char* key;
6990 const char* iv;
6991 const char* input;
6992 const char* output;
6993};
6994
6995// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
6996// of the NIST vectors are multiples of the block size.
6997static const TripleDesTestVector kTripleDesTestVectors[] = {
6998 {
6999 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7000 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7001 "", // IV
7002 "329d86bdf1bc5af4", // input
7003 "d946c2756d78633f", // output
7004 },
7005 {
7006 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7007 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7008 "", // IV
7009 "6b1540781b01ce1997adae102dbf3c5b", // input
7010 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7011 },
7012 {
7013 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7014 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7015 "", // IV
7016 "6daad94ce08acfe7", // input
7017 "660e7d32dcc90e79", // output
7018 },
7019 {
7020 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7021 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7022 "", // IV
7023 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7024 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7025 },
7026 {
7027 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7028 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7029 "43f791134c5647ba", // IV
7030 "dcc153cef81d6f24", // input
7031 "92538bd8af18d3ba", // output
7032 },
7033 {
7034 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7035 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7036 "c2e999cb6249023c", // IV
7037 "c689aee38a301bb316da75db36f110b5", // input
7038 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7039 },
7040 {
7041 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7042 PaddingMode::PKCS7,
7043 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7044 "c2e999cb6249023c", // IV
7045 "c689aee38a301bb316da75db36f110b500", // input
7046 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7047 },
7048 {
7049 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7050 PaddingMode::PKCS7,
7051 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7052 "c2e999cb6249023c", // IV
7053 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7054 "c689aee38a301bb316da75db36f110b500", // output
7055 },
7056 {
7057 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7058 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7059 "41746c7e442d3681", // IV
7060 "c53a7b0ec40600fe", // input
7061 "d4f00eb455de1034", // output
7062 },
7063 {
7064 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7065 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7066 "3982bc02c3727d45", // IV
7067 "6006f10adef52991fcc777a1238bbb65", // input
7068 "edae09288e9e3bc05746d872b48e3b29", // output
7069 },
7070};
7071
7072/*
7073 * EncryptionOperationsTest.TripleDesTestVector
7074 *
7075 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7076 */
7077TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7078 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7079 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7080 SCOPED_TRACE(test->name);
7081 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7082 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7083 hex2str(test->output));
7084 }
7085}
7086
7087/*
7088 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7089 *
7090 * Validates CBC mode functionality.
7091 */
7092TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7093 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7094 .TripleDesEncryptionKey(168)
7095 .BlockMode(BlockMode::CBC)
7096 .Authorization(TAG_NO_AUTH_REQUIRED)
7097 .Padding(PaddingMode::NONE)));
7098
7099 ASSERT_GT(key_blob_.size(), 0U);
7100
Brian J Murray734c8412022-01-13 14:55:30 -08007101 // Four-block message.
7102 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007103 vector<uint8_t> iv1;
7104 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7105 EXPECT_EQ(message.size(), ciphertext1.size());
7106
7107 vector<uint8_t> iv2;
7108 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7109 EXPECT_EQ(message.size(), ciphertext2.size());
7110
7111 // IVs should be random, so ciphertexts should differ.
7112 EXPECT_NE(iv1, iv2);
7113 EXPECT_NE(ciphertext1, ciphertext2);
7114
7115 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7116 EXPECT_EQ(message, plaintext);
7117}
7118
7119/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007120 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7121 *
7122 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7123 */
7124TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7125 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7126 .TripleDesEncryptionKey(168)
7127 .BlockMode(BlockMode::CBC)
7128 .Authorization(TAG_NO_AUTH_REQUIRED)
7129 .Authorization(TAG_CALLER_NONCE)
7130 .Padding(PaddingMode::NONE)));
7131 auto params = AuthorizationSetBuilder()
7132 .BlockMode(BlockMode::CBC)
7133 .Padding(PaddingMode::NONE)
7134 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7135 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7136}
7137
7138/*
Selene Huang31ab4042020-04-29 04:22:39 -07007139 * EncryptionOperationsTest.TripleDesCallerIv
7140 *
7141 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7142 */
7143TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7144 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7145 .TripleDesEncryptionKey(168)
7146 .BlockMode(BlockMode::CBC)
7147 .Authorization(TAG_NO_AUTH_REQUIRED)
7148 .Authorization(TAG_CALLER_NONCE)
7149 .Padding(PaddingMode::NONE)));
7150 string message = "1234567890123456";
7151 vector<uint8_t> iv;
7152 // Don't specify IV, should get a random one.
7153 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7154 EXPECT_EQ(message.size(), ciphertext1.size());
7155 EXPECT_EQ(8U, iv.size());
7156
7157 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7158 EXPECT_EQ(message, plaintext);
7159
7160 // Now specify an IV, should also work.
7161 iv = AidlBuf("abcdefgh");
7162 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7163
7164 // Decrypt with correct IV.
7165 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7166 EXPECT_EQ(message, plaintext);
7167
7168 // Now try with wrong IV.
7169 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7170 EXPECT_NE(message, plaintext);
7171}
7172
7173/*
7174 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7175 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007176 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007177 */
7178TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7179 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7180 .TripleDesEncryptionKey(168)
7181 .BlockMode(BlockMode::CBC)
7182 .Authorization(TAG_NO_AUTH_REQUIRED)
7183 .Padding(PaddingMode::NONE)));
7184
7185 string message = "12345678901234567890123456789012";
7186 vector<uint8_t> iv;
7187 // Don't specify nonce, should get a random one.
7188 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7189 EXPECT_EQ(message.size(), ciphertext1.size());
7190 EXPECT_EQ(8U, iv.size());
7191
7192 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7193 EXPECT_EQ(message, plaintext);
7194
7195 // Now specify a nonce, should fail.
7196 auto input_params = AuthorizationSetBuilder()
7197 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7198 .BlockMode(BlockMode::CBC)
7199 .Padding(PaddingMode::NONE);
7200 AuthorizationSet output_params;
7201 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7202 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7203}
7204
7205/*
7206 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7207 *
7208 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7209 */
7210TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7211 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7212 .TripleDesEncryptionKey(168)
7213 .BlockMode(BlockMode::ECB)
7214 .Authorization(TAG_NO_AUTH_REQUIRED)
7215 .Padding(PaddingMode::NONE)));
7216 // Two-block message.
7217 string message = "1234567890123456";
7218 auto begin_params =
7219 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7220 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7221}
7222
7223/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007224 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007225 *
7226 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7227 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007228TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7229 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
7230 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7231 .TripleDesEncryptionKey(168)
7232 .BlockMode(blockMode)
7233 .Authorization(TAG_NO_AUTH_REQUIRED)
7234 .Padding(PaddingMode::NONE)));
7235 // Message is slightly shorter than two blocks.
7236 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007237
David Drysdaled2cc8c22021-04-15 13:29:45 +01007238 auto begin_params =
7239 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7240 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007241 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007242 string ciphertext;
7243 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7244
7245 CheckedDeleteKey();
7246 }
Selene Huang31ab4042020-04-29 04:22:39 -07007247}
7248
7249/*
7250 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7251 *
7252 * Verifies that PKCS7 padding works correctly in CBC mode.
7253 */
7254TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7255 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7256 .TripleDesEncryptionKey(168)
7257 .BlockMode(BlockMode::CBC)
7258 .Authorization(TAG_NO_AUTH_REQUIRED)
7259 .Padding(PaddingMode::PKCS7)));
7260
7261 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007262 for (size_t i = 0; i <= 32; i++) {
7263 SCOPED_TRACE(testing::Message() << "i = " << i);
7264 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7265 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007266 vector<uint8_t> iv;
7267 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7268 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7269 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7270 EXPECT_EQ(message, plaintext);
7271 }
7272}
7273
7274/*
7275 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7276 *
7277 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7278 */
7279TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7280 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7281 .TripleDesEncryptionKey(168)
7282 .BlockMode(BlockMode::CBC)
7283 .Authorization(TAG_NO_AUTH_REQUIRED)
7284 .Padding(PaddingMode::NONE)));
7285
7286 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007287 for (size_t i = 0; i <= 32; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07007288 auto begin_params =
7289 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7290 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7291 }
7292}
7293
7294/*
7295 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7296 *
7297 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7298 */
7299TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7300 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7301 .TripleDesEncryptionKey(168)
7302 .BlockMode(BlockMode::CBC)
7303 .Authorization(TAG_NO_AUTH_REQUIRED)
7304 .Padding(PaddingMode::PKCS7)));
7305
7306 string message = "a";
7307 vector<uint8_t> iv;
7308 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7309 EXPECT_EQ(8U, ciphertext.size());
7310 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007311
7312 auto begin_params = AuthorizationSetBuilder()
7313 .BlockMode(BlockMode::CBC)
7314 .Padding(PaddingMode::PKCS7)
7315 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007316
7317 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007318 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007319 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007320 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007321 string plaintext;
7322 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7323 ErrorCode error = Finish(&plaintext);
7324 if (error == ErrorCode::INVALID_ARGUMENT) {
7325 // This is the expected error, we can exit the test now.
7326 return;
7327 } else {
7328 // Very small chance we got valid decryption, so try again.
7329 ASSERT_EQ(error, ErrorCode::OK);
7330 }
7331 }
7332 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007333}
7334
7335/*
7336 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7337 *
7338 * Verifies that 3DES CBC works with many different input sizes.
7339 */
7340TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7341 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7342 .TripleDesEncryptionKey(168)
7343 .BlockMode(BlockMode::CBC)
7344 .Authorization(TAG_NO_AUTH_REQUIRED)
7345 .Padding(PaddingMode::NONE)));
7346
7347 int increment = 7;
7348 string message(240, 'a');
7349 AuthorizationSet input_params =
7350 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7351 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007352 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007353
7354 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007355 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007356 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007357 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7358 EXPECT_EQ(message.size(), ciphertext.size());
7359
7360 // Move TAG_NONCE into input_params
7361 input_params = output_params;
7362 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7363 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7364 output_params.Clear();
7365
David Drysdale7fc26b92022-05-13 09:54:24 +01007366 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007367 string plaintext;
7368 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007369 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007370 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7371 EXPECT_EQ(ciphertext.size(), plaintext.size());
7372 EXPECT_EQ(message, plaintext);
7373}
7374
7375INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7376
7377typedef KeyMintAidlTestBase MaxOperationsTest;
7378
7379/*
7380 * MaxOperationsTest.TestLimitAes
7381 *
7382 * Verifies that the max uses per boot tag works correctly with AES keys.
7383 */
7384TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007385 if (SecLevel() == SecurityLevel::STRONGBOX) {
7386 GTEST_SKIP() << "Test not applicable to StrongBox device";
7387 }
Selene Huang31ab4042020-04-29 04:22:39 -07007388
7389 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7390 .Authorization(TAG_NO_AUTH_REQUIRED)
7391 .AesEncryptionKey(128)
7392 .EcbMode()
7393 .Padding(PaddingMode::NONE)
7394 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7395
7396 string message = "1234567890123456";
7397
7398 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7399
7400 EncryptMessage(message, params);
7401 EncryptMessage(message, params);
7402 EncryptMessage(message, params);
7403
7404 // Fourth time should fail.
7405 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7406}
7407
7408/*
Qi Wud22ec842020-11-26 13:27:53 +08007409 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007410 *
7411 * Verifies that the max uses per boot tag works correctly with RSA keys.
7412 */
7413TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007414 if (SecLevel() == SecurityLevel::STRONGBOX) {
7415 GTEST_SKIP() << "Test not applicable to StrongBox device";
7416 }
Selene Huang31ab4042020-04-29 04:22:39 -07007417
7418 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7419 .Authorization(TAG_NO_AUTH_REQUIRED)
7420 .RsaSigningKey(1024, 65537)
7421 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007422 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7423 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007424
7425 string message = "1234567890123456";
7426
7427 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7428
7429 SignMessage(message, params);
7430 SignMessage(message, params);
7431 SignMessage(message, params);
7432
7433 // Fourth time should fail.
7434 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7435}
7436
7437INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7438
Qi Wud22ec842020-11-26 13:27:53 +08007439typedef KeyMintAidlTestBase UsageCountLimitTest;
7440
7441/*
Qi Wubeefae42021-01-28 23:16:37 +08007442 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007443 *
Qi Wubeefae42021-01-28 23:16:37 +08007444 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007445 */
Qi Wubeefae42021-01-28 23:16:37 +08007446TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007447 if (SecLevel() == SecurityLevel::STRONGBOX) {
7448 GTEST_SKIP() << "Test not applicable to StrongBox device";
7449 }
Qi Wud22ec842020-11-26 13:27:53 +08007450
7451 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7452 .Authorization(TAG_NO_AUTH_REQUIRED)
7453 .AesEncryptionKey(128)
7454 .EcbMode()
7455 .Padding(PaddingMode::NONE)
7456 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7457
7458 // Check the usage count limit tag appears in the authorizations.
7459 AuthorizationSet auths;
7460 for (auto& entry : key_characteristics_) {
7461 auths.push_back(AuthorizationSet(entry.authorizations));
7462 }
7463 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7464 << "key usage count limit " << 1U << " missing";
7465
7466 string message = "1234567890123456";
7467 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7468
Qi Wubeefae42021-01-28 23:16:37 +08007469 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7470 AuthorizationSet keystore_auths =
7471 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7472
Qi Wud22ec842020-11-26 13:27:53 +08007473 // First usage of AES key should work.
7474 EncryptMessage(message, params);
7475
Qi Wud22ec842020-11-26 13:27:53 +08007476 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7477 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7478 // must be invalidated from secure storage (such as RPMB partition).
7479 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7480 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007481 // Usage count limit tag is enforced by keystore, keymint does nothing.
7482 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007483 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007484 }
7485}
7486
7487/*
Qi Wubeefae42021-01-28 23:16:37 +08007488 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007489 *
Qi Wubeefae42021-01-28 23:16:37 +08007490 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007491 */
Qi Wubeefae42021-01-28 23:16:37 +08007492TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007493 if (SecLevel() == SecurityLevel::STRONGBOX) {
7494 GTEST_SKIP() << "Test not applicable to StrongBox device";
7495 }
Qi Wubeefae42021-01-28 23:16:37 +08007496
7497 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7498 .Authorization(TAG_NO_AUTH_REQUIRED)
7499 .AesEncryptionKey(128)
7500 .EcbMode()
7501 .Padding(PaddingMode::NONE)
7502 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7503
7504 // Check the usage count limit tag appears in the authorizations.
7505 AuthorizationSet auths;
7506 for (auto& entry : key_characteristics_) {
7507 auths.push_back(AuthorizationSet(entry.authorizations));
7508 }
7509 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7510 << "key usage count limit " << 3U << " missing";
7511
7512 string message = "1234567890123456";
7513 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7514
7515 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7516 AuthorizationSet keystore_auths =
7517 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7518
7519 EncryptMessage(message, params);
7520 EncryptMessage(message, params);
7521 EncryptMessage(message, params);
7522
7523 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7524 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7525 // must be invalidated from secure storage (such as RPMB partition).
7526 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7527 } else {
7528 // Usage count limit tag is enforced by keystore, keymint does nothing.
7529 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007530 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007531 }
7532}
7533
7534/*
7535 * UsageCountLimitTest.TestSingleUseRsa
7536 *
7537 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7538 */
7539TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007540 if (SecLevel() == SecurityLevel::STRONGBOX) {
7541 GTEST_SKIP() << "Test not applicable to StrongBox device";
7542 }
Qi Wud22ec842020-11-26 13:27:53 +08007543
7544 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7545 .Authorization(TAG_NO_AUTH_REQUIRED)
7546 .RsaSigningKey(1024, 65537)
7547 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007548 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7549 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007550
7551 // Check the usage count limit tag appears in the authorizations.
7552 AuthorizationSet auths;
7553 for (auto& entry : key_characteristics_) {
7554 auths.push_back(AuthorizationSet(entry.authorizations));
7555 }
7556 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7557 << "key usage count limit " << 1U << " missing";
7558
7559 string message = "1234567890123456";
7560 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7561
Qi Wubeefae42021-01-28 23:16:37 +08007562 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7563 AuthorizationSet keystore_auths =
7564 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7565
Qi Wud22ec842020-11-26 13:27:53 +08007566 // First usage of RSA key should work.
7567 SignMessage(message, params);
7568
Qi Wud22ec842020-11-26 13:27:53 +08007569 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7570 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7571 // must be invalidated from secure storage (such as RPMB partition).
7572 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7573 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007574 // Usage count limit tag is enforced by keystore, keymint does nothing.
7575 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007576 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007577 }
7578}
7579
7580/*
7581 * UsageCountLimitTest.TestLimitUseRsa
7582 *
7583 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7584 */
7585TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007586 if (SecLevel() == SecurityLevel::STRONGBOX) {
7587 GTEST_SKIP() << "Test not applicable to StrongBox device";
7588 }
Qi Wubeefae42021-01-28 23:16:37 +08007589
7590 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7591 .Authorization(TAG_NO_AUTH_REQUIRED)
7592 .RsaSigningKey(1024, 65537)
7593 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007594 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7595 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007596
7597 // Check the usage count limit tag appears in the authorizations.
7598 AuthorizationSet auths;
7599 for (auto& entry : key_characteristics_) {
7600 auths.push_back(AuthorizationSet(entry.authorizations));
7601 }
7602 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7603 << "key usage count limit " << 3U << " missing";
7604
7605 string message = "1234567890123456";
7606 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7607
7608 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7609 AuthorizationSet keystore_auths =
7610 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7611
7612 SignMessage(message, params);
7613 SignMessage(message, params);
7614 SignMessage(message, params);
7615
7616 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7617 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7618 // must be invalidated from secure storage (such as RPMB partition).
7619 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7620 } else {
7621 // Usage count limit tag is enforced by keystore, keymint does nothing.
7622 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007623 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007624 }
7625}
7626
Qi Wu8e727f72021-02-11 02:49:33 +08007627/*
7628 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7629 *
7630 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7631 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7632 * in hardware.
7633 */
7634TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01007635 if (SecLevel() == SecurityLevel::STRONGBOX) {
7636 GTEST_SKIP() << "Test not applicable to StrongBox device";
7637 }
Qi Wu8e727f72021-02-11 02:49:33 +08007638
7639 auto error = GenerateKey(AuthorizationSetBuilder()
7640 .RsaSigningKey(2048, 65537)
7641 .Digest(Digest::NONE)
7642 .Padding(PaddingMode::NONE)
7643 .Authorization(TAG_NO_AUTH_REQUIRED)
7644 .Authorization(TAG_ROLLBACK_RESISTANCE)
7645 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007646 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7647 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007648 }
David Drysdale513bf122021-10-06 11:53:13 +01007649
7650 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7651 ASSERT_EQ(ErrorCode::OK, error);
7652 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7653 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7654 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7655
7656 // The KeyMint should also enforce single use key in hardware when it supports rollback
7657 // resistance.
7658 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7659 .Authorization(TAG_NO_AUTH_REQUIRED)
7660 .RsaSigningKey(1024, 65537)
7661 .NoDigestOrPadding()
7662 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7663 .SetDefaultValidity()));
7664
7665 // Check the usage count limit tag appears in the hardware authorizations.
7666 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7667 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7668 << "key usage count limit " << 1U << " missing";
7669
7670 string message = "1234567890123456";
7671 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7672
7673 // First usage of RSA key should work.
7674 SignMessage(message, params);
7675
7676 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7677 // must be invalidated from secure storage (such as RPMB partition).
7678 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007679}
7680
Qi Wud22ec842020-11-26 13:27:53 +08007681INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7682
David Drysdale7de9feb2021-03-05 14:56:19 +00007683typedef KeyMintAidlTestBase GetHardwareInfoTest;
7684
7685TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7686 // Retrieving hardware info should give the same result each time.
7687 KeyMintHardwareInfo info;
7688 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7689 KeyMintHardwareInfo info2;
7690 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7691 EXPECT_EQ(info, info2);
7692}
7693
7694INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7695
Selene Huang31ab4042020-04-29 04:22:39 -07007696typedef KeyMintAidlTestBase AddEntropyTest;
7697
7698/*
7699 * AddEntropyTest.AddEntropy
7700 *
7701 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7702 * is actually added.
7703 */
7704TEST_P(AddEntropyTest, AddEntropy) {
7705 string data = "foo";
7706 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7707}
7708
7709/*
7710 * AddEntropyTest.AddEmptyEntropy
7711 *
7712 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7713 */
7714TEST_P(AddEntropyTest, AddEmptyEntropy) {
7715 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7716}
7717
7718/*
7719 * AddEntropyTest.AddLargeEntropy
7720 *
7721 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7722 */
7723TEST_P(AddEntropyTest, AddLargeEntropy) {
7724 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7725}
7726
David Drysdalebb3d85e2021-04-13 11:15:51 +01007727/*
7728 * AddEntropyTest.AddTooLargeEntropy
7729 *
7730 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7731 */
7732TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7733 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7734 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7735}
7736
Selene Huang31ab4042020-04-29 04:22:39 -07007737INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7738
Selene Huang31ab4042020-04-29 04:22:39 -07007739typedef KeyMintAidlTestBase KeyDeletionTest;
7740
7741/**
7742 * KeyDeletionTest.DeleteKey
7743 *
7744 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7745 * valid key blob.
7746 */
7747TEST_P(KeyDeletionTest, DeleteKey) {
7748 auto error = GenerateKey(AuthorizationSetBuilder()
7749 .RsaSigningKey(2048, 65537)
7750 .Digest(Digest::NONE)
7751 .Padding(PaddingMode::NONE)
7752 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007753 .Authorization(TAG_ROLLBACK_RESISTANCE)
7754 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007755 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7756 GTEST_SKIP() << "Rollback resistance not supported";
7757 }
Selene Huang31ab4042020-04-29 04:22:39 -07007758
7759 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007760 ASSERT_EQ(ErrorCode::OK, error);
7761 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7762 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007763
David Drysdale513bf122021-10-06 11:53:13 +01007764 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007765
David Drysdale513bf122021-10-06 11:53:13 +01007766 string message = "12345678901234567890123456789012";
7767 AuthorizationSet begin_out_params;
7768 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7769 Begin(KeyPurpose::SIGN, key_blob_,
7770 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7771 &begin_out_params));
7772 AbortIfNeeded();
7773 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007774}
7775
7776/**
7777 * KeyDeletionTest.DeleteInvalidKey
7778 *
7779 * This test checks that the HAL excepts invalid key blobs..
7780 */
7781TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7782 // Generate key just to check if rollback protection is implemented
7783 auto error = GenerateKey(AuthorizationSetBuilder()
7784 .RsaSigningKey(2048, 65537)
7785 .Digest(Digest::NONE)
7786 .Padding(PaddingMode::NONE)
7787 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007788 .Authorization(TAG_ROLLBACK_RESISTANCE)
7789 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007790 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7791 GTEST_SKIP() << "Rollback resistance not supported";
7792 }
Selene Huang31ab4042020-04-29 04:22:39 -07007793
7794 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007795 ASSERT_EQ(ErrorCode::OK, error);
7796 AuthorizationSet enforced(SecLevelAuthorizations());
7797 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007798
David Drysdale513bf122021-10-06 11:53:13 +01007799 // Delete the key we don't care about the result at this point.
7800 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007801
David Drysdale513bf122021-10-06 11:53:13 +01007802 // Now create an invalid key blob and delete it.
7803 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007804
David Drysdale513bf122021-10-06 11:53:13 +01007805 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007806}
7807
7808/**
7809 * KeyDeletionTest.DeleteAllKeys
7810 *
7811 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7812 *
7813 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7814 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7815 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7816 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7817 * credentials stored in Keystore/Keymint.
7818 */
7819TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007820 if (!arm_deleteAllKeys) {
7821 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7822 return;
7823 }
Selene Huang31ab4042020-04-29 04:22:39 -07007824 auto error = GenerateKey(AuthorizationSetBuilder()
7825 .RsaSigningKey(2048, 65537)
7826 .Digest(Digest::NONE)
7827 .Padding(PaddingMode::NONE)
7828 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007829 .Authorization(TAG_ROLLBACK_RESISTANCE)
7830 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007831 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7832 GTEST_SKIP() << "Rollback resistance not supported";
7833 }
Selene Huang31ab4042020-04-29 04:22:39 -07007834
7835 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007836 ASSERT_EQ(ErrorCode::OK, error);
7837 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7838 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007839
David Drysdale513bf122021-10-06 11:53:13 +01007840 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007841
David Drysdale513bf122021-10-06 11:53:13 +01007842 string message = "12345678901234567890123456789012";
7843 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07007844
David Drysdale513bf122021-10-06 11:53:13 +01007845 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7846 Begin(KeyPurpose::SIGN, key_blob_,
7847 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7848 &begin_out_params));
7849 AbortIfNeeded();
7850 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007851}
7852
7853INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
7854
David Drysdaled2cc8c22021-04-15 13:29:45 +01007855typedef KeyMintAidlTestBase KeyUpgradeTest;
7856
7857/**
7858 * KeyUpgradeTest.UpgradeInvalidKey
7859 *
7860 * This test checks that the HAL excepts invalid key blobs..
7861 */
7862TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
7863 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
7864
7865 std::vector<uint8_t> new_blob;
7866 Status result = keymint_->upgradeKey(key_blob,
7867 AuthorizationSetBuilder()
7868 .Authorization(TAG_APPLICATION_ID, "clientid")
7869 .Authorization(TAG_APPLICATION_DATA, "appdata")
7870 .vector_data(),
7871 &new_blob);
7872 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
7873}
7874
7875INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
7876
Selene Huang31ab4042020-04-29 04:22:39 -07007877using UpgradeKeyTest = KeyMintAidlTestBase;
7878
7879/*
7880 * UpgradeKeyTest.UpgradeKey
7881 *
7882 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
7883 */
7884TEST_P(UpgradeKeyTest, UpgradeKey) {
7885 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7886 .AesEncryptionKey(128)
7887 .Padding(PaddingMode::NONE)
7888 .Authorization(TAG_NO_AUTH_REQUIRED)));
7889
7890 auto result = UpgradeKey(key_blob_);
7891
7892 // Key doesn't need upgrading. Should get okay, but no new key blob.
7893 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
7894}
7895
7896INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
7897
7898using ClearOperationsTest = KeyMintAidlTestBase;
7899
7900/*
7901 * ClearSlotsTest.TooManyOperations
7902 *
7903 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
7904 * operations are started without being finished or aborted. Also verifies
7905 * that aborting the operations clears the operations.
7906 *
7907 */
7908TEST_P(ClearOperationsTest, TooManyOperations) {
7909 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7910 .Authorization(TAG_NO_AUTH_REQUIRED)
7911 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08007912 .Padding(PaddingMode::NONE)
7913 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007914
7915 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
7916 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08007917 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07007918 AuthorizationSet out_params;
7919 ErrorCode result;
7920 size_t i;
7921
7922 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00007923 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07007924 if (ErrorCode::OK != result) {
7925 break;
7926 }
7927 }
7928 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
7929 // Try again just in case there's a weird overflow bug
7930 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00007931 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007932 for (size_t j = 0; j < i; j++) {
7933 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
7934 << "Aboort failed for i = " << j << std::endl;
7935 }
David Drysdale7fc26b92022-05-13 09:54:24 +01007936 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007937 AbortIfNeeded();
7938}
7939
7940INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
7941
7942typedef KeyMintAidlTestBase TransportLimitTest;
7943
7944/*
David Drysdale7de9feb2021-03-05 14:56:19 +00007945 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07007946 *
7947 * Verifies that passing input data to finish succeeds as expected.
7948 */
7949TEST_P(TransportLimitTest, LargeFinishInput) {
7950 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7951 .Authorization(TAG_NO_AUTH_REQUIRED)
7952 .AesEncryptionKey(128)
7953 .BlockMode(BlockMode::ECB)
7954 .Padding(PaddingMode::NONE)));
7955
7956 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
7957 auto cipher_params =
7958 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7959
7960 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007961 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007962
7963 string plain_message = std::string(1 << msg_size, 'x');
7964 string encrypted_message;
7965 auto rc = Finish(plain_message, &encrypted_message);
7966
7967 EXPECT_EQ(ErrorCode::OK, rc);
7968 EXPECT_EQ(plain_message.size(), encrypted_message.size())
7969 << "Encrypt finish returned OK, but did not consume all of the given input";
7970 cipher_params.push_back(out_params);
7971
David Drysdale7fc26b92022-05-13 09:54:24 +01007972 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007973
7974 string decrypted_message;
7975 rc = Finish(encrypted_message, &decrypted_message);
7976 EXPECT_EQ(ErrorCode::OK, rc);
7977 EXPECT_EQ(plain_message.size(), decrypted_message.size())
7978 << "Decrypt finish returned OK, did not consume all of the given input";
7979 }
7980}
7981
7982INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
7983
Seth Moored79a0ec2021-12-13 20:03:33 +00007984static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05007985 switch (curve) {
7986 case EcCurve::P_224:
7987 return NID_secp224r1;
7988 case EcCurve::P_256:
7989 return NID_X9_62_prime256v1;
7990 case EcCurve::P_384:
7991 return NID_secp384r1;
7992 case EcCurve::P_521:
7993 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00007994 case EcCurve::CURVE_25519:
7995 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05007996 }
7997}
7998
David Drysdale42fe1892021-10-14 14:43:46 +01007999class KeyAgreementTest : public KeyMintAidlTestBase {
8000 protected:
8001 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8002 std::vector<uint8_t>* localPublicKey) {
8003 // Generate EC key locally (with access to private key material)
8004 if (localCurve == EcCurve::CURVE_25519) {
8005 uint8_t privKeyData[32];
8006 uint8_t pubKeyData[32];
8007 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008008 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8009 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8010 } else {
8011 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8012 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8013 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8014 ASSERT_NE(group, nullptr);
8015 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8016 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8017 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8018 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008019 }
David Drysdalea410b772022-05-09 16:44:13 +01008020
8021 // Get encoded form of the public part of the locally generated key...
8022 unsigned char* p = nullptr;
8023 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8024 ASSERT_GT(localPublicKeySize, 0);
8025 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8026 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8027 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008028 }
8029
8030 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8031 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008032 auto builder = AuthorizationSetBuilder()
8033 .Authorization(TAG_NO_AUTH_REQUIRED)
8034 .Authorization(TAG_EC_CURVE, curve)
8035 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8036 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8037 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8038 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8039 .SetDefaultValidity();
8040 ErrorCode result = GenerateKey(builder);
8041
8042 if (SecLevel() == SecurityLevel::STRONGBOX) {
8043 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8044 result = GenerateKeyWithSelfSignedAttestKey(
8045 AuthorizationSetBuilder()
8046 .EcdsaKey(EcCurve::P_256)
8047 .AttestKey()
8048 .SetDefaultValidity(), /* attest key params */
8049 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8050 }
8051 }
David Drysdale42fe1892021-10-14 14:43:46 +01008052 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8053 ASSERT_GT(cert_chain_.size(), 0);
8054 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8055 ASSERT_NE(kmKeyCert, nullptr);
8056 // Check that keyAgreement (bit 4) is set in KeyUsage
8057 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8058 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8059 ASSERT_NE(*kmPubKey, nullptr);
8060 if (dump_Attestations) {
8061 for (size_t n = 0; n < cert_chain_.size(); n++) {
8062 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8063 }
8064 }
8065 }
8066
8067 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8068 const std::vector<uint8_t>& localPublicKey) {
8069 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8070 string ZabFromKeyMintStr;
8071 ASSERT_EQ(ErrorCode::OK,
8072 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8073 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8074 vector<uint8_t> ZabFromTest;
8075
8076 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8077 size_t kmPubKeySize = 32;
8078 uint8_t kmPubKeyData[32];
8079 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8080 ASSERT_EQ(kmPubKeySize, 32);
8081
8082 uint8_t localPrivKeyData[32];
8083 size_t localPrivKeySize = 32;
8084 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8085 &localPrivKeySize));
8086 ASSERT_EQ(localPrivKeySize, 32);
8087
8088 uint8_t sharedKey[32];
8089 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8090 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8091 } else {
8092 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8093 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8094 ASSERT_NE(ctx, nullptr);
8095 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8096 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8097 size_t ZabFromTestLen = 0;
8098 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8099 ZabFromTest.resize(ZabFromTestLen);
8100 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8101 }
8102 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8103 }
8104};
8105
David Zeuthene0c40892021-01-08 12:54:11 -05008106/*
8107 * KeyAgreementTest.Ecdh
8108 *
David Drysdale42fe1892021-10-14 14:43:46 +01008109 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008110 */
8111TEST_P(KeyAgreementTest, Ecdh) {
8112 // Because it's possible to use this API with keys on different curves, we
8113 // check all N^2 combinations where N is the number of supported
8114 // curves.
8115 //
8116 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8117 // lot more curves we can be smart about things and just pick |otherCurve| so
8118 // it's not |curve| and that way we end up with only 2*N runs
8119 //
8120 for (auto curve : ValidCurves()) {
8121 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008122 SCOPED_TRACE(testing::Message()
8123 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8124
David Zeuthene0c40892021-01-08 12:54:11 -05008125 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008126 EVP_PKEY_Ptr localPrivKey;
8127 vector<uint8_t> localPublicKey;
8128 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008129
8130 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008131 EVP_PKEY_Ptr kmPubKey;
8132 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008133
8134 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8135 if (curve != localCurve) {
8136 // If the keys are using different curves KeyMint should fail with
8137 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008138 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008139 string ZabFromKeyMintStr;
8140 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008141 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008142 &ZabFromKeyMintStr));
8143
8144 } else {
8145 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008146 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008147 }
8148
8149 CheckedDeleteKey();
8150 }
8151 }
8152}
8153
David Drysdale42fe1892021-10-14 14:43:46 +01008154/*
8155 * KeyAgreementTest.EcdhCurve25519
8156 *
8157 * Verifies that ECDH works for curve25519. This is also covered by the general
8158 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8159 * KeyMint 1.0.
8160 */
8161TEST_P(KeyAgreementTest, EcdhCurve25519) {
8162 if (!Curve25519Supported()) {
8163 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8164 }
8165
8166 // Generate EC key in KeyMint (only access to public key material)
8167 EcCurve curve = EcCurve::CURVE_25519;
8168 EVP_PKEY_Ptr kmPubKey = nullptr;
8169 GenerateKeyMintEcKey(curve, &kmPubKey);
8170
8171 // Generate EC key on same curve locally (with access to private key material).
8172 EVP_PKEY_Ptr privKey;
8173 vector<uint8_t> encodedPublicKey;
8174 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8175
8176 // Agree on a key between local and KeyMint and check it.
8177 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8178
8179 CheckedDeleteKey();
8180}
8181
8182/*
8183 * KeyAgreementTest.EcdhCurve25519Imported
8184 *
8185 * Verifies that ECDH works for an imported curve25519 key.
8186 */
8187TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8188 if (!Curve25519Supported()) {
8189 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8190 }
8191
8192 // Import x25519 key into KeyMint.
8193 EcCurve curve = EcCurve::CURVE_25519;
8194 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8195 .Authorization(TAG_NO_AUTH_REQUIRED)
8196 .EcdsaKey(EcCurve::CURVE_25519)
8197 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8198 .SetDefaultValidity(),
8199 KeyFormat::PKCS8, x25519_pkcs8_key));
8200 ASSERT_GT(cert_chain_.size(), 0);
8201 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8202 ASSERT_NE(kmKeyCert, nullptr);
8203 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8204 ASSERT_NE(kmPubKey.get(), nullptr);
8205
8206 // Expect the import to emit corresponding public key data.
8207 size_t kmPubKeySize = 32;
8208 uint8_t kmPubKeyData[32];
8209 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8210 ASSERT_EQ(kmPubKeySize, 32);
8211 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8212 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8213
8214 // Generate EC key on same curve locally (with access to private key material).
8215 EVP_PKEY_Ptr privKey;
8216 vector<uint8_t> encodedPublicKey;
8217 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8218
8219 // Agree on a key between local and KeyMint and check it.
8220 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8221
8222 CheckedDeleteKey();
8223}
8224
8225/*
8226 * KeyAgreementTest.EcdhCurve25519InvalidSize
8227 *
8228 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8229 */
8230TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8231 if (!Curve25519Supported()) {
8232 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8233 }
8234
8235 // Generate EC key in KeyMint (only access to public key material)
8236 EcCurve curve = EcCurve::CURVE_25519;
8237 EVP_PKEY_Ptr kmPubKey = nullptr;
8238 GenerateKeyMintEcKey(curve, &kmPubKey);
8239
8240 // Generate EC key on same curve locally (with access to private key material).
8241 EVP_PKEY_Ptr privKey;
8242 vector<uint8_t> encodedPublicKey;
8243 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8244
8245 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8246 string ZabFromKeyMintStr;
8247 // Send in an incomplete public key.
8248 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8249 &ZabFromKeyMintStr));
8250
8251 CheckedDeleteKey();
8252}
8253
8254/*
8255 * KeyAgreementTest.EcdhCurve25519Mismatch
8256 *
8257 * Verifies that ECDH fails between curve25519 and other curves.
8258 */
8259TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8260 if (!Curve25519Supported()) {
8261 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8262 }
8263
8264 // Generate EC key in KeyMint (only access to public key material)
8265 EcCurve curve = EcCurve::CURVE_25519;
8266 EVP_PKEY_Ptr kmPubKey = nullptr;
8267 GenerateKeyMintEcKey(curve, &kmPubKey);
8268
8269 for (auto localCurve : ValidCurves()) {
8270 if (localCurve == curve) {
8271 continue;
8272 }
8273 // Generate EC key on a different curve locally (with access to private key material).
8274 EVP_PKEY_Ptr privKey;
8275 vector<uint8_t> encodedPublicKey;
8276 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8277
David Drysdale7fc26b92022-05-13 09:54:24 +01008278 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008279 string ZabFromKeyMintStr;
8280 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8281 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8282 &ZabFromKeyMintStr));
8283 }
8284
8285 CheckedDeleteKey();
8286}
8287
David Zeuthene0c40892021-01-08 12:54:11 -05008288INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8289
David Drysdaled2cc8c22021-04-15 13:29:45 +01008290using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8291
8292// This is a problematic test, as it can render the device under test permanently unusable.
8293// Re-enable and run at your own risk.
8294TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8295 auto result = DestroyAttestationIds();
8296 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8297}
8298
8299INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8300
Shawn Willdend659c7c2021-02-19 14:51:51 -07008301using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008302
David Drysdaledb0dcf52021-05-18 11:43:31 +01008303/*
8304 * EarlyBootKeyTest.CreateEarlyBootKeys
8305 *
8306 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8307 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008308TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008309 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008310 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8311 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8312
David Drysdaleadfe6112021-05-27 12:00:53 +01008313 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8314 ASSERT_GT(keyData.blob.size(), 0U);
8315 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8316 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8317 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008318 CheckedDeleteKey(&aesKeyData.blob);
8319 CheckedDeleteKey(&hmacKeyData.blob);
8320 CheckedDeleteKey(&rsaKeyData.blob);
8321 CheckedDeleteKey(&ecdsaKeyData.blob);
8322}
8323
David Drysdaledb0dcf52021-05-18 11:43:31 +01008324/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008325 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8326 *
8327 * Verifies that creating an early boot key with attestation succeeds.
8328 */
8329TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8330 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8331 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8332 builder->AttestationChallenge("challenge");
8333 builder->AttestationApplicationId("app_id");
8334 });
8335
8336 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008337 // Strongbox may not support factory attestation. Key creation might fail with
8338 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8339 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8340 continue;
8341 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008342 ASSERT_GT(keyData.blob.size(), 0U);
8343 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8344 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8345 }
8346 CheckedDeleteKey(&aesKeyData.blob);
8347 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00008348 if (rsaKeyData.blob.size() != 0U) {
8349 CheckedDeleteKey(&rsaKeyData.blob);
8350 }
8351 if (ecdsaKeyData.blob.size() != 0U) {
8352 CheckedDeleteKey(&ecdsaKeyData.blob);
8353 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008354}
8355
8356/*
8357 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008358 *
8359 * Verifies that using early boot keys at a later stage fails.
8360 */
8361TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8362 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8363 .Authorization(TAG_NO_AUTH_REQUIRED)
8364 .Authorization(TAG_EARLY_BOOT_ONLY)
8365 .HmacKey(128)
8366 .Digest(Digest::SHA_2_256)
8367 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8368 AuthorizationSet output_params;
8369 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8370 AuthorizationSetBuilder()
8371 .Digest(Digest::SHA_2_256)
8372 .Authorization(TAG_MAC_LENGTH, 256),
8373 &output_params));
8374}
8375
8376/*
8377 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8378 *
8379 * Verifies that importing early boot keys fails.
8380 */
8381TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8382 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8383 .Authorization(TAG_NO_AUTH_REQUIRED)
8384 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008385 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008386 .Digest(Digest::SHA_2_256)
8387 .SetDefaultValidity(),
8388 KeyFormat::PKCS8, ec_256_key));
8389}
8390
David Drysdaled2cc8c22021-04-15 13:29:45 +01008391// 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 +00008392// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8393// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8394// early boot, so you'll have to reboot between runs.
8395TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8396 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8397 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8398 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8399 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8400 EXPECT_TRUE(
8401 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8402 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8403 EXPECT_TRUE(
8404 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8405
8406 // Should be able to use keys, since early boot has not ended
8407 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8408 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8409 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8410 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8411
8412 // End early boot
8413 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8414 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8415
8416 // Should not be able to use already-created keys.
8417 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8418 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8419 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8420 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8421
8422 CheckedDeleteKey(&aesKeyData.blob);
8423 CheckedDeleteKey(&hmacKeyData.blob);
8424 CheckedDeleteKey(&rsaKeyData.blob);
8425 CheckedDeleteKey(&ecdsaKeyData.blob);
8426
8427 // Should not be able to create new keys
8428 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
8429 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
8430
8431 CheckedDeleteKey(&aesKeyData.blob);
8432 CheckedDeleteKey(&hmacKeyData.blob);
8433 CheckedDeleteKey(&rsaKeyData.blob);
8434 CheckedDeleteKey(&ecdsaKeyData.blob);
8435}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008436
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008437INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8438
Shawn Willdend659c7c2021-02-19 14:51:51 -07008439using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008440
8441// This may be a problematic test. It can't be run repeatedly without unlocking the device in
8442// between runs... and on most test devices there are no enrolled credentials so it can't be
8443// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8444// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8445// a manual test process, which includes unlocking between runs, which is why it's included here.
8446// Well, that and the fact that it's the only test we can do without also making calls into the
8447// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8448// implications might be, so that may or may not be a solution.
8449TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8450 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8451 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
8452
8453 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8454 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8455 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8456 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8457
8458 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008459 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008460 ASSERT_EQ(ErrorCode::OK, rc);
8461 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8462 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8463 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8464 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
8465
8466 CheckedDeleteKey(&aesKeyData.blob);
8467 CheckedDeleteKey(&hmacKeyData.blob);
8468 CheckedDeleteKey(&rsaKeyData.blob);
8469 CheckedDeleteKey(&ecdsaKeyData.blob);
8470}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008471
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008472INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8473
Shawn Willden22fb9c12022-06-02 14:04:33 -06008474using VsrRequirementTest = KeyMintAidlTestBase;
8475
8476TEST_P(VsrRequirementTest, Vsr13Test) {
8477 int vsr_api_level = get_vsr_api_level();
8478 if (vsr_api_level < 33) {
8479 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8480 }
8481 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8482}
8483
8484INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8485
Janis Danisevskis24c04702020-12-16 18:28:39 -08008486} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008487
8488int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008489 std::cout << "Testing ";
8490 auto halInstances =
8491 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8492 std::cout << "HAL instances:\n";
8493 for (auto& entry : halInstances) {
8494 std::cout << " " << entry << '\n';
8495 }
8496
Selene Huang31ab4042020-04-29 04:22:39 -07008497 ::testing::InitGoogleTest(&argc, argv);
8498 for (int i = 1; i < argc; ++i) {
8499 if (argv[i][0] == '-') {
8500 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008501 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8502 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008503 }
8504 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008505 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8506 dump_Attestations = true;
8507 } else {
8508 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008509 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008510 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8511 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8512 // be run in emulated environments that don't have the normal bootloader
8513 // interactions.
8514 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8515 }
Selene Huang31ab4042020-04-29 04:22:39 -07008516 }
8517 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008518 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008519}