blob: 641a227b5988a6fc65d119ce7ca77596b5bc6d4b [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
David Drysdale37af4b32021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Drysdale42fe1892021-10-14 14:43:46 +010025#include <openssl/curve25519.h>
David Zeuthene0c40892021-01-08 12:54:11 -050026#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070027#include <openssl/evp.h>
28#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050029#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070030
31#include <cutils/properties.h>
32
David Drysdale4dc01072021-04-01 12:17:35 +010033#include <android/binder_manager.h>
34
35#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080036#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070037
Shawn Willden08a7e432020-12-11 13:05:27 +000038#include <keymint_support/key_param_output.h>
39#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070040
41#include "KeyMintAidlTestBase.h"
42
Janis Danisevskis24c04702020-12-16 18:28:39 -080043using aidl::android::hardware::security::keymint::AuthorizationSet;
44using aidl::android::hardware::security::keymint::KeyCharacteristics;
45using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070046
Selene Huang31ab4042020-04-29 04:22:39 -070047namespace std {
48
Janis Danisevskis24c04702020-12-16 18:28:39 -080049using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070050
51template <>
52struct std::equal_to<KeyCharacteristics> {
53 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070054 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070055
Shawn Willden7f424372021-01-10 18:06:50 -070056 // this isn't very efficient. Oh, well.
57 AuthorizationSet a_auths(a.authorizations);
58 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070059
Shawn Willden7f424372021-01-10 18:06:50 -070060 a_auths.Sort();
61 b_auths.Sort();
62
63 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070064 }
65};
66
67} // namespace std
68
Janis Danisevskis24c04702020-12-16 18:28:39 -080069namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000070
Selene Huang31ab4042020-04-29 04:22:39 -070071namespace {
72
David Drysdalefeab5d92022-01-06 15:46:23 +000073// Maximum supported Ed25519 message size.
74const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
75
David Drysdaledbbbe2e2021-12-02 07:44:23 +000076// Whether to check that BOOT_PATCHLEVEL is populated.
77bool check_boot_pl = true;
78
Seth Moore7a55ae32021-06-23 14:28:11 -070079// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000080// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070081// is a small (roughly 1/256) chance that corrupting ciphertext still results
82// in valid PKCS7 padding.
83constexpr size_t kMaxPaddingCorruptionRetries = 8;
84
Selene Huang31ab4042020-04-29 04:22:39 -070085template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000086bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
87 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070088 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080089 if (auto p = authorizationValue(ttag, param)) {
90 return *p == expected_value;
91 }
92 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070093 });
94 return (it != set.end());
95}
96
97template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000098bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070099 auto it = std::find_if(set.begin(), set.end(),
100 [&](const KeyParameter& param) { return param.tag == tag; });
101 return (it != set.end());
102}
103
104constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
108 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
110 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
111 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
114 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
115 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
117 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
120
121string hex2str(string a) {
122 string b;
123 size_t num = a.size() / 2;
124 b.resize(num);
125 for (size_t i = 0; i < num; i++) {
126 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
127 }
128 return b;
129}
130
David Drysdaled2cc8c22021-04-15 13:29:45 +0100131string rsa_key = hex2str(
132 // RFC 5208 s5
133 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
134 "020100" // INTEGER length 1 value 0x00 (version)
135 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
136 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
137 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
138 "0500" // NULL (parameters)
139 // } end SEQUENCE (AlgorithmIdentifier)
140 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
141 // RFC 8017 A.1.2
142 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
143 "020100" // INTEGER length 1 value 0x00 (version)
144 "028181" // INTEGER length 0x81 value (modulus) ...
145 "00c6095409047d8634812d5a218176e4"
146 "5c41d60a75b13901f234226cffe77652"
147 "1c5a77b9e389417b71c0b6a44d13afe4"
148 "e4a2805d46c9da2935adb1ff0c1f24ea"
149 "06e62b20d776430a4d435157233c6f91"
150 "6783c30e310fcbd89b85c2d567711697"
151 "85ac12bca244abda72bfb19fc44d27c8"
152 "1e1d92de284f4061edfd99280745ea6d"
153 "25"
154 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
155 "028180" // INTEGER length 0x80 (privateExponent) value...
156 "1be0f04d9cae3718691f035338308e91"
157 "564b55899ffb5084d2460e6630257e05"
158 "b3ceab02972dfabcd6ce5f6ee2589eb6"
159 "7911ed0fac16e43a444b8c861e544a05"
160 "93365772f8baf6b22fc9e3c5f1024b06"
161 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
162 "ace7240290bef16c0b3f7f3cdd64ce3a"
163 "b5912cf6e32f39ab188358afcccd8081"
164 "0241" // INTEGER length 0x41 (prime1)
165 "00e4b49ef50f765d3b24dde01aceaaf1"
166 "30f2c76670a91a61ae08af497b4a82be"
167 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
168 "8c92bfab137fba2285227b83c342ff7c"
169 "55"
170 "0241" // INTEGER length 0x41 (prime2)
171 "00ddabb5839c4c7f6bf3d4183231f005"
172 "b31aa58affdda5c79e4cce217f6bc930"
173 "dbe563d480706c24e9ebfcab28a6cdef"
174 "d324b77e1bf7251b709092c24ff501fd"
175 "91"
176 "0240" // INTEGER length 0x40 (exponent1)
177 "23d4340eda3445d8cd26c14411da6fdc"
178 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
179 "842c1d280405bc2f6c1bea214a1d742a"
180 "b996b35b63a82a5e470fa88dbf823cdd"
181 "0240" // INTEGER length 0x40 (exponent2)
182 "1b7b57449ad30d1518249a5f56bb9829"
183 "4d4b6ac12ffc86940497a5a5837a6cf9"
184 "46262b494526d328c11e1126380fde04"
185 "c24f916dec250892db09a6d77cdba351"
186 "0240" // INTEGER length 0x40 (coefficient)
187 "7762cd8f4d050da56bd591adb515d24d"
188 "7ccd32cca0d05f866d583514bd7324d5"
189 "f33645e8ed8b4a1cb3cc4a1d67987399"
190 "f2a09f5b3fb68c88d5e5d90ac33492d6"
191 // } end SEQUENCE (PrivateKey)
192 // } end SEQUENCE (PrivateKeyInfo)
193);
Selene Huang31ab4042020-04-29 04:22:39 -0700194
Selene Huange5727e62021-04-13 22:41:20 -0700195/*
196 * DER-encoded PKCS#8 format RSA key. Generated using:
197 *
198 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
199 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100200string rsa_2048_key = hex2str(
201 // RFC 5208 s5
202 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
203 "020100" // INTEGER length 1 value 0x00 (version)
204 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
205 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
206 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
207 "0500" // NULL (parameters)
208 // } end SEQUENCE (AlgorithmIdentifier)
209 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
210 // RFC 8017 A.1.2
211 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
212 "020100" // INTEGER length 1 value 0x00 (version)
213 "02820101" // INTEGER length 0x101 value (modulus) ...
214 "00BEBC342B56D443B1299F9A6A7056E8"
215 "0A897E318476A5A18029E63B2ED739A6"
216 "1791D339F58DC763D9D14911F2EDEC38"
217 "3DEE11F6319B44510E7A3ECD9B79B973"
218 "82E49500ACF8117DC89CAF0E621F7775"
219 "6554A2FD4664BFE7AB8B59AB48340DBF"
220 "A27B93B5A81F6ECDEB02D0759307128D"
221 "F3E3BAD4055C8B840216DFAA5700670E"
222 "6C5126F0962FCB70FF308F25049164CC"
223 "F76CC2DA66A7DD9A81A714C2809D6918"
224 "6133D29D84568E892B6FFBF3199BDB14"
225 "383EE224407F190358F111A949552ABA"
226 "6714227D1BD7F6B20DD0CB88F9467B71"
227 "9339F33BFF35B3870B3F62204E4286B0"
228 "948EA348B524544B5F9838F29EE643B0"
229 "79EEF8A713B220D7806924CDF7295070"
230 "C5"
231 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
232 "02820100" // INTEGER length 0x100 (privateExponent) value...
233 "69F377F35F2F584EF075353CCD1CA997"
234 "38DB3DBC7C7FF35F9366CE176DFD1B13"
235 "5AB10030344ABF5FBECF1D4659FDEF1C"
236 "0FC430834BE1BE3911951377BB3D563A"
237 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
238 "2686C7B4B3C09A7B8354133E6F93F790"
239 "D59EAEB92E84C9A4339302CCE28FDF04"
240 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
241 "6AB706645BF074A4E4090D06FB163124"
242 "365FD5EE7A20D350E9958CC30D91326E"
243 "1B292E9EF5DB408EC42DAF737D201497"
244 "04D0A678A0FB5B5446863B099228A352"
245 "D604BA8091A164D01D5AB05397C71EAD"
246 "20BE2A08FC528FE442817809C787FEE4"
247 "AB97F97B9130D022153EDC6EB6CBE7B0"
248 "F8E3473F2E901209B5DB10F93604DB01"
249 "028181" // INTEGER length 0x81 (prime1)
250 "00E83C0998214941EA4F9293F1B77E2E"
251 "99E6CF305FAF358238E126124FEAF2EB"
252 "9724B2EA7B78E6032343821A80E55D1D"
253 "88FB12D220C3F41A56142FEC85796D19"
254 "17F1E8C774F142B67D3D6E7B7E6B4383"
255 "E94DB5929089DBB346D5BDAB40CC2D96"
256 "EE0409475E175C63BF78CFD744136740"
257 "838127EA723FF3FE7FA368C1311B4A4E"
258 "05"
259 "028181" // INTEGER length 0x81 (prime2)
260 "00D240FCC0F5D7715CDE21CB2DC86EA1"
261 "46132EA3B06F61FF2AF54BF38473F59D"
262 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
263 "B1B58C39F95E4798CCBB43E83D0119AC"
264 "F532F359CA743C85199F0286610E2009"
265 "97D7312917179AC9B67558773212EC96"
266 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
267 "94D94E066A0900B7B70E82A44FB30053"
268 "C1"
269 "028181" // INTEGER length 0x81 (exponent1)
270 "00AD15DA1CBD6A492B66851BA8C316D3"
271 "8AB700E2CFDDD926A658003513C54BAA"
272 "152B30021D667D20078F500F8AD3E7F3"
273 "945D74A891ED1A28EAD0FEEAEC8C14A8"
274 "E834CF46A13D1378C99D18940823CFDD"
275 "27EC5810D59339E0C34198AC638E09C8"
276 "7CBB1B634A9864AE9F4D5EB2D53514F6"
277 "7B4CAEC048C8AB849A02E397618F3271"
278 "35"
279 "028180" // INTEGER length 0x80 (exponent2)
280 "1FA2C1A5331880A92D8F3E281C617108"
281 "BF38244F16E352E69ED417C7153F9EC3"
282 "18F211839C643DCF8B4DD67CE2AC312E"
283 "95178D5D952F06B1BF779F4916924B70"
284 "F582A23F11304E02A5E7565AE22A35E7"
285 "4FECC8B6FDC93F92A1A37703E4CF0E63"
286 "783BD02EB716A7ECBBFA606B10B74D01"
287 "579522E7EF84D91FC522292108D902C1"
288 "028180" // INTEGER length 0x80 (coefficient)
289 "796FE3825F9DCC85DF22D58690065D93"
290 "898ACD65C087BEA8DA3A63BF4549B795"
291 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
292 "0D74F40DED8E1102C52152A31B6165F8"
293 "3A6722AECFCC35A493D7634664B888A0"
294 "8D3EB034F12EA28BFEE346E205D33482"
295 "7F778B16ED40872BD29FCB36536B6E93"
296 "FFB06778696B4A9D81BB0A9423E63DE5"
297 // } end SEQUENCE (PrivateKey)
298 // } end SEQUENCE (PrivateKeyInfo)
299);
Selene Huange5727e62021-04-13 22:41:20 -0700300
David Drysdaled2cc8c22021-04-15 13:29:45 +0100301string ec_256_key = hex2str(
302 // RFC 5208 s5
303 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
304 "020100" // INTEGER length 1 value 0 (version)
305 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
306 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
307 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
308 "0608" // OBJECT IDENTIFIER length 8 (param)
309 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
310 // } end SEQUENCE (AlgorithmIdentifier)
311 "046d" // OCTET STRING length 0x6d (privateKey) holding...
312 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
313 "020101" // INTEGER length 1 value 1 (version)
314 "0420" // OCTET STRING length 0x20 (privateKey)
315 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
316 "941eed09366bc03299986481f3a4d859"
317 "a144" // TAG [1] len 0x44 (publicKey) {
318 "03420004bf85d7720d07c25461683bc6"
319 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
320 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
321 "bcc41c6eb00083cf3376d11fd44949e0"
322 "b2183bfe"
323 // } end SEQUENCE (ECPrivateKey)
324 // } end SEQUENCE (PrivateKeyInfo)
325);
Selene Huang31ab4042020-04-29 04:22:39 -0700326
David Drysdaled2cc8c22021-04-15 13:29:45 +0100327string ec_521_key = hex2str(
328 // RFC 5208 s5
329 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
330 "020100" // INTEGER length 1 value 0 (version)
331 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
332 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
333 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
334 "0605" // OBJECT IDENTIFIER length 5 (param)
335 "2B81040023" // 1.3.132.0.35 (secp521r1)
336 // } end SEQUENCE (AlgorithmIdentifier)
337 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
338 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
339 "020101" // INTEGER length 1 value 1 (version)
340 "0442" // OCTET STRING length 0x42 (privateKey)
341 "0011458C586DB5DAA92AFAB03F4FE46A"
342 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
343 "9D18D7D08B5BCFA0E53C75B064AD51C4"
344 "49BAE0258D54B94B1E885DED08ED4FB2"
345 "5CE9"
346 "A18189" // TAG [1] len 0x89 (publicKey) {
347 "03818600040149EC11C6DF0FA122C6A9"
348 "AFD9754A4FA9513A627CA329E349535A"
349 "5629875A8ADFBE27DCB932C051986377"
350 "108D054C28C6F39B6F2C9AF81802F9F3"
351 "26B842FF2E5F3C00AB7635CFB36157FC"
352 "0882D574A10D839C1A0C049DC5E0D775"
353 "E2EE50671A208431BB45E78E70BEFE93"
354 "0DB34818EE4D5C26259F5C6B8E28A652"
355 "950F9F88D7B4B2C9D9"
356 // } end SEQUENCE (ECPrivateKey)
357 // } end SEQUENCE (PrivateKeyInfo)
358);
Selene Huang31ab4042020-04-29 04:22:39 -0700359
David Drysdaled2cc8c22021-04-15 13:29:45 +0100360string ec_256_key_rfc5915 = hex2str(
361 // RFC 5208 s5
362 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
363 "020100" // INTEGER length 1 value 0 (version)
364 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
365 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
366 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
367 "0608" // OBJECT IDENTIFIER length 8 (param)
368 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
369 // } end SEQUENCE (AlgorithmIdentifier)
370 "0479" // OCTET STRING length 0x79 (privateKey) holding...
371 // RFC 5915 s3
372 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
373 "020101" // INTEGER length 1 value 1 (version)
374 "0420" // OCTET STRING length 0x42 (privateKey)
375 "782370a8c8ce5537baadd04dcff079c8"
376 "158cfa9c67b818b38e8d21c9fa750c1d"
377 "a00a" // TAG [0] length 0xa (parameters)
378 "0608" // OBJECT IDENTIFIER length 8
379 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
380 // } end TAG [0]
381 "a144" // TAG [1] length 0x44 (publicKey) {
382 "0342" // BIT STRING length 0x42
383 "00" // no pad bits
384 "04e2cc561ee701da0ad0ef0d176bb0c9"
385 "19d42e79c393fdc1bd6c4010d85cf2cf"
386 "8e68c905464666f98dad4f01573ba810"
387 "78b3428570a439ba3229fbc026c55068"
388 "2f"
389 // } end SEQUENCE (ECPrivateKey)
390 // } end SEQUENCE (PrivateKeyInfo)
391);
Selene Huang31ab4042020-04-29 04:22:39 -0700392
David Drysdaled2cc8c22021-04-15 13:29:45 +0100393string ec_256_key_sec1 = hex2str(
394 // RFC 5208 s5
395 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
396 "020100" // INTEGER length 1 value 0 (version)
397 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
398 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
399 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
400 "0608" // OBJECT IDENTIFIER length 8 (param)
401 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
402 // } end SEQUENCE (AlgorithmIdentifier)
403 "046d" // OCTET STRING length 0x6d (privateKey) holding...
404 // SEC1-v2 C.4
405 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
406 "020101" // INTEGER length 1 value 0x01 (version)
407 "0420" // OCTET STRING length 0x20 (privateKey)
408 "782370a8c8ce5537baadd04dcff079c8"
409 "158cfa9c67b818b38e8d21c9fa750c1d"
410 "a144" // TAG [1] length 0x44 (publicKey) {
411 "0342" // BIT STRING length 0x42
412 "00" // no pad bits
413 "04e2cc561ee701da0ad0ef0d176bb0c9"
414 "19d42e79c393fdc1bd6c4010d85cf2cf"
415 "8e68c905464666f98dad4f01573ba810"
416 "78b3428570a439ba3229fbc026c55068"
417 "2f"
418 // } end TAG [1] (publicKey)
419 // } end SEQUENCE (PrivateKeyInfo)
420);
Selene Huang31ab4042020-04-29 04:22:39 -0700421
David Drysdale42fe1892021-10-14 14:43:46 +0100422/**
423 * Ed25519 key pair generated as follows:
424 * ```
425 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
426 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
427 * Generating a ED25519 private key writing new private key to
428 * 'ed25519_priv.key'
429 * -----
430 * % cat ed25519_priv.key
431 * -----BEGIN PRIVATE KEY-----
432 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
433 * -----END PRIVATE KEY-----
434 * % der2ascii -pem -i ed25519_priv.key
435 * SEQUENCE {
436 * INTEGER { 0 }
437 * SEQUENCE {
438 * # ed25519
439 * OBJECT_IDENTIFIER { 1.3.101.112 }
440 * }
441 * OCTET_STRING {
442 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
443 * }
444 * }
445 * % cat ed25519.pem
446 * -----BEGIN CERTIFICATE-----
447 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
448 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
449 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
450 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
451 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
452 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
453 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
454 * -----END CERTIFICATE-----
455 * % openssl x509 -in ed25519.pem -text -noout
456 * Certificate:
457 * Data:
458 * Version: 3 (0x2)
459 * Serial Number:
460 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
461 * Signature Algorithm: ED25519
462 * Issuer: CN = fake.ed25519.com
463 * Validity
464 * Not Before: Oct 20 08:27:42 2021 GMT
465 * Not After : Sep 20 08:27:42 2023 GMT
466 * Subject: CN = fake.ed25519.com
467 * Subject Public Key Info:
468 * Public Key Algorithm: ED25519
469 * ED25519 Public-Key:
470 * pub:
471 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
472 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
473 * 56:91
474 * X509v3 extensions:
475 * X509v3 Subject Key Identifier:
476 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
477 * X509v3 Authority Key Identifier:
478 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
479 *
480 * X509v3 Basic Constraints: critical
481 * CA:TRUE
482 * Signature Algorithm: ED25519
483 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
484 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
485 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
486 * e7:07:32:60:32:8d:bb:eb:f6:0f
487 * ```
488 */
489string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
490string ed25519_pkcs8_key = hex2str(
491 // RFC 5208 s5
492 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
493 "0201" // INTEGER length 1 (Version)
494 "00" // version 0
495 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
496 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
497 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
498 // } end SEQUENCE (AlgorithmIdentifier)
499 "0422" // OCTET STRING length 0x22 (PrivateKey)
500 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
501 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
502 // } end SEQUENCE (PrivateKeyInfo)
503);
504string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
505
506/**
507 * X25519 key pair generated as follows:
508 * ```
509 * % openssl genpkey -algorithm X25519 > x25519_priv.key
510 * % cat x25519_priv.key
511 * -----BEGIN PRIVATE KEY-----
512 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
513 * -----END PRIVATE KEY-----
514 * % der2ascii -pem -i x25519_priv.key
515 * SEQUENCE {
516 * INTEGER { 0 }
517 * SEQUENCE {
518 * # x25519
519 * OBJECT_IDENTIFIER { 1.3.101.110 }
520 * }
521 * OCTET_STRING {
522 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
523 * }
524 * }
525 * ```
526 */
527
528string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
529string x25519_pkcs8_key = hex2str(
530 // RFC 5208 s5
531 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
532 "0201" // INTEGER length 1 (Version)
533 "00" // version 0
534 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
535 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
536 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
537 "0422" // OCTET STRING length 0x22 (PrivateKey)
538 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
539 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
540string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
541
Selene Huang31ab4042020-04-29 04:22:39 -0700542struct RSA_Delete {
543 void operator()(RSA* p) { RSA_free(p); }
544};
545
Selene Huang31ab4042020-04-29 04:22:39 -0700546std::string make_string(const uint8_t* data, size_t length) {
547 return std::string(reinterpret_cast<const char*>(data), length);
548}
549
550template <size_t N>
551std::string make_string(const uint8_t (&a)[N]) {
552 return make_string(a, N);
553}
554
555class AidlBuf : public vector<uint8_t> {
556 typedef vector<uint8_t> super;
557
558 public:
559 AidlBuf() {}
560 AidlBuf(const super& other) : super(other) {}
561 AidlBuf(super&& other) : super(std::move(other)) {}
562 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
563
564 AidlBuf& operator=(const super& other) {
565 super::operator=(other);
566 return *this;
567 }
568
569 AidlBuf& operator=(super&& other) {
570 super::operator=(std::move(other));
571 return *this;
572 }
573
574 AidlBuf& operator=(const string& other) {
575 resize(other.size());
576 for (size_t i = 0; i < other.size(); ++i) {
577 (*this)[i] = static_cast<uint8_t>(other[i]);
578 }
579 return *this;
580 }
581
582 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
583};
584
David Drysdale4dc01072021-04-01 12:17:35 +0100585string device_suffix(const string& name) {
586 size_t pos = name.find('/');
587 if (pos == string::npos) {
588 return name;
589 }
590 return name.substr(pos + 1);
591}
592
593bool matching_rp_instance(const string& km_name,
594 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
595 string km_suffix = device_suffix(km_name);
596
597 vector<string> rp_names =
598 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
599 for (const string& rp_name : rp_names) {
600 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
601 // KeyMint instance, assume they match.
602 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
603 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
604 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
605 return true;
606 }
607 }
608 return false;
609}
610
Selene Huang31ab4042020-04-29 04:22:39 -0700611} // namespace
612
613class NewKeyGenerationTest : public KeyMintAidlTestBase {
614 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700615 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000616 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700617 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700618
Selene Huang31ab4042020-04-29 04:22:39 -0700619 // Check that some unexpected tags/values are NOT present.
620 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
621 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000622 }
623
624 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
625 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
626 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
627 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
628
629 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000630 }
631
632 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
633 // TODO(swillden): Distinguish which params should be in which auth list.
634 AuthorizationSet auths;
635 for (auto& entry : keyCharacteristics) {
636 auths.push_back(AuthorizationSet(entry.authorizations));
637 }
638 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
639
640 // Verify that App data, ROT and auth timeout are NOT included.
641 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
642 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700643 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
644
David Drysdaled2cc8c22021-04-15 13:29:45 +0100645 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
646 // never adds it.
647 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
648
David Drysdale7de9feb2021-03-05 14:56:19 +0000649 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700650 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000651 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700652 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700653 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000654 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700655 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000656
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000657 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100658 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
659 EXPECT_TRUE(vendor_pl);
660 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000661
662 // Should include boot patchlevel (but there are some test scenarios where this is not
663 // possible).
664 if (check_boot_pl) {
665 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
666 EXPECT_TRUE(boot_pl);
667 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100668
David Drysdale7de9feb2021-03-05 14:56:19 +0000669 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700670 }
671};
672
673/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000674 * NewKeyGenerationTest.Aes
675 *
676 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
677 * have correct characteristics.
678 */
679TEST_P(NewKeyGenerationTest, Aes) {
680 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
681 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
682 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
683 SCOPED_TRACE(testing::Message()
684 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
685 vector<uint8_t> key_blob;
686 vector<KeyCharacteristics> key_characteristics;
687 auto builder = AuthorizationSetBuilder()
688 .AesEncryptionKey(key_size)
689 .BlockMode(block_mode)
690 .Padding(padding_mode)
691 .SetDefaultValidity();
692 if (block_mode == BlockMode::GCM) {
693 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
694 }
695 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
696
697 EXPECT_GT(key_blob.size(), 0U);
698 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100699 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000700
701 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
702
703 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
704 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
705 << "Key size " << key_size << "missing";
706
707 CheckedDeleteKey(&key_blob);
708 }
709 }
710 }
711}
712
713/*
714 * NewKeyGenerationTest.AesInvalidSize
715 *
716 * Verifies that specifying an invalid key size for AES key generation returns
717 * UNSUPPORTED_KEY_SIZE.
718 */
719TEST_P(NewKeyGenerationTest, AesInvalidSize) {
720 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
721 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
722 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
723 SCOPED_TRACE(testing::Message()
724 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
725 vector<uint8_t> key_blob;
726 vector<KeyCharacteristics> key_characteristics;
727 auto builder = AuthorizationSetBuilder()
728 .AesEncryptionKey(key_size)
729 .BlockMode(block_mode)
730 .Padding(padding_mode)
731 .SetDefaultValidity();
732 if (block_mode == BlockMode::GCM) {
733 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
734 }
735 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
736 GenerateKey(builder, &key_blob, &key_characteristics));
737 }
738 }
739 }
740
741 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
742 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
743 vector<uint8_t> key_blob;
744 vector<KeyCharacteristics> key_characteristics;
745 // No key size specified
746 auto builder = AuthorizationSetBuilder()
747 .Authorization(TAG_ALGORITHM, Algorithm::AES)
748 .BlockMode(block_mode)
749 .Padding(padding_mode)
750 .SetDefaultValidity();
751 if (block_mode == BlockMode::GCM) {
752 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
753 }
754 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
755 GenerateKey(builder, &key_blob, &key_characteristics));
756 }
757 }
758}
759
760/*
761 * NewKeyGenerationTest.AesInvalidPadding
762 *
763 * Verifies that specifying an invalid padding on AES keys gives a failure
764 * somewhere along the way.
765 */
766TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
767 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
768 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
769 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
770 SCOPED_TRACE(testing::Message()
771 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000772 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800773 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000774 .AesEncryptionKey(key_size)
775 .BlockMode(block_mode)
776 .Padding(padding_mode)
777 .SetDefaultValidity();
778 if (block_mode == BlockMode::GCM) {
779 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
780 }
781
Tommy Chiu3950b452021-05-03 22:01:46 +0800782 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000783 if (result == ErrorCode::OK) {
784 // Key creation was OK but has generated a key that cannot be used.
785 auto params =
786 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800787 if (block_mode == BlockMode::GCM) {
788 params.Authorization(TAG_MAC_LENGTH, 128);
789 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000790 auto result = Begin(KeyPurpose::ENCRYPT, params);
791 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100792 result == ErrorCode::INVALID_KEY_BLOB)
793 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000794 } else {
795 // The KeyMint implementation detected that the generated key
796 // is unusable.
797 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
798 }
799 }
800 }
801 }
802}
803
804/*
805 * NewKeyGenerationTest.AesGcmMissingMinMac
806 *
807 * Verifies that specifying an invalid key size for AES key generation returns
808 * UNSUPPORTED_KEY_SIZE.
809 */
810TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
811 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
812 BlockMode block_mode = BlockMode::GCM;
813 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
814 SCOPED_TRACE(testing::Message()
815 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
816 vector<uint8_t> key_blob;
817 vector<KeyCharacteristics> key_characteristics;
818 // No MIN_MAC_LENGTH provided.
819 auto builder = AuthorizationSetBuilder()
820 .AesEncryptionKey(key_size)
821 .BlockMode(block_mode)
822 .Padding(padding_mode)
823 .SetDefaultValidity();
824 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
825 GenerateKey(builder, &key_blob, &key_characteristics));
826 }
827 }
828}
829
830/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100831 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
832 *
833 * Verifies that specifying an invalid min MAC size for AES key generation returns
834 * UNSUPPORTED_MIN_MAC_LENGTH.
835 */
836TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
837 for (size_t min_mac_len : {88, 136}) {
838 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
839 BlockMode block_mode = BlockMode::GCM;
840 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
841 SCOPED_TRACE(testing::Message()
842 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
843 vector<uint8_t> key_blob;
844 vector<KeyCharacteristics> key_characteristics;
845 auto builder = AuthorizationSetBuilder()
846 .AesEncryptionKey(key_size)
847 .BlockMode(block_mode)
848 .Padding(padding_mode)
849 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
850 .SetDefaultValidity();
851 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
852 GenerateKey(builder, &key_blob, &key_characteristics));
853 }
854 }
855 }
856}
857
858/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000859 * NewKeyGenerationTest.TripleDes
860 *
861 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
862 * have correct characteristics.
863 */
864TEST_P(NewKeyGenerationTest, TripleDes) {
865 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
866 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
867 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
868 SCOPED_TRACE(testing::Message()
869 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
870 vector<uint8_t> key_blob;
871 vector<KeyCharacteristics> key_characteristics;
872 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
873 .TripleDesEncryptionKey(key_size)
874 .BlockMode(block_mode)
875 .Padding(padding_mode)
876 .Authorization(TAG_NO_AUTH_REQUIRED)
877 .SetDefaultValidity(),
878 &key_blob, &key_characteristics));
879
880 EXPECT_GT(key_blob.size(), 0U);
881 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100882 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000883
884 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
885
886 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
887 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
888 << "Key size " << key_size << "missing";
889
890 CheckedDeleteKey(&key_blob);
891 }
892 }
893 }
894}
895
896/*
897 * NewKeyGenerationTest.TripleDesWithAttestation
898 *
899 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
900 * have correct characteristics.
901 *
902 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
903 * put in a certificate) but which isn't an error.
904 */
905TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
906 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
907 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
908 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
909 SCOPED_TRACE(testing::Message()
910 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
911
912 auto challenge = "hello";
913 auto app_id = "foo";
914
915 vector<uint8_t> key_blob;
916 vector<KeyCharacteristics> key_characteristics;
917 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
918 .TripleDesEncryptionKey(key_size)
919 .BlockMode(block_mode)
920 .Padding(padding_mode)
921 .Authorization(TAG_NO_AUTH_REQUIRED)
922 .AttestationChallenge(challenge)
923 .AttestationApplicationId(app_id)
924 .SetDefaultValidity(),
925 &key_blob, &key_characteristics));
926
927 EXPECT_GT(key_blob.size(), 0U);
928 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100929 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000930
931 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
932
933 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
934 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
935 << "Key size " << key_size << "missing";
936
937 CheckedDeleteKey(&key_blob);
938 }
939 }
940 }
941}
942
943/*
944 * NewKeyGenerationTest.TripleDesInvalidSize
945 *
946 * Verifies that specifying an invalid key size for 3-DES key generation returns
947 * UNSUPPORTED_KEY_SIZE.
948 */
949TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
950 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
951 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
952 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
953 SCOPED_TRACE(testing::Message()
954 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
955 vector<uint8_t> key_blob;
956 vector<KeyCharacteristics> key_characteristics;
957 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
958 GenerateKey(AuthorizationSetBuilder()
959 .TripleDesEncryptionKey(key_size)
960 .BlockMode(block_mode)
961 .Padding(padding_mode)
962 .Authorization(TAG_NO_AUTH_REQUIRED)
963 .SetDefaultValidity(),
964 &key_blob, &key_characteristics));
965 }
966 }
967 }
968
969 // Omitting the key size fails.
970 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
971 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
972 SCOPED_TRACE(testing::Message()
973 << "3DES-default-" << block_mode << "-" << padding_mode);
974 vector<uint8_t> key_blob;
975 vector<KeyCharacteristics> key_characteristics;
976 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
977 GenerateKey(AuthorizationSetBuilder()
978 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
979 .BlockMode(block_mode)
980 .Padding(padding_mode)
981 .Authorization(TAG_NO_AUTH_REQUIRED)
982 .SetDefaultValidity(),
983 &key_blob, &key_characteristics));
984 }
985 }
986}
987
988/*
Selene Huang31ab4042020-04-29 04:22:39 -0700989 * NewKeyGenerationTest.Rsa
990 *
991 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
992 * have correct characteristics.
993 */
994TEST_P(NewKeyGenerationTest, Rsa) {
995 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
996 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700997 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700998 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
999 .RsaSigningKey(key_size, 65537)
1000 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001001 .Padding(PaddingMode::NONE)
1002 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001003 &key_blob, &key_characteristics));
1004
1005 ASSERT_GT(key_blob.size(), 0U);
1006 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001007 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001008
Shawn Willden7f424372021-01-10 18:06:50 -07001009 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001010
1011 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1012 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1013 << "Key size " << key_size << "missing";
1014 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1015
1016 CheckedDeleteKey(&key_blob);
1017 }
1018}
1019
1020/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001021 * NewKeyGenerationTest.RsaWithMissingValidity
1022 *
1023 * Verifies that keymint returns an error while generating asymmetric key
1024 * without providing NOT_BEFORE and NOT_AFTER parameters.
1025 */
1026TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
1027 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1028 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1029 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1030
1031 vector<uint8_t> key_blob;
1032 vector<KeyCharacteristics> key_characteristics;
1033 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1034 GenerateKey(AuthorizationSetBuilder()
1035 .RsaSigningKey(2048, 65537)
1036 .Digest(Digest::NONE)
1037 .Padding(PaddingMode::NONE)
1038 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1039 kUndefinedExpirationDateTime),
1040 &key_blob, &key_characteristics));
1041
1042 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1043 GenerateKey(AuthorizationSetBuilder()
1044 .RsaSigningKey(2048, 65537)
1045 .Digest(Digest::NONE)
1046 .Padding(PaddingMode::NONE)
1047 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1048 &key_blob, &key_characteristics));
1049}
1050
1051/*
Qi Wud22ec842020-11-26 13:27:53 +08001052 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001053 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001054 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1055 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001056 */
1057TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001058 auto challenge = "hello";
1059 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001060
Selene Huang6e46f142021-04-20 19:20:11 -07001061 auto subject = "cert subj 2";
1062 vector<uint8_t> subject_der(make_name_from_str(subject));
1063
1064 uint64_t serial_int = 66;
1065 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1066
Selene Huang4f64c222021-04-13 19:54:36 -07001067 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001068 vector<uint8_t> key_blob;
1069 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001070 auto builder = AuthorizationSetBuilder()
1071 .RsaSigningKey(key_size, 65537)
1072 .Digest(Digest::NONE)
1073 .Padding(PaddingMode::NONE)
1074 .AttestationChallenge(challenge)
1075 .AttestationApplicationId(app_id)
1076 .Authorization(TAG_NO_AUTH_REQUIRED)
1077 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1078 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1079 .SetDefaultValidity();
1080
1081 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001082 // Strongbox may not support factory provisioned attestation key.
1083 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001084 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1085 result = GenerateKeyWithSelfSignedAttestKey(
1086 AuthorizationSetBuilder()
1087 .RsaKey(key_size, 65537)
1088 .AttestKey()
1089 .SetDefaultValidity(), /* attest key params */
1090 builder, &key_blob, &key_characteristics);
1091 }
subrahmanyaman05642492022-02-05 07:10:56 +00001092 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001093 ASSERT_EQ(ErrorCode::OK, result);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001094 ASSERT_GT(key_blob.size(), 0U);
1095 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001096 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001097
1098 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1099
1100 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1101 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1102 << "Key size " << key_size << "missing";
1103 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1104
Selene Huang6e46f142021-04-20 19:20:11 -07001105 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001106 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001107 ASSERT_GT(cert_chain_.size(), 0);
1108
1109 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1110 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001111 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001112 sw_enforced, hw_enforced, SecLevel(),
1113 cert_chain_[0].encodedCertificate));
1114
1115 CheckedDeleteKey(&key_blob);
1116 }
1117}
1118
1119/*
David Drysdale4dc01072021-04-01 12:17:35 +01001120 * NewKeyGenerationTest.RsaWithRpkAttestation
1121 *
1122 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
1123 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale0fce69d2021-04-13 17:22:13 +01001124 *
1125 * This test is disabled because the KeyMint specification does not require that implementations
1126 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
1127 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +01001128 */
David Drysdale0fce69d2021-04-13 17:22:13 +01001129TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +01001130 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
1131 // instance.
1132 std::shared_ptr<IRemotelyProvisionedComponent> rp;
1133 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
1134 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
1135
1136 // Generate a P-256 keypair to use as an attestation key.
1137 MacedPublicKey macedPubKey;
1138 std::vector<uint8_t> privateKeyBlob;
1139 auto status =
1140 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1141 ASSERT_TRUE(status.isOk());
1142 vector<uint8_t> coseKeyData;
1143 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1144
1145 AttestationKey attestation_key;
1146 attestation_key.keyBlob = std::move(privateKeyBlob);
1147 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1148
1149 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1150 auto challenge = "hello";
1151 auto app_id = "foo";
1152
1153 vector<uint8_t> key_blob;
1154 vector<KeyCharacteristics> key_characteristics;
1155 ASSERT_EQ(ErrorCode::OK,
1156 GenerateKey(AuthorizationSetBuilder()
1157 .RsaSigningKey(key_size, 65537)
1158 .Digest(Digest::NONE)
1159 .Padding(PaddingMode::NONE)
1160 .AttestationChallenge(challenge)
1161 .AttestationApplicationId(app_id)
1162 .Authorization(TAG_NO_AUTH_REQUIRED)
1163 .SetDefaultValidity(),
1164 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1165
1166 ASSERT_GT(key_blob.size(), 0U);
1167 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001168 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001169
1170 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1171
1172 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1173 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1174 << "Key size " << key_size << "missing";
1175 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1176
1177 // Attestation by itself is not valid (last entry is not self-signed).
1178 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1179
1180 // The signature over the attested key should correspond to the P256 public key.
1181 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1182 ASSERT_TRUE(key_cert.get());
1183 EVP_PKEY_Ptr signing_pubkey;
1184 p256_pub_key(coseKeyData, &signing_pubkey);
1185 ASSERT_TRUE(signing_pubkey.get());
1186
1187 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1188 << "Verification of attested certificate failed "
1189 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1190
1191 CheckedDeleteKey(&key_blob);
1192 }
1193}
1194
1195/*
Selene Huang4f64c222021-04-13 19:54:36 -07001196 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1197 *
1198 * Verifies that keymint attestation for RSA encryption keys with challenge and
1199 * app id is also successful.
1200 */
1201TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1202 auto key_size = 2048;
1203 auto challenge = "hello";
1204 auto app_id = "foo";
1205
Selene Huang6e46f142021-04-20 19:20:11 -07001206 auto subject = "subj 2";
1207 vector<uint8_t> subject_der(make_name_from_str(subject));
1208
1209 uint64_t serial_int = 111166;
1210 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1211
Selene Huang4f64c222021-04-13 19:54:36 -07001212 vector<uint8_t> key_blob;
1213 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001214 auto builder = AuthorizationSetBuilder()
1215 .RsaEncryptionKey(key_size, 65537)
1216 .Padding(PaddingMode::NONE)
1217 .AttestationChallenge(challenge)
1218 .AttestationApplicationId(app_id)
1219 .Authorization(TAG_NO_AUTH_REQUIRED)
1220 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1221 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1222 .SetDefaultValidity();
1223
1224 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001225 // Strongbox may not support factory provisioned attestation key.
1226 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001227 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1228 result = GenerateKeyWithSelfSignedAttestKey(
1229 AuthorizationSetBuilder()
1230 .RsaKey(key_size, 65537)
1231 .AttestKey()
1232 .SetDefaultValidity(), /* attest key params */
1233 builder, &key_blob, &key_characteristics);
1234 }
subrahmanyaman05642492022-02-05 07:10:56 +00001235 }
1236 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001237
1238 ASSERT_GT(key_blob.size(), 0U);
1239 AuthorizationSet auths;
1240 for (auto& entry : key_characteristics) {
1241 auths.push_back(AuthorizationSet(entry.authorizations));
1242 }
1243
1244 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1245 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1246
1247 // Verify that App data and ROT are NOT included.
1248 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1249 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1250
1251 // Check that some unexpected tags/values are NOT present.
1252 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1253 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1254
1255 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1256
1257 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1258 ASSERT_TRUE(os_ver);
1259 EXPECT_EQ(*os_ver, os_version());
1260
1261 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1262
1263 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1264 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1265 << "Key size " << key_size << "missing";
1266 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1267
Selene Huang6e46f142021-04-20 19:20:11 -07001268 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001269 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1270 ASSERT_GT(cert_chain_.size(), 0);
1271
1272 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1273 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001274 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001275 sw_enforced, hw_enforced, SecLevel(),
1276 cert_chain_[0].encodedCertificate));
1277
1278 CheckedDeleteKey(&key_blob);
1279}
1280
1281/*
1282 * NewKeyGenerationTest.RsaWithSelfSign
1283 *
1284 * Verifies that attesting to RSA key generation is successful, and returns
1285 * self signed certificate if no challenge is provided. And signing etc
1286 * works as expected.
1287 */
1288TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001289 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1290 vector<uint8_t> subject_der(make_name_from_str(subject));
1291
1292 uint64_t serial_int = 0;
1293 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1294
Selene Huang4f64c222021-04-13 19:54:36 -07001295 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1296 vector<uint8_t> key_blob;
1297 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001298 ASSERT_EQ(ErrorCode::OK,
1299 GenerateKey(AuthorizationSetBuilder()
1300 .RsaSigningKey(key_size, 65537)
1301 .Digest(Digest::NONE)
1302 .Padding(PaddingMode::NONE)
1303 .Authorization(TAG_NO_AUTH_REQUIRED)
1304 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1305 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1306 .SetDefaultValidity(),
1307 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001308
1309 ASSERT_GT(key_blob.size(), 0U);
1310 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001311 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001312
1313 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1314
1315 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1316 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1317 << "Key size " << key_size << "missing";
1318 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1319
Selene Huang6e46f142021-04-20 19:20:11 -07001320 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001321 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1322 ASSERT_EQ(cert_chain_.size(), 1);
1323
1324 CheckedDeleteKey(&key_blob);
1325 }
1326}
1327
1328/*
1329 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1330 *
1331 * Verifies that attesting to RSA checks for missing app ID.
1332 */
1333TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1334 auto challenge = "hello";
1335 vector<uint8_t> key_blob;
1336 vector<KeyCharacteristics> key_characteristics;
1337
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001338 auto builder = AuthorizationSetBuilder()
1339 .RsaSigningKey(2048, 65537)
1340 .Digest(Digest::NONE)
1341 .Padding(PaddingMode::NONE)
1342 .AttestationChallenge(challenge)
1343 .Authorization(TAG_NO_AUTH_REQUIRED)
1344 .SetDefaultValidity();
1345
1346 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001347 // Strongbox may not support factory provisioned attestation key.
1348 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001349 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1350 result = GenerateKeyWithSelfSignedAttestKey(
1351 AuthorizationSetBuilder()
1352 .RsaKey(2048, 65537)
1353 .AttestKey()
1354 .SetDefaultValidity(), /* attest key params */
1355 builder, &key_blob, &key_characteristics);
1356 }
subrahmanyaman05642492022-02-05 07:10:56 +00001357 }
1358 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001359}
1360
1361/*
1362 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1363 *
1364 * Verifies that attesting to RSA ignores app id if challenge is missing.
1365 */
1366TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1367 auto key_size = 2048;
1368 auto app_id = "foo";
1369
Selene Huang6e46f142021-04-20 19:20:11 -07001370 auto subject = "cert subj 2";
1371 vector<uint8_t> subject_der(make_name_from_str(subject));
1372
1373 uint64_t serial_int = 1;
1374 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1375
Selene Huang4f64c222021-04-13 19:54:36 -07001376 vector<uint8_t> key_blob;
1377 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001378 ASSERT_EQ(ErrorCode::OK,
1379 GenerateKey(AuthorizationSetBuilder()
1380 .RsaSigningKey(key_size, 65537)
1381 .Digest(Digest::NONE)
1382 .Padding(PaddingMode::NONE)
1383 .AttestationApplicationId(app_id)
1384 .Authorization(TAG_NO_AUTH_REQUIRED)
1385 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1386 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1387 .SetDefaultValidity(),
1388 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001389
1390 ASSERT_GT(key_blob.size(), 0U);
1391 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001392 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001393
1394 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1395
1396 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1397 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1398 << "Key size " << key_size << "missing";
1399 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1400
Selene Huang6e46f142021-04-20 19:20:11 -07001401 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001402 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1403 ASSERT_EQ(cert_chain_.size(), 1);
1404
1405 CheckedDeleteKey(&key_blob);
1406}
1407
1408/*
Qi Wud22ec842020-11-26 13:27:53 +08001409 * NewKeyGenerationTest.LimitedUsageRsa
1410 *
1411 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1412 * resulting keys have correct characteristics.
1413 */
1414TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1415 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1416 vector<uint8_t> key_blob;
1417 vector<KeyCharacteristics> key_characteristics;
1418 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1419 .RsaSigningKey(key_size, 65537)
1420 .Digest(Digest::NONE)
1421 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001422 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1423 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001424 &key_blob, &key_characteristics));
1425
1426 ASSERT_GT(key_blob.size(), 0U);
1427 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001428 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001429
1430 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1431
1432 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1433 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1434 << "Key size " << key_size << "missing";
1435 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1436
1437 // Check the usage count limit tag appears in the authorizations.
1438 AuthorizationSet auths;
1439 for (auto& entry : key_characteristics) {
1440 auths.push_back(AuthorizationSet(entry.authorizations));
1441 }
1442 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1443 << "key usage count limit " << 1U << " missing";
1444
1445 CheckedDeleteKey(&key_blob);
1446 }
1447}
1448
1449/*
Qi Wubeefae42021-01-28 23:16:37 +08001450 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1451 *
1452 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1453 * resulting keys have correct characteristics and attestation.
1454 */
1455TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001456 auto challenge = "hello";
1457 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001458
Selene Huang6e46f142021-04-20 19:20:11 -07001459 auto subject = "cert subj 2";
1460 vector<uint8_t> subject_der(make_name_from_str(subject));
1461
1462 uint64_t serial_int = 66;
1463 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1464
Selene Huang4f64c222021-04-13 19:54:36 -07001465 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001466 vector<uint8_t> key_blob;
1467 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001468 auto builder = AuthorizationSetBuilder()
1469 .RsaSigningKey(key_size, 65537)
1470 .Digest(Digest::NONE)
1471 .Padding(PaddingMode::NONE)
1472 .AttestationChallenge(challenge)
1473 .AttestationApplicationId(app_id)
1474 .Authorization(TAG_NO_AUTH_REQUIRED)
1475 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1476 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1477 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1478 .SetDefaultValidity();
1479
1480 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001481 // Strongbox may not support factory provisioned attestation key.
1482 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001483 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1484 result = GenerateKeyWithSelfSignedAttestKey(
1485 AuthorizationSetBuilder()
1486 .RsaKey(key_size, 65537)
1487 .AttestKey()
1488 .SetDefaultValidity(), /* attest key params */
1489 builder, &key_blob, &key_characteristics);
1490 }
subrahmanyaman05642492022-02-05 07:10:56 +00001491 }
1492 ASSERT_EQ(ErrorCode::OK, result);
Qi Wubeefae42021-01-28 23:16:37 +08001493
1494 ASSERT_GT(key_blob.size(), 0U);
1495 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001496 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001497
1498 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1499
1500 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1501 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1502 << "Key size " << key_size << "missing";
1503 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1504
1505 // Check the usage count limit tag appears in the authorizations.
1506 AuthorizationSet auths;
1507 for (auto& entry : key_characteristics) {
1508 auths.push_back(AuthorizationSet(entry.authorizations));
1509 }
1510 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1511 << "key usage count limit " << 1U << " missing";
1512
1513 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001514 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001515 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001516 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001517
1518 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1519 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001520 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001521 sw_enforced, hw_enforced, SecLevel(),
1522 cert_chain_[0].encodedCertificate));
1523
1524 CheckedDeleteKey(&key_blob);
1525 }
1526}
1527
1528/*
Selene Huang31ab4042020-04-29 04:22:39 -07001529 * NewKeyGenerationTest.NoInvalidRsaSizes
1530 *
1531 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1532 */
1533TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1534 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1535 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001536 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001537 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1538 GenerateKey(AuthorizationSetBuilder()
1539 .RsaSigningKey(key_size, 65537)
1540 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001541 .Padding(PaddingMode::NONE)
1542 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001543 &key_blob, &key_characteristics));
1544 }
1545}
1546
1547/*
1548 * NewKeyGenerationTest.RsaNoDefaultSize
1549 *
1550 * Verifies that failing to specify a key size for RSA key generation returns
1551 * UNSUPPORTED_KEY_SIZE.
1552 */
1553TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1554 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1555 GenerateKey(AuthorizationSetBuilder()
1556 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1557 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001558 .SigningKey()
1559 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001560}
1561
1562/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001563 * NewKeyGenerationTest.RsaMissingParams
1564 *
1565 * Verifies that omitting optional tags works.
1566 */
1567TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1568 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1569 ASSERT_EQ(ErrorCode::OK,
1570 GenerateKey(
1571 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1572 CheckedDeleteKey();
1573 }
1574}
1575
1576/*
Selene Huang31ab4042020-04-29 04:22:39 -07001577 * NewKeyGenerationTest.Ecdsa
1578 *
David Drysdale42fe1892021-10-14 14:43:46 +01001579 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001580 * have correct characteristics.
1581 */
1582TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001583 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001584 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001585 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001586 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001587 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001588 .Digest(Digest::NONE)
1589 .SetDefaultValidity(),
1590 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001591 ASSERT_GT(key_blob.size(), 0U);
1592 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001593 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001594
Shawn Willden7f424372021-01-10 18:06:50 -07001595 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001596
1597 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001598 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001599
1600 CheckedDeleteKey(&key_blob);
1601 }
1602}
1603
1604/*
David Drysdale42fe1892021-10-14 14:43:46 +01001605 * NewKeyGenerationTest.EcdsaCurve25519
1606 *
1607 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1608 * has correct characteristics.
1609 */
1610TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1611 if (!Curve25519Supported()) {
1612 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1613 }
1614
1615 EcCurve curve = EcCurve::CURVE_25519;
1616 vector<uint8_t> key_blob;
1617 vector<KeyCharacteristics> key_characteristics;
1618 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1619 .EcdsaSigningKey(curve)
1620 .Digest(Digest::NONE)
1621 .SetDefaultValidity(),
1622 &key_blob, &key_characteristics);
1623 ASSERT_EQ(result, ErrorCode::OK);
1624 ASSERT_GT(key_blob.size(), 0U);
1625
1626 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1627 ASSERT_GT(cert_chain_.size(), 0);
1628
1629 CheckBaseParams(key_characteristics);
1630 CheckCharacteristics(key_blob, key_characteristics);
1631
1632 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1633
1634 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1635 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1636
1637 CheckedDeleteKey(&key_blob);
1638}
1639
1640/*
1641 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1642 *
1643 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1644 * SIGN and AGREE_KEY.
1645 */
1646TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1647 if (!Curve25519Supported()) {
1648 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1649 }
1650
1651 EcCurve curve = EcCurve::CURVE_25519;
1652 vector<uint8_t> key_blob;
1653 vector<KeyCharacteristics> key_characteristics;
1654 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1655 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1656 .EcdsaSigningKey(curve)
1657 .Digest(Digest::NONE)
1658 .SetDefaultValidity(),
1659 &key_blob, &key_characteristics);
1660 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1661}
1662
1663/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001664 * NewKeyGenerationTest.EcdsaWithMissingValidity
1665 *
1666 * Verifies that keymint returns an error while generating asymmetric key
1667 * without providing NOT_BEFORE and NOT_AFTER parameters.
1668 */
1669TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
1670 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1671 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1672 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1673
1674 vector<uint8_t> key_blob;
1675 vector<KeyCharacteristics> key_characteristics;
1676 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1677 GenerateKey(AuthorizationSetBuilder()
1678 .EcdsaSigningKey(EcCurve::P_256)
1679 .Digest(Digest::NONE)
1680 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1681 kUndefinedExpirationDateTime),
1682 &key_blob, &key_characteristics));
1683
1684 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1685 GenerateKey(AuthorizationSetBuilder()
1686 .EcdsaSigningKey(EcCurve::P_256)
1687 .Digest(Digest::NONE)
1688 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1689 &key_blob, &key_characteristics));
1690}
1691
1692/*
Selene Huang4f64c222021-04-13 19:54:36 -07001693 * NewKeyGenerationTest.EcdsaAttestation
1694 *
1695 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1696 * an attestation will be generated.
1697 */
1698TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1699 auto challenge = "hello";
1700 auto app_id = "foo";
1701
Selene Huang6e46f142021-04-20 19:20:11 -07001702 auto subject = "cert subj 2";
1703 vector<uint8_t> subject_der(make_name_from_str(subject));
1704
1705 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1706 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1707
David Drysdaledf09e542021-06-08 15:46:11 +01001708 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001709 vector<uint8_t> key_blob;
1710 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001711 auto builder = AuthorizationSetBuilder()
1712 .Authorization(TAG_NO_AUTH_REQUIRED)
1713 .EcdsaSigningKey(curve)
1714 .Digest(Digest::NONE)
1715 .AttestationChallenge(challenge)
1716 .AttestationApplicationId(app_id)
1717 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1718 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1719 .SetDefaultValidity();
1720
1721 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001722 // Strongbox may not support factory provisioned attestation key.
1723 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001724 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1725 result = GenerateKeyWithSelfSignedAttestKey(
1726 AuthorizationSetBuilder()
1727 .EcdsaKey(curve)
1728 .AttestKey()
1729 .SetDefaultValidity(), /* attest key params */
1730 builder, &key_blob, &key_characteristics);
1731 }
subrahmanyaman05642492022-02-05 07:10:56 +00001732 }
1733 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001734 ASSERT_GT(key_blob.size(), 0U);
1735 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001736 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001737
1738 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1739
1740 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001741 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001742
1743 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1744 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001745 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001746
1747 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1748 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001749 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001750 sw_enforced, hw_enforced, SecLevel(),
1751 cert_chain_[0].encodedCertificate));
1752
1753 CheckedDeleteKey(&key_blob);
1754 }
1755}
1756
1757/*
David Drysdale42fe1892021-10-14 14:43:46 +01001758 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1759 *
1760 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1761 * an attestation will be generated.
1762 */
1763TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1764 if (!Curve25519Supported()) {
1765 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1766 }
1767
1768 EcCurve curve = EcCurve::CURVE_25519;
1769 auto challenge = "hello";
1770 auto app_id = "foo";
1771
1772 auto subject = "cert subj 2";
1773 vector<uint8_t> subject_der(make_name_from_str(subject));
1774
1775 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1776 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1777
1778 vector<uint8_t> key_blob;
1779 vector<KeyCharacteristics> key_characteristics;
1780 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1781 .Authorization(TAG_NO_AUTH_REQUIRED)
1782 .EcdsaSigningKey(curve)
1783 .Digest(Digest::NONE)
1784 .AttestationChallenge(challenge)
1785 .AttestationApplicationId(app_id)
1786 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1787 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1788 .SetDefaultValidity(),
1789 &key_blob, &key_characteristics);
1790 ASSERT_EQ(ErrorCode::OK, result);
1791 ASSERT_GT(key_blob.size(), 0U);
1792 CheckBaseParams(key_characteristics);
1793 CheckCharacteristics(key_blob, key_characteristics);
1794
1795 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1796
1797 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1798 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1799
1800 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1801 ASSERT_GT(cert_chain_.size(), 0);
1802 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1803
1804 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1805 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1806 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1807 sw_enforced, hw_enforced, SecLevel(),
1808 cert_chain_[0].encodedCertificate));
1809
1810 CheckedDeleteKey(&key_blob);
1811}
1812
1813/*
David Drysdale37af4b32021-05-14 16:46:59 +01001814 * NewKeyGenerationTest.EcdsaAttestationTags
1815 *
1816 * Verifies that creation of an attested ECDSA key includes various tags in the
1817 * attestation extension.
1818 */
1819TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1820 auto challenge = "hello";
1821 auto app_id = "foo";
1822 auto subject = "cert subj 2";
1823 vector<uint8_t> subject_der(make_name_from_str(subject));
1824 uint64_t serial_int = 0x1010;
1825 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1826 const AuthorizationSetBuilder base_builder =
1827 AuthorizationSetBuilder()
1828 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001829 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001830 .Digest(Digest::NONE)
1831 .AttestationChallenge(challenge)
1832 .AttestationApplicationId(app_id)
1833 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1834 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1835 .SetDefaultValidity();
1836
1837 // Various tags that map to fields in the attestation extension ASN.1 schema.
1838 auto extra_tags = AuthorizationSetBuilder()
1839 .Authorization(TAG_ROLLBACK_RESISTANCE)
1840 .Authorization(TAG_EARLY_BOOT_ONLY)
1841 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1842 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1843 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1844 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1845 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1846 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1847 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1848 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1849 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1850 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001851
David Drysdale37af4b32021-05-14 16:46:59 +01001852 for (const KeyParameter& tag : extra_tags) {
1853 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1854 vector<uint8_t> key_blob;
1855 vector<KeyCharacteristics> key_characteristics;
1856 AuthorizationSetBuilder builder = base_builder;
1857 builder.push_back(tag);
1858 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1859 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1860 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1861 continue;
1862 }
Seth Mooreb393b082021-07-12 14:18:28 -07001863 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1864 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001865 continue;
1866 }
subrahmanyaman05642492022-02-05 07:10:56 +00001867 // Strongbox may not support factory provisioned attestation key.
1868 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001869 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1870 result = GenerateKeyWithSelfSignedAttestKey(
1871 AuthorizationSetBuilder()
1872 .EcdsaKey(EcCurve::P_256)
1873 .AttestKey()
1874 .SetDefaultValidity(), /* attest key params */
1875 builder, &key_blob, &key_characteristics);
1876 }
subrahmanyaman05642492022-02-05 07:10:56 +00001877 }
David Drysdale37af4b32021-05-14 16:46:59 +01001878 ASSERT_EQ(result, ErrorCode::OK);
1879 ASSERT_GT(key_blob.size(), 0U);
1880
1881 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1882 ASSERT_GT(cert_chain_.size(), 0);
1883 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1884
1885 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1886 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001887 // Some tags are optional, so don't require them to be in the enforcements.
1888 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001889 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1890 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1891 }
1892
1893 // Verifying the attestation record will check for the specific tag because
1894 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001895 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1896 hw_enforced, SecLevel(),
1897 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01001898
1899 CheckedDeleteKey(&key_blob);
1900 }
1901
David Drysdalec53b7d92021-10-11 12:35:58 +01001902 // Collection of invalid attestation ID tags.
1903 auto invalid_tags =
1904 AuthorizationSetBuilder()
1905 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1906 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1907 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1908 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1909 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
1910 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
1911 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
1912 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01001913 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01001914 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01001915 vector<uint8_t> key_blob;
1916 vector<KeyCharacteristics> key_characteristics;
1917 AuthorizationSetBuilder builder =
1918 AuthorizationSetBuilder()
1919 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001920 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001921 .Digest(Digest::NONE)
1922 .AttestationChallenge(challenge)
1923 .AttestationApplicationId(app_id)
1924 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1925 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1926 .SetDefaultValidity();
1927 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001928
1929 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
1930 // Strongbox may not support factory provisioned attestation key.
1931 if (SecLevel() == SecurityLevel::STRONGBOX) {
1932 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1933 error = GenerateKeyWithSelfSignedAttestKey(
1934 AuthorizationSetBuilder()
1935 .EcdsaKey(EcCurve::P_256)
1936 .AttestKey()
1937 .SetDefaultValidity(), /* attest key params */
1938 builder, &key_blob, &key_characteristics);
1939 }
1940 }
1941 ASSERT_EQ(error, ErrorCode::CANNOT_ATTEST_IDS);
David Drysdale37af4b32021-05-14 16:46:59 +01001942 }
1943}
1944
1945/*
David Drysdalec53b7d92021-10-11 12:35:58 +01001946 * NewKeyGenerationTest.EcdsaAttestationIdTags
1947 *
1948 * Verifies that creation of an attested ECDSA key includes various ID tags in the
1949 * attestation extension.
1950 */
1951TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
David Drysdale555ba002022-05-03 18:48:57 +01001952 if (is_gsi_image()) {
1953 // GSI sets up a standard set of device identifiers that may not match
1954 // the device identifiers held by the device.
1955 GTEST_SKIP() << "Test not applicable under GSI";
1956 }
David Drysdalec53b7d92021-10-11 12:35:58 +01001957 auto challenge = "hello";
1958 auto app_id = "foo";
1959 auto subject = "cert subj 2";
1960 vector<uint8_t> subject_der(make_name_from_str(subject));
1961 uint64_t serial_int = 0x1010;
1962 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1963 const AuthorizationSetBuilder base_builder =
1964 AuthorizationSetBuilder()
1965 .Authorization(TAG_NO_AUTH_REQUIRED)
1966 .EcdsaSigningKey(EcCurve::P_256)
1967 .Digest(Digest::NONE)
1968 .AttestationChallenge(challenge)
1969 .AttestationApplicationId(app_id)
1970 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1971 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1972 .SetDefaultValidity();
1973
1974 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
1975 auto extra_tags = AuthorizationSetBuilder();
1976 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
1977 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
1978 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
1979 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
1980 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
1981 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
1982
1983 for (const KeyParameter& tag : extra_tags) {
1984 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1985 vector<uint8_t> key_blob;
1986 vector<KeyCharacteristics> key_characteristics;
1987 AuthorizationSetBuilder builder = base_builder;
1988 builder.push_back(tag);
1989 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001990 // Strongbox may not support factory provisioned attestation key.
1991 if (SecLevel() == SecurityLevel::STRONGBOX) {
1992 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1993 }
Prashant Patil88ad1892022-03-15 16:31:02 +00001994 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
1995 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01001996 continue;
1997 }
1998 ASSERT_EQ(result, ErrorCode::OK);
1999 ASSERT_GT(key_blob.size(), 0U);
2000
2001 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2002 ASSERT_GT(cert_chain_.size(), 0);
2003 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2004
2005 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2006 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2007
2008 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2009 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2010 // attestation extension should contain them, so make sure the extra tag is added.
2011 hw_enforced.push_back(tag);
2012
2013 // Verifying the attestation record will check for the specific tag because
2014 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002015 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2016 hw_enforced, SecLevel(),
2017 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002018
2019 CheckedDeleteKey(&key_blob);
2020 }
2021}
2022
2023/*
David Drysdale565ccc72021-10-11 12:49:50 +01002024 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2025 *
2026 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2027 */
2028TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2029 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002030 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002031 auto challenge = "hello";
2032 auto subject = "cert subj 2";
2033 vector<uint8_t> subject_der(make_name_from_str(subject));
2034 uint64_t serial_int = 0x1010;
2035 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002036 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002037 AuthorizationSetBuilder()
2038 .Authorization(TAG_NO_AUTH_REQUIRED)
2039 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2040 .EcdsaSigningKey(EcCurve::P_256)
2041 .Digest(Digest::NONE)
2042 .AttestationChallenge(challenge)
2043 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2044 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2045 .AttestationApplicationId(app_id)
2046 .Authorization(TAG_CREATION_DATETIME, datetime)
2047 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002048 if (reset) {
2049 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2050 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002051 auto result = GenerateKey(builder);
2052 if (SecLevel() == SecurityLevel::STRONGBOX) {
2053 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2054 result = GenerateKeyWithSelfSignedAttestKey(
2055 AuthorizationSetBuilder()
2056 .EcdsaKey(EcCurve::P_256)
2057 .AttestKey()
2058 .SetDefaultValidity(), /* attest key params */
2059 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2060 }
2061 }
2062 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002063 ASSERT_GT(key_blob_.size(), 0U);
2064
2065 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2066 ASSERT_GT(cert_chain_.size(), 0);
2067 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2068
2069 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2070 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2071
2072 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002073 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2074 hw_enforced, SecLevel(),
2075 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002076 EXPECT_GT(unique_id->size(), 0);
2077 CheckedDeleteKey();
2078 };
2079
2080 // Generate unique ID
2081 auto app_id = "foo";
2082 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2083 vector<uint8_t> unique_id;
2084 get_unique_id(app_id, cert_date, &unique_id);
2085
2086 // Generating a new key with the same parameters should give the same unique ID.
2087 vector<uint8_t> unique_id2;
2088 get_unique_id(app_id, cert_date, &unique_id2);
2089 EXPECT_EQ(unique_id, unique_id2);
2090
2091 // Generating a new key with a slightly different date should give the same unique ID.
2092 uint64_t rounded_date = cert_date / 2592000000LLU;
2093 uint64_t min_date = rounded_date * 2592000000LLU;
2094 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2095
2096 vector<uint8_t> unique_id3;
2097 get_unique_id(app_id, min_date, &unique_id3);
2098 EXPECT_EQ(unique_id, unique_id3);
2099
2100 vector<uint8_t> unique_id4;
2101 get_unique_id(app_id, max_date, &unique_id4);
2102 EXPECT_EQ(unique_id, unique_id4);
2103
2104 // A different attestation application ID should yield a different unique ID.
2105 auto app_id2 = "different_foo";
2106 vector<uint8_t> unique_id5;
2107 get_unique_id(app_id2, cert_date, &unique_id5);
2108 EXPECT_NE(unique_id, unique_id5);
2109
2110 // A radically different date should yield a different unique ID.
2111 vector<uint8_t> unique_id6;
2112 get_unique_id(app_id, 1611621648000, &unique_id6);
2113 EXPECT_NE(unique_id, unique_id6);
2114
2115 vector<uint8_t> unique_id7;
2116 get_unique_id(app_id, max_date + 1, &unique_id7);
2117 EXPECT_NE(unique_id, unique_id7);
2118
2119 vector<uint8_t> unique_id8;
2120 get_unique_id(app_id, min_date - 1, &unique_id8);
2121 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002122
2123 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2124 vector<uint8_t> unique_id9;
2125 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2126 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002127}
2128
2129/*
David Drysdale37af4b32021-05-14 16:46:59 +01002130 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2131 *
2132 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2133 */
2134TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2135 auto challenge = "hello";
2136 auto attest_app_id = "foo";
2137 auto subject = "cert subj 2";
2138 vector<uint8_t> subject_der(make_name_from_str(subject));
2139 uint64_t serial_int = 0x1010;
2140 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2141
2142 // Earlier versions of the attestation extension schema included a slot:
2143 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2144 // This should never have been included, and should never be filled in.
2145 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2146 // to confirm that this field never makes it into the attestation extension.
2147 vector<uint8_t> key_blob;
2148 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002149 auto builder = AuthorizationSetBuilder()
2150 .Authorization(TAG_NO_AUTH_REQUIRED)
2151 .EcdsaSigningKey(EcCurve::P_256)
2152 .Digest(Digest::NONE)
2153 .AttestationChallenge(challenge)
2154 .AttestationApplicationId(attest_app_id)
2155 .Authorization(TAG_APPLICATION_ID, "client_id")
2156 .Authorization(TAG_APPLICATION_DATA, "appdata")
2157 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2158 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2159 .SetDefaultValidity();
2160
2161 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002162 // Strongbox may not support factory provisioned attestation key.
2163 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002164 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2165 result = GenerateKeyWithSelfSignedAttestKey(
2166 AuthorizationSetBuilder()
2167 .EcdsaKey(EcCurve::P_256)
2168 .AttestKey()
2169 .SetDefaultValidity(), /* attest key params */
2170 builder, &key_blob, &key_characteristics);
2171 }
subrahmanyaman05642492022-02-05 07:10:56 +00002172 }
David Drysdale37af4b32021-05-14 16:46:59 +01002173 ASSERT_EQ(result, ErrorCode::OK);
2174 ASSERT_GT(key_blob.size(), 0U);
2175
2176 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2177 ASSERT_GT(cert_chain_.size(), 0);
2178 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2179
2180 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2181 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002182 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2183 hw_enforced, SecLevel(),
2184 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002185
2186 // Check that the app id is not in the cert.
2187 string app_id = "clientid";
2188 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2189 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2190 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2191 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2192 cert_chain_[0].encodedCertificate.end());
2193
2194 CheckedDeleteKey(&key_blob);
2195}
2196
2197/*
Selene Huang4f64c222021-04-13 19:54:36 -07002198 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2199 *
2200 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2201 * the key will generate a self signed attestation.
2202 */
2203TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002204 auto subject = "cert subj 2";
2205 vector<uint8_t> subject_der(make_name_from_str(subject));
2206
2207 uint64_t serial_int = 0x123456FFF1234;
2208 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2209
David Drysdaledf09e542021-06-08 15:46:11 +01002210 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002211 vector<uint8_t> key_blob;
2212 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002213 ASSERT_EQ(ErrorCode::OK,
2214 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002215 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002216 .Digest(Digest::NONE)
2217 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2218 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2219 .SetDefaultValidity(),
2220 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002221 ASSERT_GT(key_blob.size(), 0U);
2222 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002223 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002224
2225 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2226
2227 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002228 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002229
2230 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07002231 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002232 ASSERT_EQ(cert_chain_.size(), 1);
2233
2234 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2235 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2236
2237 CheckedDeleteKey(&key_blob);
2238 }
2239}
2240
2241/*
2242 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2243 *
2244 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2245 * app id must also be provided or else it will fail.
2246 */
2247TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2248 auto challenge = "hello";
2249 vector<uint8_t> key_blob;
2250 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002251 auto builder = AuthorizationSetBuilder()
2252 .EcdsaSigningKey(EcCurve::P_256)
2253 .Digest(Digest::NONE)
2254 .AttestationChallenge(challenge)
2255 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002256
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002257 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002258 // Strongbox may not support factory provisioned attestation key.
2259 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002260 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2261 result = GenerateKeyWithSelfSignedAttestKey(
2262 AuthorizationSetBuilder()
2263 .EcdsaKey(EcCurve::P_256)
2264 .AttestKey()
2265 .SetDefaultValidity(), /* attest key params */
2266 builder, &key_blob, &key_characteristics);
2267 }
subrahmanyaman05642492022-02-05 07:10:56 +00002268 }
2269 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002270}
2271
2272/*
2273 * NewKeyGenerationTest.EcdsaIgnoreAppId
2274 *
2275 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2276 * any appid will be ignored, and keymint will generate a self sign certificate.
2277 */
2278TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2279 auto app_id = "foo";
2280
David Drysdaledf09e542021-06-08 15:46:11 +01002281 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002282 vector<uint8_t> key_blob;
2283 vector<KeyCharacteristics> key_characteristics;
2284 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002285 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002286 .Digest(Digest::NONE)
2287 .AttestationApplicationId(app_id)
2288 .SetDefaultValidity(),
2289 &key_blob, &key_characteristics));
2290
2291 ASSERT_GT(key_blob.size(), 0U);
2292 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002293 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002294
2295 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2296
2297 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002298 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002299
2300 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2301 ASSERT_EQ(cert_chain_.size(), 1);
2302
2303 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2304 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2305
2306 CheckedDeleteKey(&key_blob);
2307 }
2308}
2309
2310/*
2311 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2312 *
2313 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2314 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2315 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2316 * to specify how many following bytes will be used to encode the length.
2317 */
2318TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2319 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002320 std::vector<uint32_t> app_id_lengths{143, 258};
2321
2322 for (uint32_t length : app_id_lengths) {
2323 const string app_id(length, 'a');
2324 vector<uint8_t> key_blob;
2325 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002326 auto builder = AuthorizationSetBuilder()
2327 .Authorization(TAG_NO_AUTH_REQUIRED)
2328 .EcdsaSigningKey(EcCurve::P_256)
2329 .Digest(Digest::NONE)
2330 .AttestationChallenge(challenge)
2331 .AttestationApplicationId(app_id)
2332 .SetDefaultValidity();
2333
2334 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002335 // Strongbox may not support factory provisioned attestation key.
2336 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002337 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2338 result = GenerateKeyWithSelfSignedAttestKey(
2339 AuthorizationSetBuilder()
2340 .EcdsaKey(EcCurve::P_256)
2341 .AttestKey()
2342 .SetDefaultValidity(), /* attest key params */
2343 builder, &key_blob, &key_characteristics);
2344 }
subrahmanyaman05642492022-02-05 07:10:56 +00002345 }
2346 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002347 ASSERT_GT(key_blob.size(), 0U);
2348 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002349 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002350
2351 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2352
2353 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002354 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002355
2356 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2357 ASSERT_GT(cert_chain_.size(), 0);
2358
2359 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2360 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002361 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002362 sw_enforced, hw_enforced, SecLevel(),
2363 cert_chain_[0].encodedCertificate));
2364
2365 CheckedDeleteKey(&key_blob);
2366 }
2367}
2368
2369/*
Qi Wud22ec842020-11-26 13:27:53 +08002370 * NewKeyGenerationTest.LimitedUsageEcdsa
2371 *
2372 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2373 * resulting keys have correct characteristics.
2374 */
2375TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002376 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08002377 vector<uint8_t> key_blob;
2378 vector<KeyCharacteristics> key_characteristics;
2379 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002380 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002381 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002382 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2383 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002384 &key_blob, &key_characteristics));
2385
2386 ASSERT_GT(key_blob.size(), 0U);
2387 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002388 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002389
2390 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2391
2392 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002393 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002394
2395 // Check the usage count limit tag appears in the authorizations.
2396 AuthorizationSet auths;
2397 for (auto& entry : key_characteristics) {
2398 auths.push_back(AuthorizationSet(entry.authorizations));
2399 }
2400 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2401 << "key usage count limit " << 1U << " missing";
2402
2403 CheckedDeleteKey(&key_blob);
2404 }
2405}
2406
2407/*
Selene Huang31ab4042020-04-29 04:22:39 -07002408 * NewKeyGenerationTest.EcdsaDefaultSize
2409 *
David Drysdaledf09e542021-06-08 15:46:11 +01002410 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002411 * UNSUPPORTED_KEY_SIZE.
2412 */
2413TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2414 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2415 GenerateKey(AuthorizationSetBuilder()
2416 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2417 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002418 .Digest(Digest::NONE)
2419 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002420}
2421
2422/*
David Drysdale42fe1892021-10-14 14:43:46 +01002423 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002424 *
David Drysdale42fe1892021-10-14 14:43:46 +01002425 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002426 * UNSUPPORTED_KEY_SIZE.
2427 */
David Drysdale42fe1892021-10-14 14:43:46 +01002428TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002429 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07002430 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002431 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002432 auto result = GenerateKey(AuthorizationSetBuilder()
2433 .EcdsaSigningKey(curve)
2434 .Digest(Digest::NONE)
2435 .SetDefaultValidity(),
2436 &key_blob, &key_characteristics);
2437 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2438 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002439 }
2440
David Drysdaledf09e542021-06-08 15:46:11 +01002441 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2442 GenerateKey(AuthorizationSetBuilder()
2443 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2444 .Authorization(TAG_KEY_SIZE, 190)
2445 .SigningKey()
2446 .Digest(Digest::NONE)
2447 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002448}
2449
2450/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002451 * NewKeyGenerationTest.EcdsaMissingCurve
2452 *
2453 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
2454 */
2455TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2456 if (AidlVersion() < 2) {
2457 /*
2458 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2459 * However, this was not checked at the time so we can only be strict about checking this
2460 * for implementations of KeyMint version 2 and above.
2461 */
2462 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
2463 }
2464 /* If EC_CURVE not provided, generateKey
2465 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2466 */
2467 auto result = GenerateKey(
2468 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2469 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2470 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2471}
2472
2473/*
Selene Huang31ab4042020-04-29 04:22:39 -07002474 * NewKeyGenerationTest.EcdsaMismatchKeySize
2475 *
2476 * Verifies that specifying mismatched key size and curve for EC key generation returns
2477 * INVALID_ARGUMENT.
2478 */
2479TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002480 if (SecLevel() == SecurityLevel::STRONGBOX) {
2481 GTEST_SKIP() << "Test not applicable to StrongBox device";
2482 }
Selene Huang31ab4042020-04-29 04:22:39 -07002483
David Drysdaledf09e542021-06-08 15:46:11 +01002484 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002485 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002486 .Authorization(TAG_KEY_SIZE, 224)
2487 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002488 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002489 .Digest(Digest::NONE)
2490 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002491 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002492}
2493
2494/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002495 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002496 *
2497 * Verifies that keymint does not support any curve designated as unsupported.
2498 */
2499TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2500 Digest digest;
2501 if (SecLevel() == SecurityLevel::STRONGBOX) {
2502 digest = Digest::SHA_2_256;
2503 } else {
2504 digest = Digest::SHA_2_512;
2505 }
2506 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08002507 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2508 .EcdsaSigningKey(curve)
2509 .Digest(digest)
2510 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002511 << "Failed to generate key on curve: " << curve;
2512 CheckedDeleteKey();
2513 }
2514}
2515
2516/*
2517 * NewKeyGenerationTest.Hmac
2518 *
2519 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2520 * characteristics.
2521 */
2522TEST_P(NewKeyGenerationTest, Hmac) {
2523 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2524 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002525 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002526 constexpr size_t key_size = 128;
2527 ASSERT_EQ(ErrorCode::OK,
2528 GenerateKey(
2529 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2530 TAG_MIN_MAC_LENGTH, 128),
2531 &key_blob, &key_characteristics));
2532
2533 ASSERT_GT(key_blob.size(), 0U);
2534 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002535 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002536
Shawn Willden7f424372021-01-10 18:06:50 -07002537 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2538 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2539 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2540 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002541
2542 CheckedDeleteKey(&key_blob);
2543 }
2544}
2545
2546/*
Selene Huang4f64c222021-04-13 19:54:36 -07002547 * NewKeyGenerationTest.HmacNoAttestation
2548 *
2549 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2550 * and app id are provided.
2551 */
2552TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2553 auto challenge = "hello";
2554 auto app_id = "foo";
2555
2556 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2557 vector<uint8_t> key_blob;
2558 vector<KeyCharacteristics> key_characteristics;
2559 constexpr size_t key_size = 128;
2560 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2561 .HmacKey(key_size)
2562 .Digest(digest)
2563 .AttestationChallenge(challenge)
2564 .AttestationApplicationId(app_id)
2565 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2566 &key_blob, &key_characteristics));
2567
2568 ASSERT_GT(key_blob.size(), 0U);
2569 ASSERT_EQ(cert_chain_.size(), 0);
2570 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002571 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002572
2573 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2574 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2575 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2576 << "Key size " << key_size << "missing";
2577
2578 CheckedDeleteKey(&key_blob);
2579 }
2580}
2581
2582/*
Qi Wud22ec842020-11-26 13:27:53 +08002583 * NewKeyGenerationTest.LimitedUsageHmac
2584 *
2585 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2586 * resulting keys have correct characteristics.
2587 */
2588TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2589 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2590 vector<uint8_t> key_blob;
2591 vector<KeyCharacteristics> key_characteristics;
2592 constexpr size_t key_size = 128;
2593 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2594 .HmacKey(key_size)
2595 .Digest(digest)
2596 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2597 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2598 &key_blob, &key_characteristics));
2599
2600 ASSERT_GT(key_blob.size(), 0U);
2601 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002602 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002603
2604 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2605 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2606 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2607 << "Key size " << key_size << "missing";
2608
2609 // Check the usage count limit tag appears in the authorizations.
2610 AuthorizationSet auths;
2611 for (auto& entry : key_characteristics) {
2612 auths.push_back(AuthorizationSet(entry.authorizations));
2613 }
2614 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2615 << "key usage count limit " << 1U << " missing";
2616
2617 CheckedDeleteKey(&key_blob);
2618 }
2619}
2620
2621/*
Selene Huang31ab4042020-04-29 04:22:39 -07002622 * NewKeyGenerationTest.HmacCheckKeySizes
2623 *
2624 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2625 */
2626TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2627 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2628 if (key_size < 64 || key_size % 8 != 0) {
2629 // To keep this test from being very slow, we only test a random fraction of
2630 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2631 // them, we expect to run ~40 of them in each run.
2632 if (key_size % 8 == 0 || random() % 10 == 0) {
2633 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2634 GenerateKey(AuthorizationSetBuilder()
2635 .HmacKey(key_size)
2636 .Digest(Digest::SHA_2_256)
2637 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2638 << "HMAC key size " << key_size << " invalid";
2639 }
2640 } else {
2641 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2642 .HmacKey(key_size)
2643 .Digest(Digest::SHA_2_256)
2644 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2645 << "Failed to generate HMAC key of size " << key_size;
2646 CheckedDeleteKey();
2647 }
2648 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002649 if (SecLevel() == SecurityLevel::STRONGBOX) {
2650 // STRONGBOX devices must not support keys larger than 512 bits.
2651 size_t key_size = 520;
2652 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2653 GenerateKey(AuthorizationSetBuilder()
2654 .HmacKey(key_size)
2655 .Digest(Digest::SHA_2_256)
2656 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2657 << "HMAC key size " << key_size << " unexpectedly valid";
2658 }
Selene Huang31ab4042020-04-29 04:22:39 -07002659}
2660
2661/*
2662 * NewKeyGenerationTest.HmacCheckMinMacLengths
2663 *
2664 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2665 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2666 * specific MAC length that failed, so reproducing a failed run will be easy.
2667 */
2668TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2669 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2670 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2671 // To keep this test from being very long, we only test a random fraction of
2672 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2673 // we expect to run ~17 of them in each run.
2674 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2675 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2676 GenerateKey(AuthorizationSetBuilder()
2677 .HmacKey(128)
2678 .Digest(Digest::SHA_2_256)
2679 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2680 << "HMAC min mac length " << min_mac_length << " invalid.";
2681 }
2682 } else {
2683 EXPECT_EQ(ErrorCode::OK,
2684 GenerateKey(AuthorizationSetBuilder()
2685 .HmacKey(128)
2686 .Digest(Digest::SHA_2_256)
2687 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2688 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2689 CheckedDeleteKey();
2690 }
2691 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002692
2693 // Minimum MAC length must be no more than 512 bits.
2694 size_t min_mac_length = 520;
2695 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2696 GenerateKey(AuthorizationSetBuilder()
2697 .HmacKey(128)
2698 .Digest(Digest::SHA_2_256)
2699 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2700 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002701}
2702
2703/*
2704 * NewKeyGenerationTest.HmacMultipleDigests
2705 *
2706 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2707 */
2708TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002709 if (SecLevel() == SecurityLevel::STRONGBOX) {
2710 GTEST_SKIP() << "Test not applicable to StrongBox device";
2711 }
Selene Huang31ab4042020-04-29 04:22:39 -07002712
2713 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2714 GenerateKey(AuthorizationSetBuilder()
2715 .HmacKey(128)
2716 .Digest(Digest::SHA1)
2717 .Digest(Digest::SHA_2_256)
2718 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2719}
2720
2721/*
2722 * NewKeyGenerationTest.HmacDigestNone
2723 *
2724 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2725 */
2726TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2727 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2728 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2729 128)));
2730
2731 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2732 GenerateKey(AuthorizationSetBuilder()
2733 .HmacKey(128)
2734 .Digest(Digest::NONE)
2735 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2736}
2737
Selene Huang4f64c222021-04-13 19:54:36 -07002738/*
2739 * NewKeyGenerationTest.AesNoAttestation
2740 *
2741 * Verifies that attestation parameters to AES keys are ignored and generateKey
2742 * will succeed.
2743 */
2744TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2745 auto challenge = "hello";
2746 auto app_id = "foo";
2747
2748 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2749 .Authorization(TAG_NO_AUTH_REQUIRED)
2750 .AesEncryptionKey(128)
2751 .EcbMode()
2752 .Padding(PaddingMode::PKCS7)
2753 .AttestationChallenge(challenge)
2754 .AttestationApplicationId(app_id)));
2755
2756 ASSERT_EQ(cert_chain_.size(), 0);
2757}
2758
2759/*
2760 * NewKeyGenerationTest.TripleDesNoAttestation
2761 *
2762 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2763 * will be successful. No attestation should be generated.
2764 */
2765TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2766 auto challenge = "hello";
2767 auto app_id = "foo";
2768
2769 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2770 .TripleDesEncryptionKey(168)
2771 .BlockMode(BlockMode::ECB)
2772 .Authorization(TAG_NO_AUTH_REQUIRED)
2773 .Padding(PaddingMode::NONE)
2774 .AttestationChallenge(challenge)
2775 .AttestationApplicationId(app_id)));
2776 ASSERT_EQ(cert_chain_.size(), 0);
2777}
2778
Selene Huang31ab4042020-04-29 04:22:39 -07002779INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2780
2781typedef KeyMintAidlTestBase SigningOperationsTest;
2782
2783/*
2784 * SigningOperationsTest.RsaSuccess
2785 *
2786 * Verifies that raw RSA signature operations succeed.
2787 */
2788TEST_P(SigningOperationsTest, RsaSuccess) {
2789 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2790 .RsaSigningKey(2048, 65537)
2791 .Digest(Digest::NONE)
2792 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002793 .Authorization(TAG_NO_AUTH_REQUIRED)
2794 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002795 string message = "12345678901234567890123456789012";
2796 string signature = SignMessage(
2797 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002798 LocalVerifyMessage(message, signature,
2799 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2800}
2801
2802/*
2803 * SigningOperationsTest.RsaAllPaddingsAndDigests
2804 *
2805 * Verifies RSA signature/verification for all padding modes and digests.
2806 */
2807TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2808 auto authorizations = AuthorizationSetBuilder()
2809 .Authorization(TAG_NO_AUTH_REQUIRED)
2810 .RsaSigningKey(2048, 65537)
2811 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2812 .Padding(PaddingMode::NONE)
2813 .Padding(PaddingMode::RSA_PSS)
2814 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2815 .SetDefaultValidity();
2816
2817 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2818
2819 string message(128, 'a');
2820 string corrupt_message(message);
2821 ++corrupt_message[corrupt_message.size() / 2];
2822
2823 for (auto padding :
2824 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2825 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2826 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2827 // Digesting only makes sense with padding.
2828 continue;
2829 }
2830
2831 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2832 // PSS requires digesting.
2833 continue;
2834 }
2835
2836 string signature =
2837 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2838 LocalVerifyMessage(message, signature,
2839 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2840 }
2841 }
Selene Huang31ab4042020-04-29 04:22:39 -07002842}
2843
2844/*
2845 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2846 *
Shawn Willden7f424372021-01-10 18:06:50 -07002847 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002848 */
2849TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2850 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2851 .Authorization(TAG_NO_AUTH_REQUIRED)
2852 .RsaSigningKey(2048, 65537)
2853 .Digest(Digest::NONE)
2854 .Padding(PaddingMode::NONE)
2855 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002856 .Authorization(TAG_APPLICATION_DATA, "appdata")
2857 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002858
2859 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2860
Selene Huang31ab4042020-04-29 04:22:39 -07002861 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2862 Begin(KeyPurpose::SIGN,
2863 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2864 AbortIfNeeded();
2865 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2866 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2867 .Digest(Digest::NONE)
2868 .Padding(PaddingMode::NONE)
2869 .Authorization(TAG_APPLICATION_ID, "clientid")));
2870 AbortIfNeeded();
2871 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2872 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2873 .Digest(Digest::NONE)
2874 .Padding(PaddingMode::NONE)
2875 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2876 AbortIfNeeded();
2877 EXPECT_EQ(ErrorCode::OK,
2878 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2879 .Digest(Digest::NONE)
2880 .Padding(PaddingMode::NONE)
2881 .Authorization(TAG_APPLICATION_DATA, "appdata")
2882 .Authorization(TAG_APPLICATION_ID, "clientid")));
2883 AbortIfNeeded();
2884}
2885
2886/*
2887 * SigningOperationsTest.RsaPssSha256Success
2888 *
2889 * Verifies that RSA-PSS signature operations succeed.
2890 */
2891TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2892 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2893 .RsaSigningKey(2048, 65537)
2894 .Digest(Digest::SHA_2_256)
2895 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002896 .Authorization(TAG_NO_AUTH_REQUIRED)
2897 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002898 // Use large message, which won't work without digesting.
2899 string message(1024, 'a');
2900 string signature = SignMessage(
2901 message,
2902 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2903}
2904
2905/*
2906 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2907 *
2908 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2909 * supports only unpadded operations.
2910 */
2911TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2912 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2913 .RsaSigningKey(2048, 65537)
2914 .Digest(Digest::NONE)
2915 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002916 .Padding(PaddingMode::NONE)
2917 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002918 string message = "12345678901234567890123456789012";
2919 string signature;
2920
2921 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2922 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2923 .Digest(Digest::NONE)
2924 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2925}
2926
2927/*
2928 * SigningOperationsTest.NoUserConfirmation
2929 *
2930 * Verifies that keymint rejects signing operations for keys with
2931 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2932 * presented.
2933 */
2934TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002935 if (SecLevel() == SecurityLevel::STRONGBOX) {
2936 GTEST_SKIP() << "Test not applicable to StrongBox device";
2937 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002938 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2939 .RsaSigningKey(1024, 65537)
2940 .Digest(Digest::NONE)
2941 .Padding(PaddingMode::NONE)
2942 .Authorization(TAG_NO_AUTH_REQUIRED)
2943 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2944 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002945
2946 const string message = "12345678901234567890123456789012";
2947 EXPECT_EQ(ErrorCode::OK,
2948 Begin(KeyPurpose::SIGN,
2949 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2950 string signature;
2951 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2952}
2953
2954/*
2955 * SigningOperationsTest.RsaPkcs1Sha256Success
2956 *
2957 * Verifies that digested RSA-PKCS1 signature operations succeed.
2958 */
2959TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2960 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2961 .RsaSigningKey(2048, 65537)
2962 .Digest(Digest::SHA_2_256)
2963 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002964 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2965 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002966 string message(1024, 'a');
2967 string signature = SignMessage(message, AuthorizationSetBuilder()
2968 .Digest(Digest::SHA_2_256)
2969 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2970}
2971
2972/*
2973 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2974 *
2975 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2976 */
2977TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2978 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2979 .RsaSigningKey(2048, 65537)
2980 .Digest(Digest::NONE)
2981 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002982 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2983 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002984 string message(53, 'a');
2985 string signature = SignMessage(message, AuthorizationSetBuilder()
2986 .Digest(Digest::NONE)
2987 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2988}
2989
2990/*
2991 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2992 *
2993 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2994 * given a too-long message.
2995 */
2996TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2997 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2998 .RsaSigningKey(2048, 65537)
2999 .Digest(Digest::NONE)
3000 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003001 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3002 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003003 string message(257, 'a');
3004
3005 EXPECT_EQ(ErrorCode::OK,
3006 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3007 .Digest(Digest::NONE)
3008 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3009 string signature;
3010 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3011}
3012
3013/*
3014 * SigningOperationsTest.RsaPssSha512TooSmallKey
3015 *
3016 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3017 * used with a key that is too small for the message.
3018 *
3019 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3020 * keymint specification requires that salt_size == digest_size, so the message will be
3021 * digest_size * 2 +
3022 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3023 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3024 * for a 1024-bit key.
3025 */
3026TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003027 if (SecLevel() == SecurityLevel::STRONGBOX) {
3028 GTEST_SKIP() << "Test not applicable to StrongBox device";
3029 }
Selene Huang31ab4042020-04-29 04:22:39 -07003030 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3031 .RsaSigningKey(1024, 65537)
3032 .Digest(Digest::SHA_2_512)
3033 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003034 .Padding(PaddingMode::RSA_PSS)
3035 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003036 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3037 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3038 .Digest(Digest::SHA_2_512)
3039 .Padding(PaddingMode::RSA_PSS)));
3040}
3041
3042/*
3043 * SigningOperationsTest.RsaNoPaddingTooLong
3044 *
3045 * Verifies that raw RSA signature operations fail with the correct error code when
3046 * given a too-long message.
3047 */
3048TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3049 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3050 .RsaSigningKey(2048, 65537)
3051 .Digest(Digest::NONE)
3052 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003053 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3054 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003055 // One byte too long
3056 string message(2048 / 8 + 1, 'a');
3057 ASSERT_EQ(ErrorCode::OK,
3058 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3059 .Digest(Digest::NONE)
3060 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3061 string result;
3062 ErrorCode finish_error_code = Finish(message, &result);
3063 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3064 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3065
3066 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3067 message = string(128 * 1024, 'a');
3068 ASSERT_EQ(ErrorCode::OK,
3069 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3070 .Digest(Digest::NONE)
3071 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3072 finish_error_code = Finish(message, &result);
3073 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3074 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3075}
3076
3077/*
3078 * SigningOperationsTest.RsaAbort
3079 *
3080 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3081 * test, but the behavior should be algorithm and purpose-independent.
3082 */
3083TEST_P(SigningOperationsTest, RsaAbort) {
3084 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3085 .RsaSigningKey(2048, 65537)
3086 .Digest(Digest::NONE)
3087 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003088 .Padding(PaddingMode::NONE)
3089 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003090
3091 ASSERT_EQ(ErrorCode::OK,
3092 Begin(KeyPurpose::SIGN,
3093 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3094 EXPECT_EQ(ErrorCode::OK, Abort());
3095
3096 // Another abort should fail
3097 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3098
3099 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003100 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003101}
3102
3103/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003104 * SigningOperationsTest.RsaNonUniqueParams
3105 *
3106 * Verifies that an operation with multiple padding modes is rejected.
3107 */
3108TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3109 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3110 .RsaSigningKey(2048, 65537)
3111 .Digest(Digest::NONE)
3112 .Digest(Digest::SHA1)
3113 .Authorization(TAG_NO_AUTH_REQUIRED)
3114 .Padding(PaddingMode::NONE)
3115 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3116 .SetDefaultValidity()));
3117
3118 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3119 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3120 .Digest(Digest::NONE)
3121 .Padding(PaddingMode::NONE)
3122 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3123
Tommy Chiuc93c4392021-05-11 18:36:50 +08003124 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3125 .Digest(Digest::NONE)
3126 .Digest(Digest::SHA1)
3127 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3128 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003129
3130 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3131 Begin(KeyPurpose::SIGN,
3132 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3133}
3134
3135/*
Selene Huang31ab4042020-04-29 04:22:39 -07003136 * SigningOperationsTest.RsaUnsupportedPadding
3137 *
3138 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3139 * with a padding mode inappropriate for RSA.
3140 */
3141TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3142 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3143 .RsaSigningKey(2048, 65537)
3144 .Authorization(TAG_NO_AUTH_REQUIRED)
3145 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003146 .Padding(PaddingMode::PKCS7)
3147 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003148 ASSERT_EQ(
3149 ErrorCode::UNSUPPORTED_PADDING_MODE,
3150 Begin(KeyPurpose::SIGN,
3151 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003152 CheckedDeleteKey();
3153
3154 ASSERT_EQ(ErrorCode::OK,
3155 GenerateKey(
3156 AuthorizationSetBuilder()
3157 .RsaSigningKey(2048, 65537)
3158 .Authorization(TAG_NO_AUTH_REQUIRED)
3159 .Digest(Digest::SHA_2_256 /* supported digest */)
3160 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3161 .SetDefaultValidity()));
3162 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3163 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3164 .Digest(Digest::SHA_2_256)
3165 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003166}
3167
3168/*
3169 * SigningOperationsTest.RsaPssNoDigest
3170 *
3171 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3172 */
3173TEST_P(SigningOperationsTest, RsaNoDigest) {
3174 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3175 .RsaSigningKey(2048, 65537)
3176 .Authorization(TAG_NO_AUTH_REQUIRED)
3177 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003178 .Padding(PaddingMode::RSA_PSS)
3179 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003180 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3181 Begin(KeyPurpose::SIGN,
3182 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3183
3184 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3185 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3186}
3187
3188/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003189 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003190 *
3191 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3192 * supported in some cases (as validated in other tests), but a mode must be specified.
3193 */
3194TEST_P(SigningOperationsTest, RsaNoPadding) {
3195 // Padding must be specified
3196 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3197 .RsaKey(2048, 65537)
3198 .Authorization(TAG_NO_AUTH_REQUIRED)
3199 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003200 .Digest(Digest::NONE)
3201 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003202 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3203 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3204}
3205
3206/*
3207 * SigningOperationsTest.RsaShortMessage
3208 *
3209 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3210 */
3211TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3212 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3213 .Authorization(TAG_NO_AUTH_REQUIRED)
3214 .RsaSigningKey(2048, 65537)
3215 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003216 .Padding(PaddingMode::NONE)
3217 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003218
3219 // Barely shorter
3220 string message(2048 / 8 - 1, 'a');
3221 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3222
3223 // Much shorter
3224 message = "a";
3225 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3226}
3227
3228/*
3229 * SigningOperationsTest.RsaSignWithEncryptionKey
3230 *
3231 * Verifies that RSA encryption keys cannot be used to sign.
3232 */
3233TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3234 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3235 .Authorization(TAG_NO_AUTH_REQUIRED)
3236 .RsaEncryptionKey(2048, 65537)
3237 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003238 .Padding(PaddingMode::NONE)
3239 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003240 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3241 Begin(KeyPurpose::SIGN,
3242 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3243}
3244
3245/*
3246 * SigningOperationsTest.RsaSignTooLargeMessage
3247 *
3248 * Verifies that attempting a raw signature of a message which is the same length as the key,
3249 * but numerically larger than the public modulus, fails with the correct error.
3250 */
3251TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3252 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3253 .Authorization(TAG_NO_AUTH_REQUIRED)
3254 .RsaSigningKey(2048, 65537)
3255 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003256 .Padding(PaddingMode::NONE)
3257 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003258
3259 // Largest possible message will always be larger than the public modulus.
3260 string message(2048 / 8, static_cast<char>(0xff));
3261 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3262 .Authorization(TAG_NO_AUTH_REQUIRED)
3263 .Digest(Digest::NONE)
3264 .Padding(PaddingMode::NONE)));
3265 string signature;
3266 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3267}
3268
3269/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003270 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3271 *
David Drysdale42fe1892021-10-14 14:43:46 +01003272 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003273 */
3274TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003275
3276 string message = "1234567890";
3277 string corrupt_message = "2234567890";
3278 for (auto curve : ValidCurves()) {
3279 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003280 // Ed25519 only allows Digest::NONE.
3281 auto digests = (curve == EcCurve::CURVE_25519)
3282 ? std::vector<Digest>(1, Digest::NONE)
3283 : ValidDigests(true /* withNone */, false /* withMD5 */);
3284
David Drysdaledf8f52e2021-05-06 08:10:58 +01003285 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3286 .Authorization(TAG_NO_AUTH_REQUIRED)
3287 .EcdsaSigningKey(curve)
3288 .Digest(digests)
3289 .SetDefaultValidity());
3290 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3291 if (error != ErrorCode::OK) {
3292 continue;
3293 }
3294
3295 for (auto digest : digests) {
3296 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3297 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3298 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3299 }
3300
3301 auto rc = DeleteKey();
3302 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3303 }
3304}
3305
3306/*
Selene Huang31ab4042020-04-29 04:22:39 -07003307 * SigningOperationsTest.EcdsaAllCurves
3308 *
David Drysdale42fe1892021-10-14 14:43:46 +01003309 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003310 */
3311TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3312 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003313 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3314 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003315 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3316 .Authorization(TAG_NO_AUTH_REQUIRED)
3317 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003318 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003319 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003320 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3321 if (error != ErrorCode::OK) continue;
3322
3323 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003324 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003325 CheckedDeleteKey();
3326 }
3327}
3328
3329/*
David Drysdale42fe1892021-10-14 14:43:46 +01003330 * SigningOperationsTest.EcdsaCurve25519
3331 *
3332 * Verifies that ECDSA operations succeed with curve25519.
3333 */
3334TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3335 if (!Curve25519Supported()) {
3336 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3337 }
3338
3339 EcCurve curve = EcCurve::CURVE_25519;
3340 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3341 .Authorization(TAG_NO_AUTH_REQUIRED)
3342 .EcdsaSigningKey(curve)
3343 .Digest(Digest::NONE)
3344 .SetDefaultValidity());
3345 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3346
3347 string message(1024, 'a');
3348 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3349 CheckedDeleteKey();
3350}
3351
3352/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003353 * SigningOperationsTest.EcdsaCurve25519MaxSize
3354 *
3355 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3356 */
3357TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3358 if (!Curve25519Supported()) {
3359 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3360 }
3361
3362 EcCurve curve = EcCurve::CURVE_25519;
3363 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3364 .Authorization(TAG_NO_AUTH_REQUIRED)
3365 .EcdsaSigningKey(curve)
3366 .Digest(Digest::NONE)
3367 .SetDefaultValidity());
3368 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3369
3370 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3371
3372 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3373 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3374 string message(msg_size, 'a');
3375
3376 // Attempt to sign via Begin+Finish.
3377 AuthorizationSet out_params;
3378 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3379 EXPECT_TRUE(out_params.empty());
3380 string signature;
3381 auto result = Finish(message, &signature);
3382 EXPECT_EQ(result, ErrorCode::OK);
3383 LocalVerifyMessage(message, signature, params);
3384
3385 // Attempt to sign via Begin+Update+Finish
3386 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3387 EXPECT_TRUE(out_params.empty());
3388 string output;
3389 result = Update(message, &output);
3390 EXPECT_EQ(result, ErrorCode::OK);
3391 EXPECT_EQ(output.size(), 0);
3392 string signature2;
3393 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3394 LocalVerifyMessage(message, signature2, params);
3395 }
3396
3397 CheckedDeleteKey();
3398}
3399
3400/*
3401 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3402 *
3403 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3404 */
3405TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3406 if (!Curve25519Supported()) {
3407 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3408 }
3409
3410 EcCurve curve = EcCurve::CURVE_25519;
3411 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3412 .Authorization(TAG_NO_AUTH_REQUIRED)
3413 .EcdsaSigningKey(curve)
3414 .Digest(Digest::NONE)
3415 .SetDefaultValidity());
3416 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3417
3418 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3419
3420 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3421 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3422 string message(msg_size, 'a');
3423
3424 // Attempt to sign via Begin+Finish.
3425 AuthorizationSet out_params;
3426 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3427 EXPECT_TRUE(out_params.empty());
3428 string signature;
3429 auto result = Finish(message, &signature);
3430 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3431
3432 // Attempt to sign via Begin+Update (but never get to Finish)
3433 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3434 EXPECT_TRUE(out_params.empty());
3435 string output;
3436 result = Update(message, &output);
3437 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3438 }
3439
3440 CheckedDeleteKey();
3441}
3442
3443/*
Selene Huang31ab4042020-04-29 04:22:39 -07003444 * SigningOperationsTest.EcdsaNoDigestHugeData
3445 *
3446 * Verifies that ECDSA operations support very large messages, even without digesting. This
3447 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3448 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3449 * the framework.
3450 */
3451TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3452 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3453 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003454 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003455 .Digest(Digest::NONE)
3456 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003457 string message(1 * 1024, 'a');
3458 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3459}
3460
3461/*
3462 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3463 *
3464 * Verifies that using an EC key requires the correct app ID/data.
3465 */
3466TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3467 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3468 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003469 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003470 .Digest(Digest::NONE)
3471 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003472 .Authorization(TAG_APPLICATION_DATA, "appdata")
3473 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003474
3475 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3476
Selene Huang31ab4042020-04-29 04:22:39 -07003477 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3478 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3479 AbortIfNeeded();
3480 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3481 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3482 .Digest(Digest::NONE)
3483 .Authorization(TAG_APPLICATION_ID, "clientid")));
3484 AbortIfNeeded();
3485 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3486 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3487 .Digest(Digest::NONE)
3488 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3489 AbortIfNeeded();
3490 EXPECT_EQ(ErrorCode::OK,
3491 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3492 .Digest(Digest::NONE)
3493 .Authorization(TAG_APPLICATION_DATA, "appdata")
3494 .Authorization(TAG_APPLICATION_ID, "clientid")));
3495 AbortIfNeeded();
3496}
3497
3498/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003499 * SigningOperationsTest.EcdsaIncompatibleDigest
3500 *
3501 * Verifies that using an EC key requires compatible digest.
3502 */
3503TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3504 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3505 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003506 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003507 .Digest(Digest::NONE)
3508 .Digest(Digest::SHA1)
3509 .SetDefaultValidity()));
3510 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3511 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3512 AbortIfNeeded();
3513}
3514
3515/*
Selene Huang31ab4042020-04-29 04:22:39 -07003516 * SigningOperationsTest.AesEcbSign
3517 *
3518 * Verifies that attempts to use AES keys to sign fail in the correct way.
3519 */
3520TEST_P(SigningOperationsTest, AesEcbSign) {
3521 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3522 .Authorization(TAG_NO_AUTH_REQUIRED)
3523 .SigningKey()
3524 .AesEncryptionKey(128)
3525 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3526
3527 AuthorizationSet out_params;
3528 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3529 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3530 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3531 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3532}
3533
3534/*
3535 * SigningOperationsTest.HmacAllDigests
3536 *
3537 * Verifies that HMAC works with all digests.
3538 */
3539TEST_P(SigningOperationsTest, HmacAllDigests) {
3540 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
3541 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3542 .Authorization(TAG_NO_AUTH_REQUIRED)
3543 .HmacKey(128)
3544 .Digest(digest)
3545 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3546 << "Failed to create HMAC key with digest " << digest;
3547 string message = "12345678901234567890123456789012";
3548 string signature = MacMessage(message, digest, 160);
3549 EXPECT_EQ(160U / 8U, signature.size())
3550 << "Failed to sign with HMAC key with digest " << digest;
3551 CheckedDeleteKey();
3552 }
3553}
3554
3555/*
3556 * SigningOperationsTest.HmacSha256TooLargeMacLength
3557 *
3558 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3559 * digest size.
3560 */
3561TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3562 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3563 .Authorization(TAG_NO_AUTH_REQUIRED)
3564 .HmacKey(128)
3565 .Digest(Digest::SHA_2_256)
3566 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3567 AuthorizationSet output_params;
3568 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3569 AuthorizationSetBuilder()
3570 .Digest(Digest::SHA_2_256)
3571 .Authorization(TAG_MAC_LENGTH, 264),
3572 &output_params));
3573}
3574
3575/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003576 * SigningOperationsTest.HmacSha256InvalidMacLength
3577 *
3578 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3579 * not a multiple of 8.
3580 */
3581TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3582 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3583 .Authorization(TAG_NO_AUTH_REQUIRED)
3584 .HmacKey(128)
3585 .Digest(Digest::SHA_2_256)
3586 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3587 AuthorizationSet output_params;
3588 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3589 AuthorizationSetBuilder()
3590 .Digest(Digest::SHA_2_256)
3591 .Authorization(TAG_MAC_LENGTH, 161),
3592 &output_params));
3593}
3594
3595/*
Selene Huang31ab4042020-04-29 04:22:39 -07003596 * SigningOperationsTest.HmacSha256TooSmallMacLength
3597 *
3598 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3599 * specified minimum MAC length.
3600 */
3601TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3602 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3603 .Authorization(TAG_NO_AUTH_REQUIRED)
3604 .HmacKey(128)
3605 .Digest(Digest::SHA_2_256)
3606 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3607 AuthorizationSet output_params;
3608 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3609 AuthorizationSetBuilder()
3610 .Digest(Digest::SHA_2_256)
3611 .Authorization(TAG_MAC_LENGTH, 120),
3612 &output_params));
3613}
3614
3615/*
3616 * SigningOperationsTest.HmacRfc4231TestCase3
3617 *
3618 * Validates against the test vectors from RFC 4231 test case 3.
3619 */
3620TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3621 string key(20, 0xaa);
3622 string message(50, 0xdd);
3623 uint8_t sha_224_expected[] = {
3624 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3625 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3626 };
3627 uint8_t sha_256_expected[] = {
3628 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3629 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3630 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3631 };
3632 uint8_t sha_384_expected[] = {
3633 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3634 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3635 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3636 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3637 };
3638 uint8_t sha_512_expected[] = {
3639 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3640 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3641 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3642 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3643 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3644 };
3645
3646 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3647 if (SecLevel() != SecurityLevel::STRONGBOX) {
3648 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3649 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3650 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3651 }
3652}
3653
3654/*
3655 * SigningOperationsTest.HmacRfc4231TestCase5
3656 *
3657 * Validates against the test vectors from RFC 4231 test case 5.
3658 */
3659TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3660 string key(20, 0x0c);
3661 string message = "Test With Truncation";
3662
3663 uint8_t sha_224_expected[] = {
3664 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3665 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3666 };
3667 uint8_t sha_256_expected[] = {
3668 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3669 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3670 };
3671 uint8_t sha_384_expected[] = {
3672 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3673 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3674 };
3675 uint8_t sha_512_expected[] = {
3676 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3677 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3678 };
3679
3680 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3681 if (SecLevel() != SecurityLevel::STRONGBOX) {
3682 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3683 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3684 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3685 }
3686}
3687
3688INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3689
3690typedef KeyMintAidlTestBase VerificationOperationsTest;
3691
3692/*
Selene Huang31ab4042020-04-29 04:22:39 -07003693 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3694 *
3695 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3696 */
3697TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3698 string key_material = "HelloThisIsAKey";
3699
3700 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003701 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003702 EXPECT_EQ(ErrorCode::OK,
3703 ImportKey(AuthorizationSetBuilder()
3704 .Authorization(TAG_NO_AUTH_REQUIRED)
3705 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3706 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3707 .Digest(Digest::SHA_2_256)
3708 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3709 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3710 EXPECT_EQ(ErrorCode::OK,
3711 ImportKey(AuthorizationSetBuilder()
3712 .Authorization(TAG_NO_AUTH_REQUIRED)
3713 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3714 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3715 .Digest(Digest::SHA_2_256)
3716 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3717 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3718
3719 string message = "This is a message.";
3720 string signature = SignMessage(
3721 signing_key, message,
3722 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3723
3724 // Signing key should not work.
3725 AuthorizationSet out_params;
3726 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3727 Begin(KeyPurpose::VERIFY, signing_key,
3728 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3729
3730 // Verification key should work.
3731 VerifyMessage(verification_key, message, signature,
3732 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3733
3734 CheckedDeleteKey(&signing_key);
3735 CheckedDeleteKey(&verification_key);
3736}
3737
Prashant Patildec9fdc2021-12-08 15:25:47 +00003738/*
3739 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3740 *
3741 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3742 */
3743TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3744 string key_material = "HelloThisIsAKey";
3745
3746 vector<uint8_t> signing_key, verification_key;
3747 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3748 EXPECT_EQ(ErrorCode::OK,
3749 ImportKey(AuthorizationSetBuilder()
3750 .Authorization(TAG_NO_AUTH_REQUIRED)
3751 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3752 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3753 .Digest(Digest::SHA_2_256)
3754 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3755 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3756 EXPECT_EQ(ErrorCode::OK,
3757 ImportKey(AuthorizationSetBuilder()
3758 .Authorization(TAG_NO_AUTH_REQUIRED)
3759 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3760 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3761 .Digest(Digest::SHA_2_256)
3762 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3763 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3764
3765 string message = "This is a message.";
3766 string signature = SignMessage(
3767 signing_key, message,
3768 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3769
3770 AuthorizationSet begin_out_params;
3771 ASSERT_EQ(ErrorCode::OK,
3772 Begin(KeyPurpose::VERIFY, verification_key,
3773 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3774
3775 string corruptMessage = "This is b message."; // Corrupted message
3776 string output;
3777 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3778
3779 ASSERT_EQ(ErrorCode::OK,
3780 Begin(KeyPurpose::VERIFY, verification_key,
3781 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3782
3783 signature[0] += 1; // Corrupt a signature
3784 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3785
3786 CheckedDeleteKey(&signing_key);
3787 CheckedDeleteKey(&verification_key);
3788}
3789
Selene Huang31ab4042020-04-29 04:22:39 -07003790INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3791
3792typedef KeyMintAidlTestBase ExportKeyTest;
3793
3794/*
3795 * ExportKeyTest.RsaUnsupportedKeyFormat
3796 *
3797 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3798 */
3799// TODO(seleneh) add ExportKey to GenerateKey
3800// check result
3801
3802class ImportKeyTest : public KeyMintAidlTestBase {
3803 public:
3804 template <TagType tag_type, Tag tag, typename ValueT>
3805 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3806 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003807 for (auto& entry : key_characteristics_) {
3808 if (entry.securityLevel == SecLevel()) {
3809 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3810 << "Tag " << tag << " with value " << expected
3811 << " not found at security level" << entry.securityLevel;
3812 } else {
3813 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3814 << "Tag " << tag << " found at security level " << entry.securityLevel;
3815 }
Selene Huang31ab4042020-04-29 04:22:39 -07003816 }
3817 }
3818
3819 void CheckOrigin() {
3820 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003821 // Origin isn't a crypto param, but it always lives with them.
3822 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003823 }
3824};
3825
3826/*
3827 * ImportKeyTest.RsaSuccess
3828 *
3829 * Verifies that importing and using an RSA key pair works correctly.
3830 */
3831TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003832 uint32_t key_size;
3833 string key;
3834
3835 if (SecLevel() == SecurityLevel::STRONGBOX) {
3836 key_size = 2048;
3837 key = rsa_2048_key;
3838 } else {
3839 key_size = 1024;
3840 key = rsa_key;
3841 }
3842
Selene Huang31ab4042020-04-29 04:22:39 -07003843 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3844 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003845 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003846 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003847 .Padding(PaddingMode::RSA_PSS)
3848 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003849 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003850
3851 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003852 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003853 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3854 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3855 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3856 CheckOrigin();
3857
3858 string message(1024 / 8, 'a');
3859 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3860 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003861 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003862}
3863
3864/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003865 * ImportKeyTest.RsaSuccessWithoutParams
3866 *
3867 * Verifies that importing and using an RSA key pair without specifying parameters
3868 * works correctly.
3869 */
3870TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3871 uint32_t key_size;
3872 string key;
3873
3874 if (SecLevel() == SecurityLevel::STRONGBOX) {
3875 key_size = 2048;
3876 key = rsa_2048_key;
3877 } else {
3878 key_size = 1024;
3879 key = rsa_key;
3880 }
3881
3882 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3883 .Authorization(TAG_NO_AUTH_REQUIRED)
3884 .SigningKey()
3885 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3886 .Digest(Digest::SHA_2_256)
3887 .Padding(PaddingMode::RSA_PSS)
3888 .SetDefaultValidity(),
3889 KeyFormat::PKCS8, key));
3890
3891 // Key size and public exponent are determined from the imported key material.
3892 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3893 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3894
3895 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3896 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3897 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3898 CheckOrigin();
3899
3900 string message(1024 / 8, 'a');
3901 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3902 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003903 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003904}
3905
3906/*
Selene Huang31ab4042020-04-29 04:22:39 -07003907 * ImportKeyTest.RsaKeySizeMismatch
3908 *
3909 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3910 * correct way.
3911 */
3912TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3913 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3914 ImportKey(AuthorizationSetBuilder()
3915 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3916 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003917 .Padding(PaddingMode::NONE)
3918 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003919 KeyFormat::PKCS8, rsa_key));
3920}
3921
3922/*
3923 * ImportKeyTest.RsaPublicExponentMismatch
3924 *
3925 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3926 * fails in the correct way.
3927 */
3928TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3929 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3930 ImportKey(AuthorizationSetBuilder()
3931 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3932 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003933 .Padding(PaddingMode::NONE)
3934 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003935 KeyFormat::PKCS8, rsa_key));
3936}
3937
3938/*
David Drysdalee60248c2021-10-04 12:54:13 +01003939 * ImportKeyTest.RsaAttestMultiPurposeFail
3940 *
3941 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
3942 */
3943TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00003944 if (AidlVersion() < 2) {
3945 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
3946 // with other key purposes. However, this was not checked at the time
3947 // so we can only be strict about checking this for implementations of KeyMint
3948 // version 2 and above.
3949 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
3950 }
David Drysdalee60248c2021-10-04 12:54:13 +01003951 uint32_t key_size = 2048;
3952 string key = rsa_2048_key;
3953
3954 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3955 ImportKey(AuthorizationSetBuilder()
3956 .Authorization(TAG_NO_AUTH_REQUIRED)
3957 .RsaSigningKey(key_size, 65537)
3958 .AttestKey()
3959 .Digest(Digest::SHA_2_256)
3960 .Padding(PaddingMode::RSA_PSS)
3961 .SetDefaultValidity(),
3962 KeyFormat::PKCS8, key));
3963}
3964
3965/*
Selene Huang31ab4042020-04-29 04:22:39 -07003966 * ImportKeyTest.EcdsaSuccess
3967 *
3968 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3969 */
3970TEST_P(ImportKeyTest, EcdsaSuccess) {
3971 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3972 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003973 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003974 .Digest(Digest::SHA_2_256)
3975 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003976 KeyFormat::PKCS8, ec_256_key));
3977
3978 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003979 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3980 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3981
3982 CheckOrigin();
3983
3984 string message(32, 'a');
3985 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3986 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003987 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003988}
3989
3990/*
3991 * ImportKeyTest.EcdsaP256RFC5915Success
3992 *
3993 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3994 * correctly.
3995 */
3996TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3997 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3998 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003999 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004000 .Digest(Digest::SHA_2_256)
4001 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004002 KeyFormat::PKCS8, ec_256_key_rfc5915));
4003
4004 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004005 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4006 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4007
4008 CheckOrigin();
4009
4010 string message(32, 'a');
4011 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4012 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004013 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004014}
4015
4016/*
4017 * ImportKeyTest.EcdsaP256SEC1Success
4018 *
4019 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4020 */
4021TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4022 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4023 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004024 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004025 .Digest(Digest::SHA_2_256)
4026 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004027 KeyFormat::PKCS8, ec_256_key_sec1));
4028
4029 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004030 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4031 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4032
4033 CheckOrigin();
4034
4035 string message(32, 'a');
4036 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4037 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004038 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004039}
4040
4041/*
4042 * ImportKeyTest.Ecdsa521Success
4043 *
4044 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4045 */
4046TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004047 if (SecLevel() == SecurityLevel::STRONGBOX) {
4048 GTEST_SKIP() << "Test not applicable to StrongBox device";
4049 }
Selene Huang31ab4042020-04-29 04:22:39 -07004050 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4051 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004052 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004053 .Digest(Digest::SHA_2_256)
4054 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004055 KeyFormat::PKCS8, ec_521_key));
4056
4057 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004058 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4059 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4060 CheckOrigin();
4061
4062 string message(32, 'a');
4063 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4064 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004065 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004066}
4067
4068/*
Selene Huang31ab4042020-04-29 04:22:39 -07004069 * ImportKeyTest.EcdsaCurveMismatch
4070 *
4071 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4072 * the correct way.
4073 */
4074TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4075 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4076 ImportKey(AuthorizationSetBuilder()
4077 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004078 .Digest(Digest::NONE)
4079 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004080 KeyFormat::PKCS8, ec_256_key));
4081}
4082
4083/*
David Drysdalee60248c2021-10-04 12:54:13 +01004084 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4085 *
4086 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4087 */
4088TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004089 if (AidlVersion() < 2) {
4090 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4091 // with other key purposes. However, this was not checked at the time
4092 // so we can only be strict about checking this for implementations of KeyMint
4093 // version 2 and above.
4094 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4095 }
David Drysdalee60248c2021-10-04 12:54:13 +01004096 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4097 ImportKey(AuthorizationSetBuilder()
4098 .Authorization(TAG_NO_AUTH_REQUIRED)
4099 .EcdsaSigningKey(EcCurve::P_256)
4100 .AttestKey()
4101 .Digest(Digest::SHA_2_256)
4102 .SetDefaultValidity(),
4103 KeyFormat::PKCS8, ec_256_key));
4104}
4105
4106/*
David Drysdale42fe1892021-10-14 14:43:46 +01004107 * ImportKeyTest.Ed25519RawSuccess
4108 *
4109 * Verifies that importing and using a raw Ed25519 private key works correctly.
4110 */
4111TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4112 if (!Curve25519Supported()) {
4113 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4114 }
4115
4116 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4117 .Authorization(TAG_NO_AUTH_REQUIRED)
4118 .EcdsaSigningKey(EcCurve::CURVE_25519)
4119 .Digest(Digest::NONE)
4120 .SetDefaultValidity(),
4121 KeyFormat::RAW, ed25519_key));
4122 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4123 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4124 CheckOrigin();
4125
4126 // The returned cert should hold the correct public key.
4127 ASSERT_GT(cert_chain_.size(), 0);
4128 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4129 ASSERT_NE(kmKeyCert, nullptr);
4130 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4131 ASSERT_NE(kmPubKey.get(), nullptr);
4132 size_t kmPubKeySize = 32;
4133 uint8_t kmPubKeyData[32];
4134 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4135 ASSERT_EQ(kmPubKeySize, 32);
4136 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4137
4138 string message(32, 'a');
4139 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4140 string signature = SignMessage(message, params);
4141 LocalVerifyMessage(message, signature, params);
4142}
4143
4144/*
4145 * ImportKeyTest.Ed25519Pkcs8Success
4146 *
4147 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4148 */
4149TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4150 if (!Curve25519Supported()) {
4151 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4152 }
4153
4154 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4155 .Authorization(TAG_NO_AUTH_REQUIRED)
4156 .EcdsaSigningKey(EcCurve::CURVE_25519)
4157 .Digest(Digest::NONE)
4158 .SetDefaultValidity(),
4159 KeyFormat::PKCS8, ed25519_pkcs8_key));
4160 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4161 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4162 CheckOrigin();
4163
4164 // The returned cert should hold the correct public key.
4165 ASSERT_GT(cert_chain_.size(), 0);
4166 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4167 ASSERT_NE(kmKeyCert, nullptr);
4168 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4169 ASSERT_NE(kmPubKey.get(), nullptr);
4170 size_t kmPubKeySize = 32;
4171 uint8_t kmPubKeyData[32];
4172 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4173 ASSERT_EQ(kmPubKeySize, 32);
4174 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4175
4176 string message(32, 'a');
4177 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4178 string signature = SignMessage(message, params);
4179 LocalVerifyMessage(message, signature, params);
4180}
4181
4182/*
4183 * ImportKeyTest.Ed25519CurveMismatch
4184 *
4185 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4186 * the correct way.
4187 */
4188TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4189 if (!Curve25519Supported()) {
4190 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4191 }
4192
4193 ASSERT_NE(ErrorCode::OK,
4194 ImportKey(AuthorizationSetBuilder()
4195 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4196 .Digest(Digest::NONE)
4197 .SetDefaultValidity(),
4198 KeyFormat::RAW, ed25519_key));
4199}
4200
4201/*
4202 * ImportKeyTest.Ed25519FormatMismatch
4203 *
4204 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4205 */
4206TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4207 if (!Curve25519Supported()) {
4208 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4209 }
4210
4211 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4212 .EcdsaSigningKey(EcCurve::CURVE_25519)
4213 .Digest(Digest::NONE)
4214 .SetDefaultValidity(),
4215 KeyFormat::PKCS8, ed25519_key));
4216 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4217 .EcdsaSigningKey(EcCurve::CURVE_25519)
4218 .Digest(Digest::NONE)
4219 .SetDefaultValidity(),
4220 KeyFormat::RAW, ed25519_pkcs8_key));
4221}
4222
4223/*
4224 * ImportKeyTest.Ed25519PurposeMismatch
4225 *
4226 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4227 */
4228TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4229 if (!Curve25519Supported()) {
4230 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4231 }
4232
4233 // Can't have both SIGN and ATTEST_KEY
4234 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4235 .EcdsaSigningKey(EcCurve::CURVE_25519)
4236 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4237 .Digest(Digest::NONE)
4238 .SetDefaultValidity(),
4239 KeyFormat::RAW, ed25519_key));
4240 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4241 // PKCS#8 format and so includes an OID).
4242 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4243 .EcdsaKey(EcCurve::CURVE_25519)
4244 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4245 .Digest(Digest::NONE)
4246 .SetDefaultValidity(),
4247 KeyFormat::PKCS8, ed25519_pkcs8_key));
4248}
4249
4250/*
4251 * ImportKeyTest.X25519RawSuccess
4252 *
4253 * Verifies that importing and using a raw X25519 private key works correctly.
4254 */
4255TEST_P(ImportKeyTest, X25519RawSuccess) {
4256 if (!Curve25519Supported()) {
4257 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4258 }
4259
4260 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4261 .Authorization(TAG_NO_AUTH_REQUIRED)
4262 .EcdsaKey(EcCurve::CURVE_25519)
4263 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4264 .SetDefaultValidity(),
4265 KeyFormat::RAW, x25519_key));
4266
4267 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4268 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4269 CheckOrigin();
4270}
4271
4272/*
4273 * ImportKeyTest.X25519Pkcs8Success
4274 *
4275 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4276 */
4277TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4278 if (!Curve25519Supported()) {
4279 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4280 }
4281
4282 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4283 .Authorization(TAG_NO_AUTH_REQUIRED)
4284 .EcdsaKey(EcCurve::CURVE_25519)
4285 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4286 .SetDefaultValidity(),
4287 KeyFormat::PKCS8, x25519_pkcs8_key));
4288
4289 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4290 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4291 CheckOrigin();
4292}
4293
4294/*
4295 * ImportKeyTest.X25519CurveMismatch
4296 *
4297 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4298 * the correct way.
4299 */
4300TEST_P(ImportKeyTest, X25519CurveMismatch) {
4301 if (!Curve25519Supported()) {
4302 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4303 }
4304
4305 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4306 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4307 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4308 .SetDefaultValidity(),
4309 KeyFormat::RAW, x25519_key));
4310}
4311
4312/*
4313 * ImportKeyTest.X25519FormatMismatch
4314 *
4315 * Verifies that importing an X25519 key with an invalid format fails.
4316 */
4317TEST_P(ImportKeyTest, X25519FormatMismatch) {
4318 if (!Curve25519Supported()) {
4319 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4320 }
4321
4322 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4323 .EcdsaKey(EcCurve::CURVE_25519)
4324 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4325 .SetDefaultValidity(),
4326 KeyFormat::PKCS8, x25519_key));
4327 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4328 .EcdsaKey(EcCurve::CURVE_25519)
4329 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4330 .SetDefaultValidity(),
4331 KeyFormat::RAW, x25519_pkcs8_key));
4332}
4333
4334/*
4335 * ImportKeyTest.X25519PurposeMismatch
4336 *
4337 * Verifies that importing an X25519 key pair with an invalid format fails.
4338 */
4339TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4340 if (!Curve25519Supported()) {
4341 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4342 }
4343
4344 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4345 .EcdsaKey(EcCurve::CURVE_25519)
4346 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4347 .SetDefaultValidity(),
4348 KeyFormat::PKCS8, x25519_pkcs8_key));
4349 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4350 .EcdsaSigningKey(EcCurve::CURVE_25519)
4351 .SetDefaultValidity(),
4352 KeyFormat::PKCS8, x25519_pkcs8_key));
4353}
4354
4355/*
Selene Huang31ab4042020-04-29 04:22:39 -07004356 * ImportKeyTest.AesSuccess
4357 *
4358 * Verifies that importing and using an AES key works.
4359 */
4360TEST_P(ImportKeyTest, AesSuccess) {
4361 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4362 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4363 .Authorization(TAG_NO_AUTH_REQUIRED)
4364 .AesEncryptionKey(key.size() * 8)
4365 .EcbMode()
4366 .Padding(PaddingMode::PKCS7),
4367 KeyFormat::RAW, key));
4368
4369 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4370 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4371 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4372 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4373 CheckOrigin();
4374
4375 string message = "Hello World!";
4376 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4377 string ciphertext = EncryptMessage(message, params);
4378 string plaintext = DecryptMessage(ciphertext, params);
4379 EXPECT_EQ(message, plaintext);
4380}
4381
4382/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004383 * ImportKeyTest.AesFailure
4384 *
4385 * Verifies that importing an invalid AES key fails.
4386 */
4387TEST_P(ImportKeyTest, AesFailure) {
4388 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4389 uint32_t bitlen = key.size() * 8;
4390 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004391 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004392 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004393 .Authorization(TAG_NO_AUTH_REQUIRED)
4394 .AesEncryptionKey(key_size)
4395 .EcbMode()
4396 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004397 KeyFormat::RAW, key);
4398 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004399 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4400 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004401 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004402
4403 // Explicit key size matches that of the provided key, but it's not a valid size.
4404 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4405 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4406 ImportKey(AuthorizationSetBuilder()
4407 .Authorization(TAG_NO_AUTH_REQUIRED)
4408 .AesEncryptionKey(long_key.size() * 8)
4409 .EcbMode()
4410 .Padding(PaddingMode::PKCS7),
4411 KeyFormat::RAW, long_key));
4412 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4413 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4414 ImportKey(AuthorizationSetBuilder()
4415 .Authorization(TAG_NO_AUTH_REQUIRED)
4416 .AesEncryptionKey(short_key.size() * 8)
4417 .EcbMode()
4418 .Padding(PaddingMode::PKCS7),
4419 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004420}
4421
4422/*
4423 * ImportKeyTest.TripleDesSuccess
4424 *
4425 * Verifies that importing and using a 3DES key works.
4426 */
4427TEST_P(ImportKeyTest, TripleDesSuccess) {
4428 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4429 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4430 .Authorization(TAG_NO_AUTH_REQUIRED)
4431 .TripleDesEncryptionKey(168)
4432 .EcbMode()
4433 .Padding(PaddingMode::PKCS7),
4434 KeyFormat::RAW, key));
4435
4436 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4437 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4438 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4439 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4440 CheckOrigin();
4441
4442 string message = "Hello World!";
4443 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4444 string ciphertext = EncryptMessage(message, params);
4445 string plaintext = DecryptMessage(ciphertext, params);
4446 EXPECT_EQ(message, plaintext);
4447}
4448
4449/*
4450 * ImportKeyTest.TripleDesFailure
4451 *
4452 * Verifies that importing an invalid 3DES key fails.
4453 */
4454TEST_P(ImportKeyTest, TripleDesFailure) {
4455 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004456 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004457 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004458 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004459 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004460 .Authorization(TAG_NO_AUTH_REQUIRED)
4461 .TripleDesEncryptionKey(key_size)
4462 .EcbMode()
4463 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004464 KeyFormat::RAW, key);
4465 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004466 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4467 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004468 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004469 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004470 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004471 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4472 ImportKey(AuthorizationSetBuilder()
4473 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004474 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004475 .EcbMode()
4476 .Padding(PaddingMode::PKCS7),
4477 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004478 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004479 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4480 ImportKey(AuthorizationSetBuilder()
4481 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004482 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004483 .EcbMode()
4484 .Padding(PaddingMode::PKCS7),
4485 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004486}
4487
4488/*
4489 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004490 *
4491 * Verifies that importing and using an HMAC key works.
4492 */
4493TEST_P(ImportKeyTest, HmacKeySuccess) {
4494 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4495 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4496 .Authorization(TAG_NO_AUTH_REQUIRED)
4497 .HmacKey(key.size() * 8)
4498 .Digest(Digest::SHA_2_256)
4499 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4500 KeyFormat::RAW, key));
4501
4502 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4503 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4504 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4505 CheckOrigin();
4506
4507 string message = "Hello World!";
4508 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4509 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4510}
4511
4512INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4513
4514auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004515 // IKeyMintDevice.aidl
4516 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4517 "020100" // INTEGER length 1 value 0x00 (version)
4518 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4519 "934bf94e2aa28a3f83c9f79297250262"
4520 "fbe3276b5a1c91159bbfa3ef8957aac8"
4521 "4b59b30b455a79c2973480823d8b3863"
4522 "c3deef4a8e243590268d80e18751a0e1"
4523 "30f67ce6a1ace9f79b95e097474febc9"
4524 "81195b1d13a69086c0863f66a7b7fdb4"
4525 "8792227b1ac5e2489febdf087ab54864"
4526 "83033a6f001ca5d1ec1e27f5c30f4cec"
4527 "2642074a39ae68aee552e196627a8e3d"
4528 "867e67a8c01b11e75f13cca0a97ab668"
4529 "b50cda07a8ecb7cd8e3dd7009c963653"
4530 "4f6f239cffe1fc8daa466f78b676c711"
4531 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4532 "99b801597d5220e307eaa5bee507fb94"
4533 "d1fa69f9e519b2de315bac92c36f2ea1"
4534 "fa1df4478c0ddedeae8c70e0233cd098"
4535 "040c" // OCTET STRING length 0x0c (initializationVector)
4536 "d796b02c370f1fa4cc0124f1"
4537 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4538 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4539 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4540 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4541 "3106" // SET length 0x06
4542 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4543 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4544 // } end SET
4545 // } end [1]
4546 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4547 "020120" // INTEGER length 1 value 0x20 (AES)
4548 // } end [2]
4549 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4550 "02020100" // INTEGER length 2 value 0x100
4551 // } end [3]
4552 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4553 "3103" // SET length 0x03 {
4554 "020101" // INTEGER length 1 value 0x01 (ECB)
4555 // } end SET
4556 // } end [4]
4557 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4558 "3103" // SET length 0x03 {
4559 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4560 // } end SET
4561 // } end [5]
4562 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4563 // (noAuthRequired)
4564 "0500" // NULL
4565 // } end [503]
4566 // } end SEQUENCE (AuthorizationList)
4567 // } end SEQUENCE (KeyDescription)
4568 "0420" // OCTET STRING length 0x20 (encryptedKey)
4569 "ccd540855f833a5e1480bfd2d36faf3a"
4570 "eee15df5beabe2691bc82dde2a7aa910"
4571 "0410" // OCTET STRING length 0x10 (tag)
4572 "64c9f689c60ff6223ab6e6999e0eb6e5"
4573 // } SEQUENCE (SecureKeyWrapper)
4574);
Selene Huang31ab4042020-04-29 04:22:39 -07004575
4576auto wrapped_key_masked = 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 "aad93ed5924f283b4bb5526fbe7a1412"
4582 "f9d9749ec30db9062b29e574a8546f33"
4583 "c88732452f5b8e6a391ee76c39ed1712"
4584 "c61d8df6213dec1cffbc17a8c6d04c7b"
4585 "30893d8daa9b2015213e219468215532"
4586 "07f8f9931c4caba23ed3bee28b36947e"
4587 "47f10e0a5c3dc51c988a628daad3e5e1"
4588 "f4005e79c2d5a96c284b4b8d7e4948f3"
4589 "31e5b85dd5a236f85579f3ea1d1b8484"
4590 "87470bdb0ab4f81a12bee42c99fe0df4"
4591 "bee3759453e69ad1d68a809ce06b949f"
4592 "7694a990429b2fe81e066ff43e56a216"
4593 "02db70757922a4bcc23ab89f1e35da77"
4594 "586775f423e519c2ea394caf48a28d0c"
4595 "8020f1dcf6b3a68ec246f615ae96dae9"
4596 "a079b1f6eb959033c1af5c125fd94168"
4597 "040c" // OCTET STRING length 0x0c (initializationVector)
4598 "6d9721d08589581ab49204a3"
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 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4632 "c20d1f99a9a024a76f35c8e2cab9b68d"
4633 "0410" // OCTET STRING length 0x10 (tag)
4634 "2560c70109ae67c030f00b98b512a670"
4635 // } SEQUENCE (SecureKeyWrapper)
4636);
Selene Huang31ab4042020-04-29 04:22:39 -07004637
4638auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004639 // RFC 5208 s5
4640 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4641 "020100" // INTEGER length 1 value 0x00 (version)
4642 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4643 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4644 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4645 "0500" // NULL (parameters)
4646 // } SEQUENCE (AlgorithmIdentifier)
4647 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4648 // RFC 8017 A.1.2
4649 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4650 "020100" // INTEGER length 1 value 0x00 (version)
4651 "02820101" // INTEGER length 0x0101 (modulus) value...
4652 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4653 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4654 "7b06e673a837313d56b1c725150a3fef" // 0x30
4655 "86acbddc41bb759c2854eae32d35841e" // 0x40
4656 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4657 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4658 "312d7bd5921ffaea1347c157406fef71" // 0x70
4659 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4660 "f4645c11f5c1374c3886427411c44979" // 0x90
4661 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4662 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4663 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4664 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4665 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4666 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4667 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4668 "55" // 0x101
4669 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4670 "02820100" // INTEGER length 0x100 (privateExponent) value...
4671 "431447b6251908112b1ee76f99f3711a" // 0x10
4672 "52b6630960046c2de70de188d833f8b8" // 0x20
4673 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4674 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4675 "e710b630a03adc683b5d2c43080e52be" // 0x50
4676 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4677 "822bccff087d63c940ba8a45f670feb2" // 0x70
4678 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4679 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4680 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4681 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4682 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4683 "52659d5a5ba05b663737a8696281865b" // 0xd0
4684 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4685 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4686 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4687 "028181" // INTEGER length 0x81 (prime1) value...
4688 "00de392e18d682c829266cc3454e1d61" // 0x10
4689 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4690 "ff841be5bac82a164c5970007047b8c5" // 0x30
4691 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4692 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4693 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4694 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4695 "9e91346130748a6e3c124f9149d71c74" // 0x80
4696 "35"
4697 "028181" // INTEGER length 0x81 (prime2) value...
4698 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4699 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4700 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4701 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4702 "9ed39a2d934c880440aed8832f984316" // 0x50
4703 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4704 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4705 "b880677c068e1be936e81288815252a8" // 0x80
4706 "a1"
4707 "028180" // INTEGER length 0x80 (exponent1) value...
4708 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4709 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4710 "5a063212a4f105a3764743e53281988a" // 0x30
4711 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4712 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4713 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4714 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4715 "4719d6e2b9439823719cd08bcd031781" // 0x80
4716 "028181" // INTEGER length 0x81 (exponent2) value...
4717 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4718 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4719 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4720 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4721 "1254186af30b22c10582a8a43e34fe94" // 0x50
4722 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4723 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4724 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4725 "61"
4726 "028181" // INTEGER length 0x81 (coefficient) value...
4727 "00c931617c77829dfb1270502be9195c" // 0x10
4728 "8f2830885f57dba869536811e6864236" // 0x20
4729 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4730 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4731 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4732 "959356210723287b0affcc9f727044d4" // 0x60
4733 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4734 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4735 "22"
4736 // } SEQUENCE
4737 // } SEQUENCE ()
4738);
Selene Huang31ab4042020-04-29 04:22:39 -07004739
4740string zero_masking_key =
4741 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4742string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4743
4744class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4745
4746TEST_P(ImportWrappedKeyTest, Success) {
4747 auto wrapping_key_desc = AuthorizationSetBuilder()
4748 .RsaEncryptionKey(2048, 65537)
4749 .Digest(Digest::SHA_2_256)
4750 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004751 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4752 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004753
4754 ASSERT_EQ(ErrorCode::OK,
4755 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4756 AuthorizationSetBuilder()
4757 .Digest(Digest::SHA_2_256)
4758 .Padding(PaddingMode::RSA_OAEP)));
4759
4760 string message = "Hello World!";
4761 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4762 string ciphertext = EncryptMessage(message, params);
4763 string plaintext = DecryptMessage(ciphertext, params);
4764 EXPECT_EQ(message, plaintext);
4765}
4766
David Drysdaled2cc8c22021-04-15 13:29:45 +01004767/*
4768 * ImportWrappedKeyTest.SuccessSidsIgnored
4769 *
4770 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
4771 * include Tag:USER_SECURE_ID.
4772 */
4773TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
4774 auto wrapping_key_desc = AuthorizationSetBuilder()
4775 .RsaEncryptionKey(2048, 65537)
4776 .Digest(Digest::SHA_2_256)
4777 .Padding(PaddingMode::RSA_OAEP)
4778 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4779 .SetDefaultValidity();
4780
4781 int64_t password_sid = 42;
4782 int64_t biometric_sid = 24;
4783 ASSERT_EQ(ErrorCode::OK,
4784 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4785 AuthorizationSetBuilder()
4786 .Digest(Digest::SHA_2_256)
4787 .Padding(PaddingMode::RSA_OAEP),
4788 password_sid, biometric_sid));
4789
4790 string message = "Hello World!";
4791 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4792 string ciphertext = EncryptMessage(message, params);
4793 string plaintext = DecryptMessage(ciphertext, params);
4794 EXPECT_EQ(message, plaintext);
4795}
4796
Selene Huang31ab4042020-04-29 04:22:39 -07004797TEST_P(ImportWrappedKeyTest, SuccessMasked) {
4798 auto wrapping_key_desc = AuthorizationSetBuilder()
4799 .RsaEncryptionKey(2048, 65537)
4800 .Digest(Digest::SHA_2_256)
4801 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004802 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4803 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004804
4805 ASSERT_EQ(ErrorCode::OK,
4806 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
4807 AuthorizationSetBuilder()
4808 .Digest(Digest::SHA_2_256)
4809 .Padding(PaddingMode::RSA_OAEP)));
4810}
4811
4812TEST_P(ImportWrappedKeyTest, WrongMask) {
4813 auto wrapping_key_desc = AuthorizationSetBuilder()
4814 .RsaEncryptionKey(2048, 65537)
4815 .Digest(Digest::SHA_2_256)
4816 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004817 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4818 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004819
4820 ASSERT_EQ(
4821 ErrorCode::VERIFICATION_FAILED,
4822 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4823 AuthorizationSetBuilder()
4824 .Digest(Digest::SHA_2_256)
4825 .Padding(PaddingMode::RSA_OAEP)));
4826}
4827
4828TEST_P(ImportWrappedKeyTest, WrongPurpose) {
4829 auto wrapping_key_desc = AuthorizationSetBuilder()
4830 .RsaEncryptionKey(2048, 65537)
4831 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004832 .Padding(PaddingMode::RSA_OAEP)
4833 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004834
4835 ASSERT_EQ(
4836 ErrorCode::INCOMPATIBLE_PURPOSE,
4837 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4838 AuthorizationSetBuilder()
4839 .Digest(Digest::SHA_2_256)
4840 .Padding(PaddingMode::RSA_OAEP)));
4841}
4842
David Drysdaled2cc8c22021-04-15 13:29:45 +01004843TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
4844 auto wrapping_key_desc = AuthorizationSetBuilder()
4845 .RsaEncryptionKey(2048, 65537)
4846 .Digest(Digest::SHA_2_256)
4847 .Padding(PaddingMode::RSA_PSS)
4848 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4849 .SetDefaultValidity();
4850
4851 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
4852 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4853 AuthorizationSetBuilder()
4854 .Digest(Digest::SHA_2_256)
4855 .Padding(PaddingMode::RSA_OAEP)));
4856}
4857
4858TEST_P(ImportWrappedKeyTest, WrongDigest) {
4859 auto wrapping_key_desc = AuthorizationSetBuilder()
4860 .RsaEncryptionKey(2048, 65537)
4861 .Digest(Digest::SHA_2_512)
4862 .Padding(PaddingMode::RSA_OAEP)
4863 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4864 .SetDefaultValidity();
4865
4866 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
4867 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4868 AuthorizationSetBuilder()
4869 .Digest(Digest::SHA_2_256)
4870 .Padding(PaddingMode::RSA_OAEP)));
4871}
4872
Selene Huang31ab4042020-04-29 04:22:39 -07004873INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
4874
4875typedef KeyMintAidlTestBase EncryptionOperationsTest;
4876
4877/*
4878 * EncryptionOperationsTest.RsaNoPaddingSuccess
4879 *
David Drysdale59cae642021-05-12 13:52:03 +01004880 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07004881 */
4882TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00004883 for (uint64_t exponent : ValidExponents()) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01004884 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4885 .Authorization(TAG_NO_AUTH_REQUIRED)
4886 .RsaEncryptionKey(2048, exponent)
4887 .Padding(PaddingMode::NONE)
4888 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004889
David Drysdaled2cc8c22021-04-15 13:29:45 +01004890 string message = string(2048 / 8, 'a');
4891 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004892 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004893 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004894
David Drysdale59cae642021-05-12 13:52:03 +01004895 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004896 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004897
David Drysdaled2cc8c22021-04-15 13:29:45 +01004898 // Unpadded RSA is deterministic
4899 EXPECT_EQ(ciphertext1, ciphertext2);
4900
4901 CheckedDeleteKey();
4902 }
Selene Huang31ab4042020-04-29 04:22:39 -07004903}
4904
4905/*
4906 * EncryptionOperationsTest.RsaNoPaddingShortMessage
4907 *
David Drysdale59cae642021-05-12 13:52:03 +01004908 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07004909 */
4910TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
4911 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4912 .Authorization(TAG_NO_AUTH_REQUIRED)
4913 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004914 .Padding(PaddingMode::NONE)
4915 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004916
4917 string message = "1";
4918 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4919
David Drysdale59cae642021-05-12 13:52:03 +01004920 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004921 EXPECT_EQ(2048U / 8, ciphertext.size());
4922
4923 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
4924 string plaintext = DecryptMessage(ciphertext, params);
4925
4926 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07004927}
4928
4929/*
Selene Huang31ab4042020-04-29 04:22:39 -07004930 * EncryptionOperationsTest.RsaOaepSuccess
4931 *
David Drysdale59cae642021-05-12 13:52:03 +01004932 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07004933 */
4934TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
4935 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4936
4937 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01004938 ASSERT_EQ(ErrorCode::OK,
4939 GenerateKey(AuthorizationSetBuilder()
4940 .Authorization(TAG_NO_AUTH_REQUIRED)
4941 .RsaEncryptionKey(key_size, 65537)
4942 .Padding(PaddingMode::RSA_OAEP)
4943 .Digest(digests)
4944 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
4945 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004946
4947 string message = "Hello";
4948
4949 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01004950 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4951
4952 auto params = AuthorizationSetBuilder()
4953 .Digest(digest)
4954 .Padding(PaddingMode::RSA_OAEP)
4955 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
4956 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004957 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4958 EXPECT_EQ(key_size / 8, ciphertext1.size());
4959
David Drysdale59cae642021-05-12 13:52:03 +01004960 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004961 EXPECT_EQ(key_size / 8, ciphertext2.size());
4962
4963 // OAEP randomizes padding so every result should be different (with astronomically high
4964 // probability).
4965 EXPECT_NE(ciphertext1, ciphertext2);
4966
4967 string plaintext1 = DecryptMessage(ciphertext1, params);
4968 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4969 string plaintext2 = DecryptMessage(ciphertext2, params);
4970 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4971
4972 // Decrypting corrupted ciphertext should fail.
4973 size_t offset_to_corrupt = random() % ciphertext1.size();
4974 char corrupt_byte;
4975 do {
4976 corrupt_byte = static_cast<char>(random() % 256);
4977 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4978 ciphertext1[offset_to_corrupt] = corrupt_byte;
4979
4980 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4981 string result;
4982 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4983 EXPECT_EQ(0U, result.size());
4984 }
4985}
4986
4987/*
4988 * EncryptionOperationsTest.RsaOaepInvalidDigest
4989 *
David Drysdale59cae642021-05-12 13:52:03 +01004990 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07004991 * without a digest.
4992 */
4993TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
4994 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4995 .Authorization(TAG_NO_AUTH_REQUIRED)
4996 .RsaEncryptionKey(2048, 65537)
4997 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004998 .Digest(Digest::NONE)
4999 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005000
5001 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005002 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005003}
5004
5005/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005006 * EncryptionOperationsTest.RsaOaepInvalidPadding
5007 *
David Drysdale59cae642021-05-12 13:52:03 +01005008 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005009 * with a padding value that is only suitable for signing/verifying.
5010 */
5011TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5012 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5013 .Authorization(TAG_NO_AUTH_REQUIRED)
5014 .RsaEncryptionKey(2048, 65537)
5015 .Padding(PaddingMode::RSA_PSS)
5016 .Digest(Digest::NONE)
5017 .SetDefaultValidity()));
5018
5019 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005020 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005021}
5022
5023/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005024 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005025 *
David Drysdale59cae642021-05-12 13:52:03 +01005026 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005027 * with a different digest than was used to encrypt.
5028 */
5029TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005030 if (SecLevel() == SecurityLevel::STRONGBOX) {
5031 GTEST_SKIP() << "Test not applicable to StrongBox device";
5032 }
Selene Huang31ab4042020-04-29 04:22:39 -07005033
5034 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5035 .Authorization(TAG_NO_AUTH_REQUIRED)
5036 .RsaEncryptionKey(1024, 65537)
5037 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005038 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5039 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005040 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005041 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005042 message,
5043 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5044
5045 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5046 .Digest(Digest::SHA_2_256)
5047 .Padding(PaddingMode::RSA_OAEP)));
5048 string result;
5049 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5050 EXPECT_EQ(0U, result.size());
5051}
5052
5053/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005054 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5055 *
David Drysdale59cae642021-05-12 13:52:03 +01005056 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005057 * digests.
5058 */
5059TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5060 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5061
5062 size_t key_size = 2048; // Need largish key for SHA-512 test.
5063 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5064 .OaepMGFDigest(digests)
5065 .Authorization(TAG_NO_AUTH_REQUIRED)
5066 .RsaEncryptionKey(key_size, 65537)
5067 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005068 .Digest(Digest::SHA_2_256)
5069 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005070
5071 string message = "Hello";
5072
5073 for (auto digest : digests) {
5074 auto params = AuthorizationSetBuilder()
5075 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5076 .Digest(Digest::SHA_2_256)
5077 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005078 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005079 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5080 EXPECT_EQ(key_size / 8, ciphertext1.size());
5081
David Drysdale59cae642021-05-12 13:52:03 +01005082 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005083 EXPECT_EQ(key_size / 8, ciphertext2.size());
5084
5085 // OAEP randomizes padding so every result should be different (with astronomically high
5086 // probability).
5087 EXPECT_NE(ciphertext1, ciphertext2);
5088
5089 string plaintext1 = DecryptMessage(ciphertext1, params);
5090 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5091 string plaintext2 = DecryptMessage(ciphertext2, params);
5092 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5093
5094 // Decrypting corrupted ciphertext should fail.
5095 size_t offset_to_corrupt = random() % ciphertext1.size();
5096 char corrupt_byte;
5097 do {
5098 corrupt_byte = static_cast<char>(random() % 256);
5099 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5100 ciphertext1[offset_to_corrupt] = corrupt_byte;
5101
5102 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5103 string result;
5104 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5105 EXPECT_EQ(0U, result.size());
5106 }
5107}
5108
5109/*
5110 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5111 *
David Drysdale59cae642021-05-12 13:52:03 +01005112 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005113 * with incompatible MGF digest.
5114 */
5115TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5116 ASSERT_EQ(ErrorCode::OK,
5117 GenerateKey(AuthorizationSetBuilder()
5118 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5119 .Authorization(TAG_NO_AUTH_REQUIRED)
5120 .RsaEncryptionKey(2048, 65537)
5121 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005122 .Digest(Digest::SHA_2_256)
5123 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005124 string message = "Hello World!";
5125
5126 auto params = AuthorizationSetBuilder()
5127 .Padding(PaddingMode::RSA_OAEP)
5128 .Digest(Digest::SHA_2_256)
5129 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005130 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005131}
5132
5133/*
5134 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5135 *
5136 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5137 * with unsupported MGF digest.
5138 */
5139TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5140 ASSERT_EQ(ErrorCode::OK,
5141 GenerateKey(AuthorizationSetBuilder()
5142 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5143 .Authorization(TAG_NO_AUTH_REQUIRED)
5144 .RsaEncryptionKey(2048, 65537)
5145 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005146 .Digest(Digest::SHA_2_256)
5147 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005148 string message = "Hello World!";
5149
5150 auto params = AuthorizationSetBuilder()
5151 .Padding(PaddingMode::RSA_OAEP)
5152 .Digest(Digest::SHA_2_256)
5153 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005154 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005155}
5156
5157/*
Selene Huang31ab4042020-04-29 04:22:39 -07005158 * EncryptionOperationsTest.RsaPkcs1Success
5159 *
5160 * Verifies that RSA PKCS encryption/decrypts works.
5161 */
5162TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5163 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5164 .Authorization(TAG_NO_AUTH_REQUIRED)
5165 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005166 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5167 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005168
5169 string message = "Hello World!";
5170 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005171 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005172 EXPECT_EQ(2048U / 8, ciphertext1.size());
5173
David Drysdale59cae642021-05-12 13:52:03 +01005174 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005175 EXPECT_EQ(2048U / 8, ciphertext2.size());
5176
5177 // PKCS1 v1.5 randomizes padding so every result should be different.
5178 EXPECT_NE(ciphertext1, ciphertext2);
5179
5180 string plaintext = DecryptMessage(ciphertext1, params);
5181 EXPECT_EQ(message, plaintext);
5182
5183 // Decrypting corrupted ciphertext should fail.
5184 size_t offset_to_corrupt = random() % ciphertext1.size();
5185 char corrupt_byte;
5186 do {
5187 corrupt_byte = static_cast<char>(random() % 256);
5188 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5189 ciphertext1[offset_to_corrupt] = corrupt_byte;
5190
5191 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5192 string result;
5193 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5194 EXPECT_EQ(0U, result.size());
5195}
5196
5197/*
Selene Huang31ab4042020-04-29 04:22:39 -07005198 * EncryptionOperationsTest.EcdsaEncrypt
5199 *
5200 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5201 */
5202TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5203 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5204 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005205 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005206 .Digest(Digest::NONE)
5207 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005208 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5209 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5210 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5211}
5212
5213/*
5214 * EncryptionOperationsTest.HmacEncrypt
5215 *
5216 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5217 */
5218TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5219 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5220 .Authorization(TAG_NO_AUTH_REQUIRED)
5221 .HmacKey(128)
5222 .Digest(Digest::SHA_2_256)
5223 .Padding(PaddingMode::NONE)
5224 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5225 auto params = AuthorizationSetBuilder()
5226 .Digest(Digest::SHA_2_256)
5227 .Padding(PaddingMode::NONE)
5228 .Authorization(TAG_MAC_LENGTH, 128);
5229 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5230 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5231}
5232
5233/*
5234 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5235 *
5236 * Verifies that AES ECB mode works.
5237 */
5238TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5239 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5240 .Authorization(TAG_NO_AUTH_REQUIRED)
5241 .AesEncryptionKey(128)
5242 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5243 .Padding(PaddingMode::NONE)));
5244
5245 ASSERT_GT(key_blob_.size(), 0U);
5246 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5247
5248 // Two-block message.
5249 string message = "12345678901234567890123456789012";
5250 string ciphertext1 = EncryptMessage(message, params);
5251 EXPECT_EQ(message.size(), ciphertext1.size());
5252
5253 string ciphertext2 = EncryptMessage(string(message), params);
5254 EXPECT_EQ(message.size(), ciphertext2.size());
5255
5256 // ECB is deterministic.
5257 EXPECT_EQ(ciphertext1, ciphertext2);
5258
5259 string plaintext = DecryptMessage(ciphertext1, params);
5260 EXPECT_EQ(message, plaintext);
5261}
5262
5263/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005264 * EncryptionOperationsTest.AesEcbUnknownTag
5265 *
5266 * Verifies that AES ECB operations ignore unknown tags.
5267 */
5268TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5269 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5270 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5271 KeyParameter unknown_param;
5272 unknown_param.tag = unknown_tag;
5273
5274 vector<KeyCharacteristics> key_characteristics;
5275 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5276 .Authorization(TAG_NO_AUTH_REQUIRED)
5277 .AesEncryptionKey(128)
5278 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5279 .Padding(PaddingMode::NONE)
5280 .Authorization(unknown_param),
5281 &key_blob_, &key_characteristics));
5282 ASSERT_GT(key_blob_.size(), 0U);
5283
5284 // Unknown tags should not be returned in key characteristics.
5285 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5286 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5287 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5288 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5289
5290 // Encrypt without mentioning the unknown parameter.
5291 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5292 string message = "12345678901234567890123456789012";
5293 string ciphertext = EncryptMessage(message, params);
5294 EXPECT_EQ(message.size(), ciphertext.size());
5295
5296 // Decrypt including the unknown parameter.
5297 auto decrypt_params = AuthorizationSetBuilder()
5298 .BlockMode(BlockMode::ECB)
5299 .Padding(PaddingMode::NONE)
5300 .Authorization(unknown_param);
5301 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5302 EXPECT_EQ(message, plaintext);
5303}
5304
5305/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005306 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005307 *
5308 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5309 */
5310TEST_P(EncryptionOperationsTest, AesWrongMode) {
5311 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5312 .Authorization(TAG_NO_AUTH_REQUIRED)
5313 .AesEncryptionKey(128)
5314 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5315 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005316 ASSERT_GT(key_blob_.size(), 0U);
5317
Selene Huang31ab4042020-04-29 04:22:39 -07005318 EXPECT_EQ(
5319 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5320 Begin(KeyPurpose::ENCRYPT,
5321 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5322}
5323
5324/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005325 * EncryptionOperationsTest.AesWrongPadding
5326 *
5327 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5328 */
5329TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5330 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5331 .Authorization(TAG_NO_AUTH_REQUIRED)
5332 .AesEncryptionKey(128)
5333 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5334 .Padding(PaddingMode::NONE)));
5335 ASSERT_GT(key_blob_.size(), 0U);
5336
5337 EXPECT_EQ(
5338 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5339 Begin(KeyPurpose::ENCRYPT,
5340 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5341}
5342
5343/*
5344 * EncryptionOperationsTest.AesInvalidParams
5345 *
5346 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5347 */
5348TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5349 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5350 .Authorization(TAG_NO_AUTH_REQUIRED)
5351 .AesEncryptionKey(128)
5352 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5353 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5354 .Padding(PaddingMode::NONE)
5355 .Padding(PaddingMode::PKCS7)));
5356 ASSERT_GT(key_blob_.size(), 0U);
5357
5358 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5359 .BlockMode(BlockMode::CBC)
5360 .BlockMode(BlockMode::ECB)
5361 .Padding(PaddingMode::NONE));
5362 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5363 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5364
5365 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5366 .BlockMode(BlockMode::ECB)
5367 .Padding(PaddingMode::NONE)
5368 .Padding(PaddingMode::PKCS7));
5369 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5370 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5371}
5372
5373/*
Selene Huang31ab4042020-04-29 04:22:39 -07005374 * EncryptionOperationsTest.AesWrongPurpose
5375 *
5376 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5377 * specified.
5378 */
5379TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5380 auto err = GenerateKey(AuthorizationSetBuilder()
5381 .Authorization(TAG_NO_AUTH_REQUIRED)
5382 .AesKey(128)
5383 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5384 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5385 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5386 .Padding(PaddingMode::NONE));
5387 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5388 ASSERT_GT(key_blob_.size(), 0U);
5389
5390 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5391 .BlockMode(BlockMode::GCM)
5392 .Padding(PaddingMode::NONE)
5393 .Authorization(TAG_MAC_LENGTH, 128));
5394 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5395
5396 CheckedDeleteKey();
5397
5398 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5399 .Authorization(TAG_NO_AUTH_REQUIRED)
5400 .AesKey(128)
5401 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5402 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5403 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5404 .Padding(PaddingMode::NONE)));
5405
5406 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5407 .BlockMode(BlockMode::GCM)
5408 .Padding(PaddingMode::NONE)
5409 .Authorization(TAG_MAC_LENGTH, 128));
5410 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5411}
5412
5413/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005414 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005415 *
5416 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5417 * multiple of the block size and no padding is specified.
5418 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005419TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5420 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5421 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5422 .Authorization(TAG_NO_AUTH_REQUIRED)
5423 .AesEncryptionKey(128)
5424 .Authorization(TAG_BLOCK_MODE, blockMode)
5425 .Padding(PaddingMode::NONE)));
5426 // Message is slightly shorter than two blocks.
5427 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005428
David Drysdaled2cc8c22021-04-15 13:29:45 +01005429 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5430 AuthorizationSet out_params;
5431 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5432 string ciphertext;
5433 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5434 EXPECT_EQ(0U, ciphertext.size());
5435
5436 CheckedDeleteKey();
5437 }
Selene Huang31ab4042020-04-29 04:22:39 -07005438}
5439
5440/*
5441 * EncryptionOperationsTest.AesEcbPkcs7Padding
5442 *
5443 * Verifies that AES PKCS7 padding works for any message length.
5444 */
5445TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5446 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5447 .Authorization(TAG_NO_AUTH_REQUIRED)
5448 .AesEncryptionKey(128)
5449 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5450 .Padding(PaddingMode::PKCS7)));
5451
5452 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5453
5454 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005455 for (size_t i = 0; i <= 48; i++) {
5456 SCOPED_TRACE(testing::Message() << "i = " << i);
5457 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5458 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005459 string ciphertext = EncryptMessage(message, params);
5460 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5461 string plaintext = DecryptMessage(ciphertext, params);
5462 EXPECT_EQ(message, plaintext);
5463 }
5464}
5465
5466/*
5467 * EncryptionOperationsTest.AesEcbWrongPadding
5468 *
5469 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5470 * specified.
5471 */
5472TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5473 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5474 .Authorization(TAG_NO_AUTH_REQUIRED)
5475 .AesEncryptionKey(128)
5476 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5477 .Padding(PaddingMode::NONE)));
5478
5479 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5480
5481 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005482 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005483 string message(i, 'a');
5484 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5485 }
5486}
5487
5488/*
5489 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5490 *
5491 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5492 */
5493TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5494 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5495 .Authorization(TAG_NO_AUTH_REQUIRED)
5496 .AesEncryptionKey(128)
5497 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5498 .Padding(PaddingMode::PKCS7)));
5499
5500 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5501
5502 string message = "a";
5503 string ciphertext = EncryptMessage(message, params);
5504 EXPECT_EQ(16U, ciphertext.size());
5505 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005506
Seth Moore7a55ae32021-06-23 14:28:11 -07005507 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5508 ++ciphertext[ciphertext.size() / 2];
5509
5510 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5511 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005512 ErrorCode error = Finish(ciphertext, &plaintext);
5513 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005514 // This is the expected error, we can exit the test now.
5515 return;
5516 } else {
5517 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005518 ASSERT_EQ(error, ErrorCode::OK)
5519 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005520 }
5521 }
5522 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005523}
5524
David Drysdaleb8093292022-04-08 12:22:35 +01005525/*
5526 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5527 *
5528 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5529 */
5530TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5531 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5532 .Authorization(TAG_NO_AUTH_REQUIRED)
5533 .AesEncryptionKey(128)
5534 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5535 .Padding(PaddingMode::PKCS7)));
5536
5537 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5538
5539 string message = "a";
5540 string ciphertext = EncryptMessage(message, params);
5541 EXPECT_EQ(16U, ciphertext.size());
5542 EXPECT_NE(ciphertext, message);
5543
5544 // Shorten the ciphertext.
5545 ciphertext.resize(ciphertext.size() - 1);
5546 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5547 string plaintext;
5548 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5549}
5550
Selene Huang31ab4042020-04-29 04:22:39 -07005551vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5552 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005553 EXPECT_TRUE(iv);
5554 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005555}
5556
5557/*
5558 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5559 *
5560 * Verifies that AES CTR mode works.
5561 */
5562TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5563 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5564 .Authorization(TAG_NO_AUTH_REQUIRED)
5565 .AesEncryptionKey(128)
5566 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5567 .Padding(PaddingMode::NONE)));
5568
5569 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5570
5571 string message = "123";
5572 AuthorizationSet out_params;
5573 string ciphertext1 = EncryptMessage(message, params, &out_params);
5574 vector<uint8_t> iv1 = CopyIv(out_params);
5575 EXPECT_EQ(16U, iv1.size());
5576
5577 EXPECT_EQ(message.size(), ciphertext1.size());
5578
5579 out_params.Clear();
5580 string ciphertext2 = EncryptMessage(message, params, &out_params);
5581 vector<uint8_t> iv2 = CopyIv(out_params);
5582 EXPECT_EQ(16U, iv2.size());
5583
5584 // IVs should be random, so ciphertexts should differ.
5585 EXPECT_NE(ciphertext1, ciphertext2);
5586
5587 auto params_iv1 =
5588 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5589 auto params_iv2 =
5590 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5591
5592 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5593 EXPECT_EQ(message, plaintext);
5594 plaintext = DecryptMessage(ciphertext2, params_iv2);
5595 EXPECT_EQ(message, plaintext);
5596
5597 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5598 plaintext = DecryptMessage(ciphertext1, params_iv2);
5599 EXPECT_NE(message, plaintext);
5600 plaintext = DecryptMessage(ciphertext2, params_iv1);
5601 EXPECT_NE(message, plaintext);
5602}
5603
5604/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305605 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07005606 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305607 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07005608 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305609TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5610 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5611}
Selene Huang31ab4042020-04-29 04:22:39 -07005612
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305613/*
5614 * EncryptionOperationsTest.AesCbcIncremental
5615 *
5616 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5617 */
5618TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5619 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5620}
Selene Huang31ab4042020-04-29 04:22:39 -07005621
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305622/*
5623 * EncryptionOperationsTest.AesCtrIncremental
5624 *
5625 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5626 */
5627TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5628 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5629}
Selene Huang31ab4042020-04-29 04:22:39 -07005630
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305631/*
5632 * EncryptionOperationsTest.AesGcmIncremental
5633 *
5634 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5635 */
5636TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5637 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07005638}
5639
5640struct AesCtrSp80038aTestVector {
5641 const char* key;
5642 const char* nonce;
5643 const char* plaintext;
5644 const char* ciphertext;
5645};
5646
5647// These test vectors are taken from
5648// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
5649static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
5650 // AES-128
5651 {
5652 "2b7e151628aed2a6abf7158809cf4f3c",
5653 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5654 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5655 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5656 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
5657 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
5658 },
5659 // AES-192
5660 {
5661 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
5662 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5663 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5664 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5665 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
5666 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
5667 },
5668 // AES-256
5669 {
5670 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
5671 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5672 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5673 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5674 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
5675 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
5676 },
5677};
5678
5679/*
5680 * EncryptionOperationsTest.AesCtrSp80038aTestVector
5681 *
5682 * Verifies AES CTR implementation against SP800-38A test vectors.
5683 */
5684TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
5685 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
5686 for (size_t i = 0; i < 3; i++) {
5687 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
5688 const string key = hex2str(test.key);
5689 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
5690 InvalidSizes.end())
5691 continue;
5692 const string nonce = hex2str(test.nonce);
5693 const string plaintext = hex2str(test.plaintext);
5694 const string ciphertext = hex2str(test.ciphertext);
5695 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
5696 }
5697}
5698
5699/*
5700 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
5701 *
5702 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
5703 */
5704TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
5705 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5706 .Authorization(TAG_NO_AUTH_REQUIRED)
5707 .AesEncryptionKey(128)
5708 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5709 .Padding(PaddingMode::PKCS7)));
5710 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5711 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5712}
5713
5714/*
5715 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
5716 *
5717 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5718 */
5719TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
5720 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5721 .Authorization(TAG_NO_AUTH_REQUIRED)
5722 .AesEncryptionKey(128)
5723 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5724 .Authorization(TAG_CALLER_NONCE)
5725 .Padding(PaddingMode::NONE)));
5726
5727 auto params = AuthorizationSetBuilder()
5728 .BlockMode(BlockMode::CTR)
5729 .Padding(PaddingMode::NONE)
5730 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
5731 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5732
5733 params = AuthorizationSetBuilder()
5734 .BlockMode(BlockMode::CTR)
5735 .Padding(PaddingMode::NONE)
5736 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
5737 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5738
5739 params = AuthorizationSetBuilder()
5740 .BlockMode(BlockMode::CTR)
5741 .Padding(PaddingMode::NONE)
5742 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
5743 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5744}
5745
5746/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005747 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07005748 *
5749 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5750 */
5751TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
5752 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5753 .Authorization(TAG_NO_AUTH_REQUIRED)
5754 .AesEncryptionKey(128)
5755 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5756 .Padding(PaddingMode::NONE)));
5757 // Two-block message.
5758 string message = "12345678901234567890123456789012";
5759 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5760 AuthorizationSet out_params;
5761 string ciphertext1 = EncryptMessage(message, params, &out_params);
5762 vector<uint8_t> iv1 = CopyIv(out_params);
5763 EXPECT_EQ(message.size(), ciphertext1.size());
5764
5765 out_params.Clear();
5766
5767 string ciphertext2 = EncryptMessage(message, params, &out_params);
5768 vector<uint8_t> iv2 = CopyIv(out_params);
5769 EXPECT_EQ(message.size(), ciphertext2.size());
5770
5771 // IVs should be random, so ciphertexts should differ.
5772 EXPECT_NE(ciphertext1, ciphertext2);
5773
5774 params.push_back(TAG_NONCE, iv1);
5775 string plaintext = DecryptMessage(ciphertext1, params);
5776 EXPECT_EQ(message, plaintext);
5777}
5778
5779/*
Tommy Chiuee705692021-09-23 20:09:13 +08005780 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
5781 *
5782 * Verifies that keymaster generates correct output on zero-input with
5783 * NonePadding mode
5784 */
5785TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
5786 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5787 .Authorization(TAG_NO_AUTH_REQUIRED)
5788 .AesEncryptionKey(128)
5789 .BlockMode(BlockMode::CBC)
5790 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
5791
5792 // Zero input message
5793 string message = "";
5794 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
5795 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
5796 AuthorizationSet out_params;
5797 string ciphertext1 = EncryptMessage(message, params, &out_params);
5798 vector<uint8_t> iv1 = CopyIv(out_params);
5799 if (padding == PaddingMode::NONE)
5800 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
5801 else
5802 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
5803
5804 out_params.Clear();
5805
5806 string ciphertext2 = EncryptMessage(message, params, &out_params);
5807 vector<uint8_t> iv2 = CopyIv(out_params);
5808 if (padding == PaddingMode::NONE)
5809 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
5810 else
5811 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
5812
5813 // IVs should be random
5814 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
5815
5816 params.push_back(TAG_NONCE, iv1);
5817 string plaintext = DecryptMessage(ciphertext1, params);
5818 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
5819 }
5820}
5821
5822/*
Selene Huang31ab4042020-04-29 04:22:39 -07005823 * EncryptionOperationsTest.AesCallerNonce
5824 *
5825 * Verifies that AES caller-provided nonces work correctly.
5826 */
5827TEST_P(EncryptionOperationsTest, AesCallerNonce) {
5828 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5829 .Authorization(TAG_NO_AUTH_REQUIRED)
5830 .AesEncryptionKey(128)
5831 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5832 .Authorization(TAG_CALLER_NONCE)
5833 .Padding(PaddingMode::NONE)));
5834
5835 string message = "12345678901234567890123456789012";
5836
5837 // Don't specify nonce, should get a random one.
5838 AuthorizationSetBuilder params =
5839 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5840 AuthorizationSet out_params;
5841 string ciphertext = EncryptMessage(message, params, &out_params);
5842 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005843 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005844
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005845 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005846 string plaintext = DecryptMessage(ciphertext, params);
5847 EXPECT_EQ(message, plaintext);
5848
5849 // Now specify a nonce, should also work.
5850 params = AuthorizationSetBuilder()
5851 .BlockMode(BlockMode::CBC)
5852 .Padding(PaddingMode::NONE)
5853 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5854 out_params.Clear();
5855 ciphertext = EncryptMessage(message, params, &out_params);
5856
5857 // Decrypt with correct nonce.
5858 plaintext = DecryptMessage(ciphertext, params);
5859 EXPECT_EQ(message, plaintext);
5860
5861 // Try with wrong nonce.
5862 params = AuthorizationSetBuilder()
5863 .BlockMode(BlockMode::CBC)
5864 .Padding(PaddingMode::NONE)
5865 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
5866 plaintext = DecryptMessage(ciphertext, params);
5867 EXPECT_NE(message, plaintext);
5868}
5869
5870/*
5871 * EncryptionOperationsTest.AesCallerNonceProhibited
5872 *
5873 * Verifies that caller-provided nonces are not permitted when not specified in the key
5874 * authorizations.
5875 */
5876TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
5877 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5878 .Authorization(TAG_NO_AUTH_REQUIRED)
5879 .AesEncryptionKey(128)
5880 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5881 .Padding(PaddingMode::NONE)));
5882
5883 string message = "12345678901234567890123456789012";
5884
5885 // Don't specify nonce, should get a random one.
5886 AuthorizationSetBuilder params =
5887 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5888 AuthorizationSet out_params;
5889 string ciphertext = EncryptMessage(message, params, &out_params);
5890 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005891 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005892
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005893 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005894 string plaintext = DecryptMessage(ciphertext, params);
5895 EXPECT_EQ(message, plaintext);
5896
5897 // Now specify a nonce, should fail
5898 params = AuthorizationSetBuilder()
5899 .BlockMode(BlockMode::CBC)
5900 .Padding(PaddingMode::NONE)
5901 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5902 out_params.Clear();
5903 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5904}
5905
5906/*
5907 * EncryptionOperationsTest.AesGcmRoundTripSuccess
5908 *
5909 * Verifies that AES GCM mode works.
5910 */
5911TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
5912 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5913 .Authorization(TAG_NO_AUTH_REQUIRED)
5914 .AesEncryptionKey(128)
5915 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5916 .Padding(PaddingMode::NONE)
5917 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5918
5919 string aad = "foobar";
5920 string message = "123456789012345678901234567890123456";
5921
5922 auto begin_params = AuthorizationSetBuilder()
5923 .BlockMode(BlockMode::GCM)
5924 .Padding(PaddingMode::NONE)
5925 .Authorization(TAG_MAC_LENGTH, 128);
5926
Selene Huang31ab4042020-04-29 04:22:39 -07005927 // Encrypt
5928 AuthorizationSet begin_out_params;
5929 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5930 << "Begin encrypt";
5931 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005932 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5933 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005934 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5935
5936 // Grab nonce
5937 begin_params.push_back(begin_out_params);
5938
5939 // Decrypt.
5940 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07005941 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005942 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005943 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005944 EXPECT_EQ(message.length(), plaintext.length());
5945 EXPECT_EQ(message, plaintext);
5946}
5947
5948/*
5949 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
5950 *
5951 * Verifies that AES GCM mode works, even when there's a long delay
5952 * between operations.
5953 */
5954TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
5955 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5956 .Authorization(TAG_NO_AUTH_REQUIRED)
5957 .AesEncryptionKey(128)
5958 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5959 .Padding(PaddingMode::NONE)
5960 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5961
5962 string aad = "foobar";
5963 string message = "123456789012345678901234567890123456";
5964
5965 auto begin_params = AuthorizationSetBuilder()
5966 .BlockMode(BlockMode::GCM)
5967 .Padding(PaddingMode::NONE)
5968 .Authorization(TAG_MAC_LENGTH, 128);
5969
Selene Huang31ab4042020-04-29 04:22:39 -07005970 // Encrypt
5971 AuthorizationSet begin_out_params;
5972 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5973 << "Begin encrypt";
5974 string ciphertext;
5975 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005976 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005977 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005978 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005979
5980 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5981
5982 // Grab nonce
5983 begin_params.push_back(begin_out_params);
5984
5985 // Decrypt.
5986 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
5987 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005988 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005989 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005990 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005991 sleep(5);
5992 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
5993 EXPECT_EQ(message.length(), plaintext.length());
5994 EXPECT_EQ(message, plaintext);
5995}
5996
5997/*
5998 * EncryptionOperationsTest.AesGcmDifferentNonces
5999 *
6000 * Verifies that encrypting the same data with different nonces produces different outputs.
6001 */
6002TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6003 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6004 .Authorization(TAG_NO_AUTH_REQUIRED)
6005 .AesEncryptionKey(128)
6006 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6007 .Padding(PaddingMode::NONE)
6008 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6009 .Authorization(TAG_CALLER_NONCE)));
6010
6011 string aad = "foobar";
6012 string message = "123456789012345678901234567890123456";
6013 string nonce1 = "000000000000";
6014 string nonce2 = "111111111111";
6015 string nonce3 = "222222222222";
6016
6017 string ciphertext1 =
6018 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6019 string ciphertext2 =
6020 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6021 string ciphertext3 =
6022 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6023
6024 ASSERT_NE(ciphertext1, ciphertext2);
6025 ASSERT_NE(ciphertext1, ciphertext3);
6026 ASSERT_NE(ciphertext2, ciphertext3);
6027}
6028
6029/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006030 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6031 *
6032 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6033 */
6034TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6035 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6036 .Authorization(TAG_NO_AUTH_REQUIRED)
6037 .AesEncryptionKey(128)
6038 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6039 .Padding(PaddingMode::NONE)
6040 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6041
6042 string aad = "foobar";
6043 string message = "123456789012345678901234567890123456";
6044
6045 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6046 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6047 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6048
6049 ASSERT_NE(ciphertext1, ciphertext2);
6050 ASSERT_NE(ciphertext1, ciphertext3);
6051 ASSERT_NE(ciphertext2, ciphertext3);
6052}
6053
6054/*
Selene Huang31ab4042020-04-29 04:22:39 -07006055 * EncryptionOperationsTest.AesGcmTooShortTag
6056 *
6057 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6058 */
6059TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6060 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6061 .Authorization(TAG_NO_AUTH_REQUIRED)
6062 .AesEncryptionKey(128)
6063 .BlockMode(BlockMode::GCM)
6064 .Padding(PaddingMode::NONE)
6065 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6066 string message = "123456789012345678901234567890123456";
6067 auto params = AuthorizationSetBuilder()
6068 .BlockMode(BlockMode::GCM)
6069 .Padding(PaddingMode::NONE)
6070 .Authorization(TAG_MAC_LENGTH, 96);
6071
6072 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6073}
6074
6075/*
6076 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6077 *
6078 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6079 */
6080TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6081 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6082 .Authorization(TAG_NO_AUTH_REQUIRED)
6083 .AesEncryptionKey(128)
6084 .BlockMode(BlockMode::GCM)
6085 .Padding(PaddingMode::NONE)
6086 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6087 string aad = "foobar";
6088 string message = "123456789012345678901234567890123456";
6089 auto params = AuthorizationSetBuilder()
6090 .BlockMode(BlockMode::GCM)
6091 .Padding(PaddingMode::NONE)
6092 .Authorization(TAG_MAC_LENGTH, 128);
6093
Selene Huang31ab4042020-04-29 04:22:39 -07006094 // Encrypt
6095 AuthorizationSet begin_out_params;
6096 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6097 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006098 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006099
6100 AuthorizationSet finish_out_params;
6101 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006102 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6103 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006104
6105 params = AuthorizationSetBuilder()
6106 .Authorizations(begin_out_params)
6107 .BlockMode(BlockMode::GCM)
6108 .Padding(PaddingMode::NONE)
6109 .Authorization(TAG_MAC_LENGTH, 96);
6110
6111 // Decrypt.
6112 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6113}
6114
6115/*
6116 * EncryptionOperationsTest.AesGcmCorruptKey
6117 *
6118 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6119 */
6120TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6121 const uint8_t nonce_bytes[] = {
6122 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6123 };
6124 string nonce = make_string(nonce_bytes);
6125 const uint8_t ciphertext_bytes[] = {
6126 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6127 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6128 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6129 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6130 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6131 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6132 };
6133 string ciphertext = make_string(ciphertext_bytes);
6134
6135 auto params = AuthorizationSetBuilder()
6136 .BlockMode(BlockMode::GCM)
6137 .Padding(PaddingMode::NONE)
6138 .Authorization(TAG_MAC_LENGTH, 128)
6139 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6140
6141 auto import_params = AuthorizationSetBuilder()
6142 .Authorization(TAG_NO_AUTH_REQUIRED)
6143 .AesEncryptionKey(128)
6144 .BlockMode(BlockMode::GCM)
6145 .Padding(PaddingMode::NONE)
6146 .Authorization(TAG_CALLER_NONCE)
6147 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6148
6149 // Import correct key and decrypt
6150 const uint8_t key_bytes[] = {
6151 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6152 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6153 };
6154 string key = make_string(key_bytes);
6155 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6156 string plaintext = DecryptMessage(ciphertext, params);
6157 CheckedDeleteKey();
6158
6159 // Corrupt key and attempt to decrypt
6160 key[0] = 0;
6161 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6162 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6163 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6164 CheckedDeleteKey();
6165}
6166
6167/*
6168 * EncryptionOperationsTest.AesGcmAadNoData
6169 *
6170 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6171 * encrypt.
6172 */
6173TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6174 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6175 .Authorization(TAG_NO_AUTH_REQUIRED)
6176 .AesEncryptionKey(128)
6177 .BlockMode(BlockMode::GCM)
6178 .Padding(PaddingMode::NONE)
6179 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6180
6181 string aad = "1234567890123456";
6182 auto params = AuthorizationSetBuilder()
6183 .BlockMode(BlockMode::GCM)
6184 .Padding(PaddingMode::NONE)
6185 .Authorization(TAG_MAC_LENGTH, 128);
6186
Selene Huang31ab4042020-04-29 04:22:39 -07006187 // Encrypt
6188 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006189 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006190 string ciphertext;
6191 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006192 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6193 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006194 EXPECT_TRUE(finish_out_params.empty());
6195
6196 // Grab nonce
6197 params.push_back(begin_out_params);
6198
6199 // Decrypt.
6200 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006201 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006202 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006203 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006204
6205 EXPECT_TRUE(finish_out_params.empty());
6206
6207 EXPECT_EQ("", plaintext);
6208}
6209
6210/*
6211 * EncryptionOperationsTest.AesGcmMultiPartAad
6212 *
6213 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6214 * chunks.
6215 */
6216TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6217 const size_t tag_bits = 128;
6218 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6219 .Authorization(TAG_NO_AUTH_REQUIRED)
6220 .AesEncryptionKey(128)
6221 .BlockMode(BlockMode::GCM)
6222 .Padding(PaddingMode::NONE)
6223 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6224
6225 string message = "123456789012345678901234567890123456";
6226 auto begin_params = AuthorizationSetBuilder()
6227 .BlockMode(BlockMode::GCM)
6228 .Padding(PaddingMode::NONE)
6229 .Authorization(TAG_MAC_LENGTH, tag_bits);
6230 AuthorizationSet begin_out_params;
6231
David Drysdale7fc26b92022-05-13 09:54:24 +01006232 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006233
6234 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006235 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6236 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006237 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006238 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6239 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006240
Selene Huang31ab4042020-04-29 04:22:39 -07006241 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006242 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006243
6244 // Grab nonce.
6245 begin_params.push_back(begin_out_params);
6246
6247 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01006248 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006249 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006250 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006251 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006252 EXPECT_EQ(message, plaintext);
6253}
6254
6255/*
6256 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6257 *
6258 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6259 */
6260TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6261 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6262 .Authorization(TAG_NO_AUTH_REQUIRED)
6263 .AesEncryptionKey(128)
6264 .BlockMode(BlockMode::GCM)
6265 .Padding(PaddingMode::NONE)
6266 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6267
6268 string message = "123456789012345678901234567890123456";
6269 auto begin_params = AuthorizationSetBuilder()
6270 .BlockMode(BlockMode::GCM)
6271 .Padding(PaddingMode::NONE)
6272 .Authorization(TAG_MAC_LENGTH, 128);
6273 AuthorizationSet begin_out_params;
6274
David Drysdale7fc26b92022-05-13 09:54:24 +01006275 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006276
Shawn Willden92d79c02021-02-19 07:31:55 -07006277 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006278 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006279 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6280 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006281
David Drysdaled2cc8c22021-04-15 13:29:45 +01006282 // The failure should have already cancelled the operation.
6283 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6284
Shawn Willden92d79c02021-02-19 07:31:55 -07006285 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006286}
6287
6288/*
6289 * EncryptionOperationsTest.AesGcmBadAad
6290 *
6291 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6292 */
6293TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6294 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6295 .Authorization(TAG_NO_AUTH_REQUIRED)
6296 .AesEncryptionKey(128)
6297 .BlockMode(BlockMode::GCM)
6298 .Padding(PaddingMode::NONE)
6299 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6300
6301 string message = "12345678901234567890123456789012";
6302 auto begin_params = AuthorizationSetBuilder()
6303 .BlockMode(BlockMode::GCM)
6304 .Padding(PaddingMode::NONE)
6305 .Authorization(TAG_MAC_LENGTH, 128);
6306
Selene Huang31ab4042020-04-29 04:22:39 -07006307 // Encrypt
6308 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006309 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006310 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006311 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006312 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006313
6314 // Grab nonce
6315 begin_params.push_back(begin_out_params);
6316
Selene Huang31ab4042020-04-29 04:22:39 -07006317 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006318 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006319 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006320 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006321 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006322}
6323
6324/*
6325 * EncryptionOperationsTest.AesGcmWrongNonce
6326 *
6327 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6328 */
6329TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6330 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6331 .Authorization(TAG_NO_AUTH_REQUIRED)
6332 .AesEncryptionKey(128)
6333 .BlockMode(BlockMode::GCM)
6334 .Padding(PaddingMode::NONE)
6335 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6336
6337 string message = "12345678901234567890123456789012";
6338 auto begin_params = AuthorizationSetBuilder()
6339 .BlockMode(BlockMode::GCM)
6340 .Padding(PaddingMode::NONE)
6341 .Authorization(TAG_MAC_LENGTH, 128);
6342
Selene Huang31ab4042020-04-29 04:22:39 -07006343 // Encrypt
6344 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006345 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006346 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006347 string ciphertext;
6348 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006349 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006350
6351 // Wrong nonce
6352 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6353
6354 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006355 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006356 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006357 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006358 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006359
6360 // With wrong nonce, should have gotten garbage plaintext (or none).
6361 EXPECT_NE(message, plaintext);
6362}
6363
6364/*
6365 * EncryptionOperationsTest.AesGcmCorruptTag
6366 *
6367 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6368 */
6369TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6370 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6371 .Authorization(TAG_NO_AUTH_REQUIRED)
6372 .AesEncryptionKey(128)
6373 .BlockMode(BlockMode::GCM)
6374 .Padding(PaddingMode::NONE)
6375 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6376
6377 string aad = "1234567890123456";
6378 string message = "123456789012345678901234567890123456";
6379
6380 auto params = AuthorizationSetBuilder()
6381 .BlockMode(BlockMode::GCM)
6382 .Padding(PaddingMode::NONE)
6383 .Authorization(TAG_MAC_LENGTH, 128);
6384
Selene Huang31ab4042020-04-29 04:22:39 -07006385 // Encrypt
6386 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006387 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006388 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006389 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006390 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006391
6392 // Corrupt tag
6393 ++(*ciphertext.rbegin());
6394
6395 // Grab nonce
6396 params.push_back(begin_out_params);
6397
6398 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006399 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006400 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006401 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006402 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006403}
6404
6405/*
6406 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
6407 *
6408 * Verifies that 3DES is basically functional.
6409 */
6410TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
6411 auto auths = AuthorizationSetBuilder()
6412 .TripleDesEncryptionKey(168)
6413 .BlockMode(BlockMode::ECB)
6414 .Authorization(TAG_NO_AUTH_REQUIRED)
6415 .Padding(PaddingMode::NONE);
6416
6417 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
6418 // Two-block message.
6419 string message = "1234567890123456";
6420 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6421 string ciphertext1 = EncryptMessage(message, inParams);
6422 EXPECT_EQ(message.size(), ciphertext1.size());
6423
6424 string ciphertext2 = EncryptMessage(string(message), inParams);
6425 EXPECT_EQ(message.size(), ciphertext2.size());
6426
6427 // ECB is deterministic.
6428 EXPECT_EQ(ciphertext1, ciphertext2);
6429
6430 string plaintext = DecryptMessage(ciphertext1, inParams);
6431 EXPECT_EQ(message, plaintext);
6432}
6433
6434/*
6435 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
6436 *
6437 * Verifies that CBC keys reject ECB usage.
6438 */
6439TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
6440 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6441 .TripleDesEncryptionKey(168)
6442 .BlockMode(BlockMode::CBC)
6443 .Authorization(TAG_NO_AUTH_REQUIRED)
6444 .Padding(PaddingMode::NONE)));
6445
6446 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6447 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
6448}
6449
6450/*
6451 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
6452 *
6453 * Tests ECB mode with PKCS#7 padding, various message sizes.
6454 */
6455TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
6456 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6457 .TripleDesEncryptionKey(168)
6458 .BlockMode(BlockMode::ECB)
6459 .Authorization(TAG_NO_AUTH_REQUIRED)
6460 .Padding(PaddingMode::PKCS7)));
6461
6462 for (size_t i = 0; i < 32; ++i) {
6463 string message(i, 'a');
6464 auto inParams =
6465 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6466 string ciphertext = EncryptMessage(message, inParams);
6467 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6468 string plaintext = DecryptMessage(ciphertext, inParams);
6469 EXPECT_EQ(message, plaintext);
6470 }
6471}
6472
6473/*
6474 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
6475 *
6476 * Verifies that keys configured for no padding reject PKCS7 padding
6477 */
6478TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
6479 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6480 .TripleDesEncryptionKey(168)
6481 .BlockMode(BlockMode::ECB)
6482 .Authorization(TAG_NO_AUTH_REQUIRED)
6483 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00006484 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6485 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07006486}
6487
6488/*
6489 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
6490 *
6491 * Verifies that corrupted padding is detected.
6492 */
6493TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
6494 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6495 .TripleDesEncryptionKey(168)
6496 .BlockMode(BlockMode::ECB)
6497 .Authorization(TAG_NO_AUTH_REQUIRED)
6498 .Padding(PaddingMode::PKCS7)));
6499
6500 string message = "a";
6501 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
6502 EXPECT_EQ(8U, ciphertext.size());
6503 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006504
6505 AuthorizationSetBuilder begin_params;
6506 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
6507 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07006508
6509 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
6510 ++ciphertext[ciphertext.size() / 2];
6511
David Drysdale7fc26b92022-05-13 09:54:24 +01006512 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07006513 string plaintext;
6514 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6515 ErrorCode error = Finish(&plaintext);
6516 if (error == ErrorCode::INVALID_ARGUMENT) {
6517 // This is the expected error, we can exit the test now.
6518 return;
6519 } else {
6520 // Very small chance we got valid decryption, so try again.
6521 ASSERT_EQ(error, ErrorCode::OK);
6522 }
6523 }
6524 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006525}
6526
6527struct TripleDesTestVector {
6528 const char* name;
6529 const KeyPurpose purpose;
6530 const BlockMode block_mode;
6531 const PaddingMode padding_mode;
6532 const char* key;
6533 const char* iv;
6534 const char* input;
6535 const char* output;
6536};
6537
6538// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
6539// of the NIST vectors are multiples of the block size.
6540static const TripleDesTestVector kTripleDesTestVectors[] = {
6541 {
6542 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6543 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
6544 "", // IV
6545 "329d86bdf1bc5af4", // input
6546 "d946c2756d78633f", // output
6547 },
6548 {
6549 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6550 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
6551 "", // IV
6552 "6b1540781b01ce1997adae102dbf3c5b", // input
6553 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
6554 },
6555 {
6556 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6557 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
6558 "", // IV
6559 "6daad94ce08acfe7", // input
6560 "660e7d32dcc90e79", // output
6561 },
6562 {
6563 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6564 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
6565 "", // IV
6566 "e9653a0a1f05d31b9acd12d73aa9879d", // input
6567 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
6568 },
6569 {
6570 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6571 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
6572 "43f791134c5647ba", // IV
6573 "dcc153cef81d6f24", // input
6574 "92538bd8af18d3ba", // output
6575 },
6576 {
6577 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6578 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6579 "c2e999cb6249023c", // IV
6580 "c689aee38a301bb316da75db36f110b5", // input
6581 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
6582 },
6583 {
6584 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
6585 PaddingMode::PKCS7,
6586 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6587 "c2e999cb6249023c", // IV
6588 "c689aee38a301bb316da75db36f110b500", // input
6589 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
6590 },
6591 {
6592 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
6593 PaddingMode::PKCS7,
6594 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6595 "c2e999cb6249023c", // IV
6596 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
6597 "c689aee38a301bb316da75db36f110b500", // output
6598 },
6599 {
6600 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6601 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
6602 "41746c7e442d3681", // IV
6603 "c53a7b0ec40600fe", // input
6604 "d4f00eb455de1034", // output
6605 },
6606 {
6607 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6608 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
6609 "3982bc02c3727d45", // IV
6610 "6006f10adef52991fcc777a1238bbb65", // input
6611 "edae09288e9e3bc05746d872b48e3b29", // output
6612 },
6613};
6614
6615/*
6616 * EncryptionOperationsTest.TripleDesTestVector
6617 *
6618 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
6619 */
6620TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
6621 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
6622 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
6623 SCOPED_TRACE(test->name);
6624 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
6625 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
6626 hex2str(test->output));
6627 }
6628}
6629
6630/*
6631 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
6632 *
6633 * Validates CBC mode functionality.
6634 */
6635TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
6636 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6637 .TripleDesEncryptionKey(168)
6638 .BlockMode(BlockMode::CBC)
6639 .Authorization(TAG_NO_AUTH_REQUIRED)
6640 .Padding(PaddingMode::NONE)));
6641
6642 ASSERT_GT(key_blob_.size(), 0U);
6643
Brian J Murray734c8412022-01-13 14:55:30 -08006644 // Four-block message.
6645 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07006646 vector<uint8_t> iv1;
6647 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
6648 EXPECT_EQ(message.size(), ciphertext1.size());
6649
6650 vector<uint8_t> iv2;
6651 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
6652 EXPECT_EQ(message.size(), ciphertext2.size());
6653
6654 // IVs should be random, so ciphertexts should differ.
6655 EXPECT_NE(iv1, iv2);
6656 EXPECT_NE(ciphertext1, ciphertext2);
6657
6658 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
6659 EXPECT_EQ(message, plaintext);
6660}
6661
6662/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006663 * EncryptionOperationsTest.TripleDesInvalidCallerIv
6664 *
6665 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
6666 */
6667TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
6668 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6669 .TripleDesEncryptionKey(168)
6670 .BlockMode(BlockMode::CBC)
6671 .Authorization(TAG_NO_AUTH_REQUIRED)
6672 .Authorization(TAG_CALLER_NONCE)
6673 .Padding(PaddingMode::NONE)));
6674 auto params = AuthorizationSetBuilder()
6675 .BlockMode(BlockMode::CBC)
6676 .Padding(PaddingMode::NONE)
6677 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
6678 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6679}
6680
6681/*
Selene Huang31ab4042020-04-29 04:22:39 -07006682 * EncryptionOperationsTest.TripleDesCallerIv
6683 *
6684 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
6685 */
6686TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
6687 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6688 .TripleDesEncryptionKey(168)
6689 .BlockMode(BlockMode::CBC)
6690 .Authorization(TAG_NO_AUTH_REQUIRED)
6691 .Authorization(TAG_CALLER_NONCE)
6692 .Padding(PaddingMode::NONE)));
6693 string message = "1234567890123456";
6694 vector<uint8_t> iv;
6695 // Don't specify IV, should get a random one.
6696 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6697 EXPECT_EQ(message.size(), ciphertext1.size());
6698 EXPECT_EQ(8U, iv.size());
6699
6700 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6701 EXPECT_EQ(message, plaintext);
6702
6703 // Now specify an IV, should also work.
6704 iv = AidlBuf("abcdefgh");
6705 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
6706
6707 // Decrypt with correct IV.
6708 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
6709 EXPECT_EQ(message, plaintext);
6710
6711 // Now try with wrong IV.
6712 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
6713 EXPECT_NE(message, plaintext);
6714}
6715
6716/*
6717 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
6718 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01006719 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07006720 */
6721TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
6722 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6723 .TripleDesEncryptionKey(168)
6724 .BlockMode(BlockMode::CBC)
6725 .Authorization(TAG_NO_AUTH_REQUIRED)
6726 .Padding(PaddingMode::NONE)));
6727
6728 string message = "12345678901234567890123456789012";
6729 vector<uint8_t> iv;
6730 // Don't specify nonce, should get a random one.
6731 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6732 EXPECT_EQ(message.size(), ciphertext1.size());
6733 EXPECT_EQ(8U, iv.size());
6734
6735 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6736 EXPECT_EQ(message, plaintext);
6737
6738 // Now specify a nonce, should fail.
6739 auto input_params = AuthorizationSetBuilder()
6740 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
6741 .BlockMode(BlockMode::CBC)
6742 .Padding(PaddingMode::NONE);
6743 AuthorizationSet output_params;
6744 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
6745 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6746}
6747
6748/*
6749 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
6750 *
6751 * Verifies that 3DES ECB-only keys do not allow CBC usage.
6752 */
6753TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
6754 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6755 .TripleDesEncryptionKey(168)
6756 .BlockMode(BlockMode::ECB)
6757 .Authorization(TAG_NO_AUTH_REQUIRED)
6758 .Padding(PaddingMode::NONE)));
6759 // Two-block message.
6760 string message = "1234567890123456";
6761 auto begin_params =
6762 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6763 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6764}
6765
6766/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006767 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07006768 *
6769 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
6770 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01006771TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
6772 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
6773 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6774 .TripleDesEncryptionKey(168)
6775 .BlockMode(blockMode)
6776 .Authorization(TAG_NO_AUTH_REQUIRED)
6777 .Padding(PaddingMode::NONE)));
6778 // Message is slightly shorter than two blocks.
6779 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07006780
David Drysdaled2cc8c22021-04-15 13:29:45 +01006781 auto begin_params =
6782 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
6783 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006784 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01006785 string ciphertext;
6786 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
6787
6788 CheckedDeleteKey();
6789 }
Selene Huang31ab4042020-04-29 04:22:39 -07006790}
6791
6792/*
6793 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
6794 *
6795 * Verifies that PKCS7 padding works correctly in CBC mode.
6796 */
6797TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
6798 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6799 .TripleDesEncryptionKey(168)
6800 .BlockMode(BlockMode::CBC)
6801 .Authorization(TAG_NO_AUTH_REQUIRED)
6802 .Padding(PaddingMode::PKCS7)));
6803
6804 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08006805 for (size_t i = 0; i <= 32; i++) {
6806 SCOPED_TRACE(testing::Message() << "i = " << i);
6807 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
6808 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07006809 vector<uint8_t> iv;
6810 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6811 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6812 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
6813 EXPECT_EQ(message, plaintext);
6814 }
6815}
6816
6817/*
6818 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
6819 *
6820 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
6821 */
6822TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
6823 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6824 .TripleDesEncryptionKey(168)
6825 .BlockMode(BlockMode::CBC)
6826 .Authorization(TAG_NO_AUTH_REQUIRED)
6827 .Padding(PaddingMode::NONE)));
6828
6829 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08006830 for (size_t i = 0; i <= 32; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07006831 auto begin_params =
6832 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
6833 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6834 }
6835}
6836
6837/*
6838 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
6839 *
6840 * Verifies that corrupted PKCS7 padding is rejected during decryption.
6841 */
6842TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
6843 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6844 .TripleDesEncryptionKey(168)
6845 .BlockMode(BlockMode::CBC)
6846 .Authorization(TAG_NO_AUTH_REQUIRED)
6847 .Padding(PaddingMode::PKCS7)));
6848
6849 string message = "a";
6850 vector<uint8_t> iv;
6851 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6852 EXPECT_EQ(8U, ciphertext.size());
6853 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006854
6855 auto begin_params = AuthorizationSetBuilder()
6856 .BlockMode(BlockMode::CBC)
6857 .Padding(PaddingMode::PKCS7)
6858 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07006859
6860 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08006861 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07006862 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01006863 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07006864 string plaintext;
6865 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6866 ErrorCode error = Finish(&plaintext);
6867 if (error == ErrorCode::INVALID_ARGUMENT) {
6868 // This is the expected error, we can exit the test now.
6869 return;
6870 } else {
6871 // Very small chance we got valid decryption, so try again.
6872 ASSERT_EQ(error, ErrorCode::OK);
6873 }
6874 }
6875 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006876}
6877
6878/*
6879 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
6880 *
6881 * Verifies that 3DES CBC works with many different input sizes.
6882 */
6883TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
6884 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6885 .TripleDesEncryptionKey(168)
6886 .BlockMode(BlockMode::CBC)
6887 .Authorization(TAG_NO_AUTH_REQUIRED)
6888 .Padding(PaddingMode::NONE)));
6889
6890 int increment = 7;
6891 string message(240, 'a');
6892 AuthorizationSet input_params =
6893 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6894 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006895 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006896
6897 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07006898 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006899 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006900 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
6901 EXPECT_EQ(message.size(), ciphertext.size());
6902
6903 // Move TAG_NONCE into input_params
6904 input_params = output_params;
6905 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
6906 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
6907 output_params.Clear();
6908
David Drysdale7fc26b92022-05-13 09:54:24 +01006909 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006910 string plaintext;
6911 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006912 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006913 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
6914 EXPECT_EQ(ciphertext.size(), plaintext.size());
6915 EXPECT_EQ(message, plaintext);
6916}
6917
6918INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
6919
6920typedef KeyMintAidlTestBase MaxOperationsTest;
6921
6922/*
6923 * MaxOperationsTest.TestLimitAes
6924 *
6925 * Verifies that the max uses per boot tag works correctly with AES keys.
6926 */
6927TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006928 if (SecLevel() == SecurityLevel::STRONGBOX) {
6929 GTEST_SKIP() << "Test not applicable to StrongBox device";
6930 }
Selene Huang31ab4042020-04-29 04:22:39 -07006931
6932 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6933 .Authorization(TAG_NO_AUTH_REQUIRED)
6934 .AesEncryptionKey(128)
6935 .EcbMode()
6936 .Padding(PaddingMode::NONE)
6937 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
6938
6939 string message = "1234567890123456";
6940
6941 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6942
6943 EncryptMessage(message, params);
6944 EncryptMessage(message, params);
6945 EncryptMessage(message, params);
6946
6947 // Fourth time should fail.
6948 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
6949}
6950
6951/*
Qi Wud22ec842020-11-26 13:27:53 +08006952 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07006953 *
6954 * Verifies that the max uses per boot tag works correctly with RSA keys.
6955 */
6956TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006957 if (SecLevel() == SecurityLevel::STRONGBOX) {
6958 GTEST_SKIP() << "Test not applicable to StrongBox device";
6959 }
Selene Huang31ab4042020-04-29 04:22:39 -07006960
6961 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6962 .Authorization(TAG_NO_AUTH_REQUIRED)
6963 .RsaSigningKey(1024, 65537)
6964 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006965 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
6966 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006967
6968 string message = "1234567890123456";
6969
6970 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6971
6972 SignMessage(message, params);
6973 SignMessage(message, params);
6974 SignMessage(message, params);
6975
6976 // Fourth time should fail.
6977 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
6978}
6979
6980INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
6981
Qi Wud22ec842020-11-26 13:27:53 +08006982typedef KeyMintAidlTestBase UsageCountLimitTest;
6983
6984/*
Qi Wubeefae42021-01-28 23:16:37 +08006985 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006986 *
Qi Wubeefae42021-01-28 23:16:37 +08006987 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006988 */
Qi Wubeefae42021-01-28 23:16:37 +08006989TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006990 if (SecLevel() == SecurityLevel::STRONGBOX) {
6991 GTEST_SKIP() << "Test not applicable to StrongBox device";
6992 }
Qi Wud22ec842020-11-26 13:27:53 +08006993
6994 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6995 .Authorization(TAG_NO_AUTH_REQUIRED)
6996 .AesEncryptionKey(128)
6997 .EcbMode()
6998 .Padding(PaddingMode::NONE)
6999 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7000
7001 // Check the usage count limit tag appears in the authorizations.
7002 AuthorizationSet auths;
7003 for (auto& entry : key_characteristics_) {
7004 auths.push_back(AuthorizationSet(entry.authorizations));
7005 }
7006 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7007 << "key usage count limit " << 1U << " missing";
7008
7009 string message = "1234567890123456";
7010 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7011
Qi Wubeefae42021-01-28 23:16:37 +08007012 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7013 AuthorizationSet keystore_auths =
7014 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7015
Qi Wud22ec842020-11-26 13:27:53 +08007016 // First usage of AES key should work.
7017 EncryptMessage(message, params);
7018
Qi Wud22ec842020-11-26 13:27:53 +08007019 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7020 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7021 // must be invalidated from secure storage (such as RPMB partition).
7022 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7023 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007024 // Usage count limit tag is enforced by keystore, keymint does nothing.
7025 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007026 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007027 }
7028}
7029
7030/*
Qi Wubeefae42021-01-28 23:16:37 +08007031 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007032 *
Qi Wubeefae42021-01-28 23:16:37 +08007033 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007034 */
Qi Wubeefae42021-01-28 23:16:37 +08007035TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007036 if (SecLevel() == SecurityLevel::STRONGBOX) {
7037 GTEST_SKIP() << "Test not applicable to StrongBox device";
7038 }
Qi Wubeefae42021-01-28 23:16:37 +08007039
7040 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7041 .Authorization(TAG_NO_AUTH_REQUIRED)
7042 .AesEncryptionKey(128)
7043 .EcbMode()
7044 .Padding(PaddingMode::NONE)
7045 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7046
7047 // Check the usage count limit tag appears in the authorizations.
7048 AuthorizationSet auths;
7049 for (auto& entry : key_characteristics_) {
7050 auths.push_back(AuthorizationSet(entry.authorizations));
7051 }
7052 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7053 << "key usage count limit " << 3U << " missing";
7054
7055 string message = "1234567890123456";
7056 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7057
7058 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7059 AuthorizationSet keystore_auths =
7060 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7061
7062 EncryptMessage(message, params);
7063 EncryptMessage(message, params);
7064 EncryptMessage(message, params);
7065
7066 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7067 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7068 // must be invalidated from secure storage (such as RPMB partition).
7069 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7070 } else {
7071 // Usage count limit tag is enforced by keystore, keymint does nothing.
7072 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007073 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007074 }
7075}
7076
7077/*
7078 * UsageCountLimitTest.TestSingleUseRsa
7079 *
7080 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7081 */
7082TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007083 if (SecLevel() == SecurityLevel::STRONGBOX) {
7084 GTEST_SKIP() << "Test not applicable to StrongBox device";
7085 }
Qi Wud22ec842020-11-26 13:27:53 +08007086
7087 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7088 .Authorization(TAG_NO_AUTH_REQUIRED)
7089 .RsaSigningKey(1024, 65537)
7090 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007091 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7092 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007093
7094 // Check the usage count limit tag appears in the authorizations.
7095 AuthorizationSet auths;
7096 for (auto& entry : key_characteristics_) {
7097 auths.push_back(AuthorizationSet(entry.authorizations));
7098 }
7099 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7100 << "key usage count limit " << 1U << " missing";
7101
7102 string message = "1234567890123456";
7103 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7104
Qi Wubeefae42021-01-28 23:16:37 +08007105 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7106 AuthorizationSet keystore_auths =
7107 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7108
Qi Wud22ec842020-11-26 13:27:53 +08007109 // First usage of RSA key should work.
7110 SignMessage(message, params);
7111
Qi Wud22ec842020-11-26 13:27:53 +08007112 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7113 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7114 // must be invalidated from secure storage (such as RPMB partition).
7115 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7116 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007117 // Usage count limit tag is enforced by keystore, keymint does nothing.
7118 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007119 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007120 }
7121}
7122
7123/*
7124 * UsageCountLimitTest.TestLimitUseRsa
7125 *
7126 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7127 */
7128TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007129 if (SecLevel() == SecurityLevel::STRONGBOX) {
7130 GTEST_SKIP() << "Test not applicable to StrongBox device";
7131 }
Qi Wubeefae42021-01-28 23:16:37 +08007132
7133 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7134 .Authorization(TAG_NO_AUTH_REQUIRED)
7135 .RsaSigningKey(1024, 65537)
7136 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007137 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7138 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007139
7140 // Check the usage count limit tag appears in the authorizations.
7141 AuthorizationSet auths;
7142 for (auto& entry : key_characteristics_) {
7143 auths.push_back(AuthorizationSet(entry.authorizations));
7144 }
7145 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7146 << "key usage count limit " << 3U << " missing";
7147
7148 string message = "1234567890123456";
7149 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7150
7151 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7152 AuthorizationSet keystore_auths =
7153 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7154
7155 SignMessage(message, params);
7156 SignMessage(message, params);
7157 SignMessage(message, params);
7158
7159 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7160 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7161 // must be invalidated from secure storage (such as RPMB partition).
7162 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7163 } else {
7164 // Usage count limit tag is enforced by keystore, keymint does nothing.
7165 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007166 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007167 }
7168}
7169
Qi Wu8e727f72021-02-11 02:49:33 +08007170/*
7171 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7172 *
7173 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7174 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7175 * in hardware.
7176 */
7177TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01007178 if (SecLevel() == SecurityLevel::STRONGBOX) {
7179 GTEST_SKIP() << "Test not applicable to StrongBox device";
7180 }
Qi Wu8e727f72021-02-11 02:49:33 +08007181
7182 auto error = GenerateKey(AuthorizationSetBuilder()
7183 .RsaSigningKey(2048, 65537)
7184 .Digest(Digest::NONE)
7185 .Padding(PaddingMode::NONE)
7186 .Authorization(TAG_NO_AUTH_REQUIRED)
7187 .Authorization(TAG_ROLLBACK_RESISTANCE)
7188 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007189 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7190 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007191 }
David Drysdale513bf122021-10-06 11:53:13 +01007192
7193 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7194 ASSERT_EQ(ErrorCode::OK, error);
7195 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7196 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7197 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7198
7199 // The KeyMint should also enforce single use key in hardware when it supports rollback
7200 // resistance.
7201 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7202 .Authorization(TAG_NO_AUTH_REQUIRED)
7203 .RsaSigningKey(1024, 65537)
7204 .NoDigestOrPadding()
7205 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7206 .SetDefaultValidity()));
7207
7208 // Check the usage count limit tag appears in the hardware authorizations.
7209 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7210 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7211 << "key usage count limit " << 1U << " missing";
7212
7213 string message = "1234567890123456";
7214 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7215
7216 // First usage of RSA key should work.
7217 SignMessage(message, params);
7218
7219 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7220 // must be invalidated from secure storage (such as RPMB partition).
7221 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007222}
7223
Qi Wud22ec842020-11-26 13:27:53 +08007224INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7225
David Drysdale7de9feb2021-03-05 14:56:19 +00007226typedef KeyMintAidlTestBase GetHardwareInfoTest;
7227
7228TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7229 // Retrieving hardware info should give the same result each time.
7230 KeyMintHardwareInfo info;
7231 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7232 KeyMintHardwareInfo info2;
7233 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7234 EXPECT_EQ(info, info2);
7235}
7236
7237INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7238
Selene Huang31ab4042020-04-29 04:22:39 -07007239typedef KeyMintAidlTestBase AddEntropyTest;
7240
7241/*
7242 * AddEntropyTest.AddEntropy
7243 *
7244 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7245 * is actually added.
7246 */
7247TEST_P(AddEntropyTest, AddEntropy) {
7248 string data = "foo";
7249 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7250}
7251
7252/*
7253 * AddEntropyTest.AddEmptyEntropy
7254 *
7255 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7256 */
7257TEST_P(AddEntropyTest, AddEmptyEntropy) {
7258 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7259}
7260
7261/*
7262 * AddEntropyTest.AddLargeEntropy
7263 *
7264 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7265 */
7266TEST_P(AddEntropyTest, AddLargeEntropy) {
7267 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7268}
7269
David Drysdalebb3d85e2021-04-13 11:15:51 +01007270/*
7271 * AddEntropyTest.AddTooLargeEntropy
7272 *
7273 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7274 */
7275TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7276 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7277 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7278}
7279
Selene Huang31ab4042020-04-29 04:22:39 -07007280INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7281
Selene Huang31ab4042020-04-29 04:22:39 -07007282typedef KeyMintAidlTestBase KeyDeletionTest;
7283
7284/**
7285 * KeyDeletionTest.DeleteKey
7286 *
7287 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7288 * valid key blob.
7289 */
7290TEST_P(KeyDeletionTest, DeleteKey) {
7291 auto error = GenerateKey(AuthorizationSetBuilder()
7292 .RsaSigningKey(2048, 65537)
7293 .Digest(Digest::NONE)
7294 .Padding(PaddingMode::NONE)
7295 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007296 .Authorization(TAG_ROLLBACK_RESISTANCE)
7297 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007298 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7299 GTEST_SKIP() << "Rollback resistance not supported";
7300 }
Selene Huang31ab4042020-04-29 04:22:39 -07007301
7302 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007303 ASSERT_EQ(ErrorCode::OK, error);
7304 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7305 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007306
David Drysdale513bf122021-10-06 11:53:13 +01007307 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007308
David Drysdale513bf122021-10-06 11:53:13 +01007309 string message = "12345678901234567890123456789012";
7310 AuthorizationSet begin_out_params;
7311 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7312 Begin(KeyPurpose::SIGN, key_blob_,
7313 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7314 &begin_out_params));
7315 AbortIfNeeded();
7316 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007317}
7318
7319/**
7320 * KeyDeletionTest.DeleteInvalidKey
7321 *
7322 * This test checks that the HAL excepts invalid key blobs..
7323 */
7324TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7325 // Generate key just to check if rollback protection is implemented
7326 auto error = GenerateKey(AuthorizationSetBuilder()
7327 .RsaSigningKey(2048, 65537)
7328 .Digest(Digest::NONE)
7329 .Padding(PaddingMode::NONE)
7330 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007331 .Authorization(TAG_ROLLBACK_RESISTANCE)
7332 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007333 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7334 GTEST_SKIP() << "Rollback resistance not supported";
7335 }
Selene Huang31ab4042020-04-29 04:22:39 -07007336
7337 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007338 ASSERT_EQ(ErrorCode::OK, error);
7339 AuthorizationSet enforced(SecLevelAuthorizations());
7340 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007341
David Drysdale513bf122021-10-06 11:53:13 +01007342 // Delete the key we don't care about the result at this point.
7343 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007344
David Drysdale513bf122021-10-06 11:53:13 +01007345 // Now create an invalid key blob and delete it.
7346 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007347
David Drysdale513bf122021-10-06 11:53:13 +01007348 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007349}
7350
7351/**
7352 * KeyDeletionTest.DeleteAllKeys
7353 *
7354 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7355 *
7356 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7357 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7358 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7359 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7360 * credentials stored in Keystore/Keymint.
7361 */
7362TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007363 if (!arm_deleteAllKeys) {
7364 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7365 return;
7366 }
Selene Huang31ab4042020-04-29 04:22:39 -07007367 auto error = GenerateKey(AuthorizationSetBuilder()
7368 .RsaSigningKey(2048, 65537)
7369 .Digest(Digest::NONE)
7370 .Padding(PaddingMode::NONE)
7371 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007372 .Authorization(TAG_ROLLBACK_RESISTANCE)
7373 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007374 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7375 GTEST_SKIP() << "Rollback resistance not supported";
7376 }
Selene Huang31ab4042020-04-29 04:22:39 -07007377
7378 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007379 ASSERT_EQ(ErrorCode::OK, error);
7380 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7381 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007382
David Drysdale513bf122021-10-06 11:53:13 +01007383 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007384
David Drysdale513bf122021-10-06 11:53:13 +01007385 string message = "12345678901234567890123456789012";
7386 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07007387
David Drysdale513bf122021-10-06 11:53:13 +01007388 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7389 Begin(KeyPurpose::SIGN, key_blob_,
7390 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7391 &begin_out_params));
7392 AbortIfNeeded();
7393 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007394}
7395
7396INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
7397
David Drysdaled2cc8c22021-04-15 13:29:45 +01007398typedef KeyMintAidlTestBase KeyUpgradeTest;
7399
7400/**
7401 * KeyUpgradeTest.UpgradeInvalidKey
7402 *
7403 * This test checks that the HAL excepts invalid key blobs..
7404 */
7405TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
7406 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
7407
7408 std::vector<uint8_t> new_blob;
7409 Status result = keymint_->upgradeKey(key_blob,
7410 AuthorizationSetBuilder()
7411 .Authorization(TAG_APPLICATION_ID, "clientid")
7412 .Authorization(TAG_APPLICATION_DATA, "appdata")
7413 .vector_data(),
7414 &new_blob);
7415 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
7416}
7417
7418INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
7419
Selene Huang31ab4042020-04-29 04:22:39 -07007420using UpgradeKeyTest = KeyMintAidlTestBase;
7421
7422/*
7423 * UpgradeKeyTest.UpgradeKey
7424 *
7425 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
7426 */
7427TEST_P(UpgradeKeyTest, UpgradeKey) {
7428 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7429 .AesEncryptionKey(128)
7430 .Padding(PaddingMode::NONE)
7431 .Authorization(TAG_NO_AUTH_REQUIRED)));
7432
7433 auto result = UpgradeKey(key_blob_);
7434
7435 // Key doesn't need upgrading. Should get okay, but no new key blob.
7436 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
7437}
7438
7439INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
7440
7441using ClearOperationsTest = KeyMintAidlTestBase;
7442
7443/*
7444 * ClearSlotsTest.TooManyOperations
7445 *
7446 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
7447 * operations are started without being finished or aborted. Also verifies
7448 * that aborting the operations clears the operations.
7449 *
7450 */
7451TEST_P(ClearOperationsTest, TooManyOperations) {
7452 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7453 .Authorization(TAG_NO_AUTH_REQUIRED)
7454 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08007455 .Padding(PaddingMode::NONE)
7456 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007457
7458 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
7459 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08007460 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07007461 AuthorizationSet out_params;
7462 ErrorCode result;
7463 size_t i;
7464
7465 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00007466 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07007467 if (ErrorCode::OK != result) {
7468 break;
7469 }
7470 }
7471 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
7472 // Try again just in case there's a weird overflow bug
7473 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00007474 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007475 for (size_t j = 0; j < i; j++) {
7476 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
7477 << "Aboort failed for i = " << j << std::endl;
7478 }
David Drysdale7fc26b92022-05-13 09:54:24 +01007479 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007480 AbortIfNeeded();
7481}
7482
7483INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
7484
7485typedef KeyMintAidlTestBase TransportLimitTest;
7486
7487/*
David Drysdale7de9feb2021-03-05 14:56:19 +00007488 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07007489 *
7490 * Verifies that passing input data to finish succeeds as expected.
7491 */
7492TEST_P(TransportLimitTest, LargeFinishInput) {
7493 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7494 .Authorization(TAG_NO_AUTH_REQUIRED)
7495 .AesEncryptionKey(128)
7496 .BlockMode(BlockMode::ECB)
7497 .Padding(PaddingMode::NONE)));
7498
7499 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
7500 auto cipher_params =
7501 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7502
7503 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007504 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007505
7506 string plain_message = std::string(1 << msg_size, 'x');
7507 string encrypted_message;
7508 auto rc = Finish(plain_message, &encrypted_message);
7509
7510 EXPECT_EQ(ErrorCode::OK, rc);
7511 EXPECT_EQ(plain_message.size(), encrypted_message.size())
7512 << "Encrypt finish returned OK, but did not consume all of the given input";
7513 cipher_params.push_back(out_params);
7514
David Drysdale7fc26b92022-05-13 09:54:24 +01007515 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007516
7517 string decrypted_message;
7518 rc = Finish(encrypted_message, &decrypted_message);
7519 EXPECT_EQ(ErrorCode::OK, rc);
7520 EXPECT_EQ(plain_message.size(), decrypted_message.size())
7521 << "Decrypt finish returned OK, did not consume all of the given input";
7522 }
7523}
7524
7525INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
7526
Seth Moored79a0ec2021-12-13 20:03:33 +00007527static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05007528 switch (curve) {
7529 case EcCurve::P_224:
7530 return NID_secp224r1;
7531 case EcCurve::P_256:
7532 return NID_X9_62_prime256v1;
7533 case EcCurve::P_384:
7534 return NID_secp384r1;
7535 case EcCurve::P_521:
7536 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00007537 case EcCurve::CURVE_25519:
7538 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05007539 }
7540}
7541
David Drysdale42fe1892021-10-14 14:43:46 +01007542class KeyAgreementTest : public KeyMintAidlTestBase {
7543 protected:
7544 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
7545 std::vector<uint8_t>* localPublicKey) {
7546 // Generate EC key locally (with access to private key material)
7547 if (localCurve == EcCurve::CURVE_25519) {
7548 uint8_t privKeyData[32];
7549 uint8_t pubKeyData[32];
7550 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01007551 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
7552 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
7553 } else {
7554 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
7555 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
7556 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
7557 ASSERT_NE(group, nullptr);
7558 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
7559 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
7560 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
7561 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01007562 }
David Drysdalea410b772022-05-09 16:44:13 +01007563
7564 // Get encoded form of the public part of the locally generated key...
7565 unsigned char* p = nullptr;
7566 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
7567 ASSERT_GT(localPublicKeySize, 0);
7568 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
7569 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
7570 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01007571 }
7572
7573 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
7574 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00007575 auto builder = AuthorizationSetBuilder()
7576 .Authorization(TAG_NO_AUTH_REQUIRED)
7577 .Authorization(TAG_EC_CURVE, curve)
7578 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7579 .Authorization(TAG_ALGORITHM, Algorithm::EC)
7580 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
7581 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
7582 .SetDefaultValidity();
7583 ErrorCode result = GenerateKey(builder);
7584
7585 if (SecLevel() == SecurityLevel::STRONGBOX) {
7586 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
7587 result = GenerateKeyWithSelfSignedAttestKey(
7588 AuthorizationSetBuilder()
7589 .EcdsaKey(EcCurve::P_256)
7590 .AttestKey()
7591 .SetDefaultValidity(), /* attest key params */
7592 builder, &key_blob_, &key_characteristics_, &cert_chain_);
7593 }
7594 }
David Drysdale42fe1892021-10-14 14:43:46 +01007595 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
7596 ASSERT_GT(cert_chain_.size(), 0);
7597 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7598 ASSERT_NE(kmKeyCert, nullptr);
7599 // Check that keyAgreement (bit 4) is set in KeyUsage
7600 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
7601 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
7602 ASSERT_NE(*kmPubKey, nullptr);
7603 if (dump_Attestations) {
7604 for (size_t n = 0; n < cert_chain_.size(); n++) {
7605 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
7606 }
7607 }
7608 }
7609
7610 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
7611 const std::vector<uint8_t>& localPublicKey) {
7612 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7613 string ZabFromKeyMintStr;
7614 ASSERT_EQ(ErrorCode::OK,
7615 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
7616 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
7617 vector<uint8_t> ZabFromTest;
7618
7619 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
7620 size_t kmPubKeySize = 32;
7621 uint8_t kmPubKeyData[32];
7622 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7623 ASSERT_EQ(kmPubKeySize, 32);
7624
7625 uint8_t localPrivKeyData[32];
7626 size_t localPrivKeySize = 32;
7627 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
7628 &localPrivKeySize));
7629 ASSERT_EQ(localPrivKeySize, 32);
7630
7631 uint8_t sharedKey[32];
7632 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
7633 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
7634 } else {
7635 // Perform local ECDH between the two keys so we can check if we get the same Zab..
7636 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
7637 ASSERT_NE(ctx, nullptr);
7638 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
7639 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
7640 size_t ZabFromTestLen = 0;
7641 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
7642 ZabFromTest.resize(ZabFromTestLen);
7643 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
7644 }
7645 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
7646 }
7647};
7648
David Zeuthene0c40892021-01-08 12:54:11 -05007649/*
7650 * KeyAgreementTest.Ecdh
7651 *
David Drysdale42fe1892021-10-14 14:43:46 +01007652 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05007653 */
7654TEST_P(KeyAgreementTest, Ecdh) {
7655 // Because it's possible to use this API with keys on different curves, we
7656 // check all N^2 combinations where N is the number of supported
7657 // curves.
7658 //
7659 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
7660 // lot more curves we can be smart about things and just pick |otherCurve| so
7661 // it's not |curve| and that way we end up with only 2*N runs
7662 //
7663 for (auto curve : ValidCurves()) {
7664 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01007665 SCOPED_TRACE(testing::Message()
7666 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
7667
David Zeuthene0c40892021-01-08 12:54:11 -05007668 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007669 EVP_PKEY_Ptr localPrivKey;
7670 vector<uint8_t> localPublicKey;
7671 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007672
7673 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007674 EVP_PKEY_Ptr kmPubKey;
7675 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007676
7677 // Now that we have the two keys, we ask KeyMint to perform ECDH...
7678 if (curve != localCurve) {
7679 // If the keys are using different curves KeyMint should fail with
7680 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01007681 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05007682 string ZabFromKeyMintStr;
7683 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01007684 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05007685 &ZabFromKeyMintStr));
7686
7687 } else {
7688 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01007689 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007690 }
7691
7692 CheckedDeleteKey();
7693 }
7694 }
7695}
7696
David Drysdale42fe1892021-10-14 14:43:46 +01007697/*
7698 * KeyAgreementTest.EcdhCurve25519
7699 *
7700 * Verifies that ECDH works for curve25519. This is also covered by the general
7701 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
7702 * KeyMint 1.0.
7703 */
7704TEST_P(KeyAgreementTest, EcdhCurve25519) {
7705 if (!Curve25519Supported()) {
7706 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7707 }
7708
7709 // Generate EC key in KeyMint (only access to public key material)
7710 EcCurve curve = EcCurve::CURVE_25519;
7711 EVP_PKEY_Ptr kmPubKey = nullptr;
7712 GenerateKeyMintEcKey(curve, &kmPubKey);
7713
7714 // Generate EC key on same curve locally (with access to private key material).
7715 EVP_PKEY_Ptr privKey;
7716 vector<uint8_t> encodedPublicKey;
7717 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7718
7719 // Agree on a key between local and KeyMint and check it.
7720 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7721
7722 CheckedDeleteKey();
7723}
7724
7725/*
7726 * KeyAgreementTest.EcdhCurve25519Imported
7727 *
7728 * Verifies that ECDH works for an imported curve25519 key.
7729 */
7730TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
7731 if (!Curve25519Supported()) {
7732 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7733 }
7734
7735 // Import x25519 key into KeyMint.
7736 EcCurve curve = EcCurve::CURVE_25519;
7737 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
7738 .Authorization(TAG_NO_AUTH_REQUIRED)
7739 .EcdsaKey(EcCurve::CURVE_25519)
7740 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7741 .SetDefaultValidity(),
7742 KeyFormat::PKCS8, x25519_pkcs8_key));
7743 ASSERT_GT(cert_chain_.size(), 0);
7744 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7745 ASSERT_NE(kmKeyCert, nullptr);
7746 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
7747 ASSERT_NE(kmPubKey.get(), nullptr);
7748
7749 // Expect the import to emit corresponding public key data.
7750 size_t kmPubKeySize = 32;
7751 uint8_t kmPubKeyData[32];
7752 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7753 ASSERT_EQ(kmPubKeySize, 32);
7754 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
7755 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
7756
7757 // Generate EC key on same curve locally (with access to private key material).
7758 EVP_PKEY_Ptr privKey;
7759 vector<uint8_t> encodedPublicKey;
7760 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7761
7762 // Agree on a key between local and KeyMint and check it.
7763 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7764
7765 CheckedDeleteKey();
7766}
7767
7768/*
7769 * KeyAgreementTest.EcdhCurve25519InvalidSize
7770 *
7771 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
7772 */
7773TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
7774 if (!Curve25519Supported()) {
7775 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7776 }
7777
7778 // Generate EC key in KeyMint (only access to public key material)
7779 EcCurve curve = EcCurve::CURVE_25519;
7780 EVP_PKEY_Ptr kmPubKey = nullptr;
7781 GenerateKeyMintEcKey(curve, &kmPubKey);
7782
7783 // Generate EC key on same curve locally (with access to private key material).
7784 EVP_PKEY_Ptr privKey;
7785 vector<uint8_t> encodedPublicKey;
7786 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7787
7788 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7789 string ZabFromKeyMintStr;
7790 // Send in an incomplete public key.
7791 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
7792 &ZabFromKeyMintStr));
7793
7794 CheckedDeleteKey();
7795}
7796
7797/*
7798 * KeyAgreementTest.EcdhCurve25519Mismatch
7799 *
7800 * Verifies that ECDH fails between curve25519 and other curves.
7801 */
7802TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
7803 if (!Curve25519Supported()) {
7804 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7805 }
7806
7807 // Generate EC key in KeyMint (only access to public key material)
7808 EcCurve curve = EcCurve::CURVE_25519;
7809 EVP_PKEY_Ptr kmPubKey = nullptr;
7810 GenerateKeyMintEcKey(curve, &kmPubKey);
7811
7812 for (auto localCurve : ValidCurves()) {
7813 if (localCurve == curve) {
7814 continue;
7815 }
7816 // Generate EC key on a different curve locally (with access to private key material).
7817 EVP_PKEY_Ptr privKey;
7818 vector<uint8_t> encodedPublicKey;
7819 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
7820
David Drysdale7fc26b92022-05-13 09:54:24 +01007821 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01007822 string ZabFromKeyMintStr;
7823 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
7824 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
7825 &ZabFromKeyMintStr));
7826 }
7827
7828 CheckedDeleteKey();
7829}
7830
David Zeuthene0c40892021-01-08 12:54:11 -05007831INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
7832
David Drysdaled2cc8c22021-04-15 13:29:45 +01007833using DestroyAttestationIdsTest = KeyMintAidlTestBase;
7834
7835// This is a problematic test, as it can render the device under test permanently unusable.
7836// Re-enable and run at your own risk.
7837TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
7838 auto result = DestroyAttestationIds();
7839 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
7840}
7841
7842INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
7843
Shawn Willdend659c7c2021-02-19 14:51:51 -07007844using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007845
David Drysdaledb0dcf52021-05-18 11:43:31 +01007846/*
7847 * EarlyBootKeyTest.CreateEarlyBootKeys
7848 *
7849 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
7850 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007851TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01007852 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007853 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7854 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7855
David Drysdaleadfe6112021-05-27 12:00:53 +01007856 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
7857 ASSERT_GT(keyData.blob.size(), 0U);
7858 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7859 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7860 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007861 CheckedDeleteKey(&aesKeyData.blob);
7862 CheckedDeleteKey(&hmacKeyData.blob);
7863 CheckedDeleteKey(&rsaKeyData.blob);
7864 CheckedDeleteKey(&ecdsaKeyData.blob);
7865}
7866
David Drysdaledb0dcf52021-05-18 11:43:31 +01007867/*
David Drysdaleadfe6112021-05-27 12:00:53 +01007868 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
7869 *
7870 * Verifies that creating an early boot key with attestation succeeds.
7871 */
7872TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
7873 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
7874 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
7875 builder->AttestationChallenge("challenge");
7876 builder->AttestationApplicationId("app_id");
7877 });
7878
7879 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00007880 // Strongbox may not support factory attestation. Key creation might fail with
7881 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
7882 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
7883 continue;
7884 }
David Drysdaleadfe6112021-05-27 12:00:53 +01007885 ASSERT_GT(keyData.blob.size(), 0U);
7886 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7887 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7888 }
7889 CheckedDeleteKey(&aesKeyData.blob);
7890 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00007891 if (rsaKeyData.blob.size() != 0U) {
7892 CheckedDeleteKey(&rsaKeyData.blob);
7893 }
7894 if (ecdsaKeyData.blob.size() != 0U) {
7895 CheckedDeleteKey(&ecdsaKeyData.blob);
7896 }
David Drysdaleadfe6112021-05-27 12:00:53 +01007897}
7898
7899/*
7900 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01007901 *
7902 * Verifies that using early boot keys at a later stage fails.
7903 */
7904TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
7905 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7906 .Authorization(TAG_NO_AUTH_REQUIRED)
7907 .Authorization(TAG_EARLY_BOOT_ONLY)
7908 .HmacKey(128)
7909 .Digest(Digest::SHA_2_256)
7910 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
7911 AuthorizationSet output_params;
7912 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
7913 AuthorizationSetBuilder()
7914 .Digest(Digest::SHA_2_256)
7915 .Authorization(TAG_MAC_LENGTH, 256),
7916 &output_params));
7917}
7918
7919/*
7920 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
7921 *
7922 * Verifies that importing early boot keys fails.
7923 */
7924TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
7925 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
7926 .Authorization(TAG_NO_AUTH_REQUIRED)
7927 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01007928 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01007929 .Digest(Digest::SHA_2_256)
7930 .SetDefaultValidity(),
7931 KeyFormat::PKCS8, ec_256_key));
7932}
7933
David Drysdaled2cc8c22021-04-15 13:29:45 +01007934// 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 +00007935// boot stage, which no proper Android device is by the time we can run VTS. To use this,
7936// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
7937// early boot, so you'll have to reboot between runs.
7938TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
7939 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7940 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7941 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
7942 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7943 EXPECT_TRUE(
7944 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7945 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7946 EXPECT_TRUE(
7947 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7948
7949 // Should be able to use keys, since early boot has not ended
7950 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7951 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
7952 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
7953 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
7954
7955 // End early boot
7956 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
7957 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
7958
7959 // Should not be able to use already-created keys.
7960 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
7961 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
7962 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
7963 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
7964
7965 CheckedDeleteKey(&aesKeyData.blob);
7966 CheckedDeleteKey(&hmacKeyData.blob);
7967 CheckedDeleteKey(&rsaKeyData.blob);
7968 CheckedDeleteKey(&ecdsaKeyData.blob);
7969
7970 // Should not be able to create new keys
7971 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
7972 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
7973
7974 CheckedDeleteKey(&aesKeyData.blob);
7975 CheckedDeleteKey(&hmacKeyData.blob);
7976 CheckedDeleteKey(&rsaKeyData.blob);
7977 CheckedDeleteKey(&ecdsaKeyData.blob);
7978}
Shawn Willdend659c7c2021-02-19 14:51:51 -07007979
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007980INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
7981
Shawn Willdend659c7c2021-02-19 14:51:51 -07007982using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007983
7984// This may be a problematic test. It can't be run repeatedly without unlocking the device in
7985// between runs... and on most test devices there are no enrolled credentials so it can't be
7986// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
7987// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
7988// a manual test process, which includes unlocking between runs, which is why it's included here.
7989// Well, that and the fact that it's the only test we can do without also making calls into the
7990// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
7991// implications might be, so that may or may not be a solution.
7992TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
7993 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7994 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
7995
7996 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7997 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
7998 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
7999 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8000
8001 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008002 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008003 ASSERT_EQ(ErrorCode::OK, rc);
8004 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8005 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8006 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8007 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
8008
8009 CheckedDeleteKey(&aesKeyData.blob);
8010 CheckedDeleteKey(&hmacKeyData.blob);
8011 CheckedDeleteKey(&rsaKeyData.blob);
8012 CheckedDeleteKey(&ecdsaKeyData.blob);
8013}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008014
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008015INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8016
Shawn Willden22fb9c12022-06-02 14:04:33 -06008017using VsrRequirementTest = KeyMintAidlTestBase;
8018
8019TEST_P(VsrRequirementTest, Vsr13Test) {
8020 int vsr_api_level = get_vsr_api_level();
8021 if (vsr_api_level < 33) {
8022 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8023 }
8024 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8025}
8026
8027INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8028
Janis Danisevskis24c04702020-12-16 18:28:39 -08008029} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008030
8031int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008032 std::cout << "Testing ";
8033 auto halInstances =
8034 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8035 std::cout << "HAL instances:\n";
8036 for (auto& entry : halInstances) {
8037 std::cout << " " << entry << '\n';
8038 }
8039
Selene Huang31ab4042020-04-29 04:22:39 -07008040 ::testing::InitGoogleTest(&argc, argv);
8041 for (int i = 1; i < argc; ++i) {
8042 if (argv[i][0] == '-') {
8043 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008044 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8045 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008046 }
8047 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008048 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8049 dump_Attestations = true;
8050 } else {
8051 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008052 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008053 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8054 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8055 // be run in emulated environments that don't have the normal bootloader
8056 // interactions.
8057 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8058 }
Selene Huang31ab4042020-04-29 04:22:39 -07008059 }
8060 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008061 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008062}