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