blob: dc1d843bd2173aac8470972c3e839bcd23a32920 [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
David Drysdale37af4b32021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Drysdale42fe1892021-10-14 14:43:46 +010025#include <openssl/curve25519.h>
David Zeuthene0c40892021-01-08 12:54:11 -050026#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070027#include <openssl/evp.h>
28#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050029#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070030
31#include <cutils/properties.h>
32
David Drysdale4dc01072021-04-01 12:17:35 +010033#include <android/binder_manager.h>
34
35#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080036#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070037
Shawn Willden08a7e432020-12-11 13:05:27 +000038#include <keymint_support/key_param_output.h>
39#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070040
41#include "KeyMintAidlTestBase.h"
42
Janis Danisevskis24c04702020-12-16 18:28:39 -080043using aidl::android::hardware::security::keymint::AuthorizationSet;
44using aidl::android::hardware::security::keymint::KeyCharacteristics;
45using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070046
Selene Huang31ab4042020-04-29 04:22:39 -070047namespace std {
48
Janis Danisevskis24c04702020-12-16 18:28:39 -080049using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070050
51template <>
52struct std::equal_to<KeyCharacteristics> {
53 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070054 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070055
Shawn Willden7f424372021-01-10 18:06:50 -070056 // this isn't very efficient. Oh, well.
57 AuthorizationSet a_auths(a.authorizations);
58 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070059
Shawn Willden7f424372021-01-10 18:06:50 -070060 a_auths.Sort();
61 b_auths.Sort();
62
63 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070064 }
65};
66
67} // namespace std
68
Janis Danisevskis24c04702020-12-16 18:28:39 -080069namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000070
Selene Huang31ab4042020-04-29 04:22:39 -070071namespace {
72
David Drysdalefeab5d92022-01-06 15:46:23 +000073// Maximum supported Ed25519 message size.
74const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
75
David Drysdaledbbbe2e2021-12-02 07:44:23 +000076// Whether to check that BOOT_PATCHLEVEL is populated.
77bool check_boot_pl = true;
78
Seth Moore7a55ae32021-06-23 14:28:11 -070079// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000080// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070081// is a small (roughly 1/256) chance that corrupting ciphertext still results
82// in valid PKCS7 padding.
83constexpr size_t kMaxPaddingCorruptionRetries = 8;
84
Selene Huang31ab4042020-04-29 04:22:39 -070085template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000086bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
87 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070088 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080089 if (auto p = authorizationValue(ttag, param)) {
90 return *p == expected_value;
91 }
92 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070093 });
94 return (it != set.end());
95}
96
97template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000098bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070099 auto it = std::find_if(set.begin(), set.end(),
100 [&](const KeyParameter& param) { return param.tag == tag; });
101 return (it != set.end());
102}
103
104constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
108 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
110 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
111 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
114 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
115 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
117 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
120
121string hex2str(string a) {
122 string b;
123 size_t num = a.size() / 2;
124 b.resize(num);
125 for (size_t i = 0; i < num; i++) {
126 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
127 }
128 return b;
129}
130
David Drysdaled2cc8c22021-04-15 13:29:45 +0100131string rsa_key = hex2str(
132 // RFC 5208 s5
133 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
134 "020100" // INTEGER length 1 value 0x00 (version)
135 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
136 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
137 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
138 "0500" // NULL (parameters)
139 // } end SEQUENCE (AlgorithmIdentifier)
140 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
141 // RFC 8017 A.1.2
142 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
143 "020100" // INTEGER length 1 value 0x00 (version)
144 "028181" // INTEGER length 0x81 value (modulus) ...
145 "00c6095409047d8634812d5a218176e4"
146 "5c41d60a75b13901f234226cffe77652"
147 "1c5a77b9e389417b71c0b6a44d13afe4"
148 "e4a2805d46c9da2935adb1ff0c1f24ea"
149 "06e62b20d776430a4d435157233c6f91"
150 "6783c30e310fcbd89b85c2d567711697"
151 "85ac12bca244abda72bfb19fc44d27c8"
152 "1e1d92de284f4061edfd99280745ea6d"
153 "25"
154 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
155 "028180" // INTEGER length 0x80 (privateExponent) value...
156 "1be0f04d9cae3718691f035338308e91"
157 "564b55899ffb5084d2460e6630257e05"
158 "b3ceab02972dfabcd6ce5f6ee2589eb6"
159 "7911ed0fac16e43a444b8c861e544a05"
160 "93365772f8baf6b22fc9e3c5f1024b06"
161 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
162 "ace7240290bef16c0b3f7f3cdd64ce3a"
163 "b5912cf6e32f39ab188358afcccd8081"
164 "0241" // INTEGER length 0x41 (prime1)
165 "00e4b49ef50f765d3b24dde01aceaaf1"
166 "30f2c76670a91a61ae08af497b4a82be"
167 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
168 "8c92bfab137fba2285227b83c342ff7c"
169 "55"
170 "0241" // INTEGER length 0x41 (prime2)
171 "00ddabb5839c4c7f6bf3d4183231f005"
172 "b31aa58affdda5c79e4cce217f6bc930"
173 "dbe563d480706c24e9ebfcab28a6cdef"
174 "d324b77e1bf7251b709092c24ff501fd"
175 "91"
176 "0240" // INTEGER length 0x40 (exponent1)
177 "23d4340eda3445d8cd26c14411da6fdc"
178 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
179 "842c1d280405bc2f6c1bea214a1d742a"
180 "b996b35b63a82a5e470fa88dbf823cdd"
181 "0240" // INTEGER length 0x40 (exponent2)
182 "1b7b57449ad30d1518249a5f56bb9829"
183 "4d4b6ac12ffc86940497a5a5837a6cf9"
184 "46262b494526d328c11e1126380fde04"
185 "c24f916dec250892db09a6d77cdba351"
186 "0240" // INTEGER length 0x40 (coefficient)
187 "7762cd8f4d050da56bd591adb515d24d"
188 "7ccd32cca0d05f866d583514bd7324d5"
189 "f33645e8ed8b4a1cb3cc4a1d67987399"
190 "f2a09f5b3fb68c88d5e5d90ac33492d6"
191 // } end SEQUENCE (PrivateKey)
192 // } end SEQUENCE (PrivateKeyInfo)
193);
Selene Huang31ab4042020-04-29 04:22:39 -0700194
Selene Huange5727e62021-04-13 22:41:20 -0700195/*
196 * DER-encoded PKCS#8 format RSA key. Generated using:
197 *
198 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
199 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100200string rsa_2048_key = hex2str(
201 // RFC 5208 s5
202 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
203 "020100" // INTEGER length 1 value 0x00 (version)
204 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
205 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
206 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
207 "0500" // NULL (parameters)
208 // } end SEQUENCE (AlgorithmIdentifier)
209 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
210 // RFC 8017 A.1.2
211 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
212 "020100" // INTEGER length 1 value 0x00 (version)
213 "02820101" // INTEGER length 0x101 value (modulus) ...
214 "00BEBC342B56D443B1299F9A6A7056E8"
215 "0A897E318476A5A18029E63B2ED739A6"
216 "1791D339F58DC763D9D14911F2EDEC38"
217 "3DEE11F6319B44510E7A3ECD9B79B973"
218 "82E49500ACF8117DC89CAF0E621F7775"
219 "6554A2FD4664BFE7AB8B59AB48340DBF"
220 "A27B93B5A81F6ECDEB02D0759307128D"
221 "F3E3BAD4055C8B840216DFAA5700670E"
222 "6C5126F0962FCB70FF308F25049164CC"
223 "F76CC2DA66A7DD9A81A714C2809D6918"
224 "6133D29D84568E892B6FFBF3199BDB14"
225 "383EE224407F190358F111A949552ABA"
226 "6714227D1BD7F6B20DD0CB88F9467B71"
227 "9339F33BFF35B3870B3F62204E4286B0"
228 "948EA348B524544B5F9838F29EE643B0"
229 "79EEF8A713B220D7806924CDF7295070"
230 "C5"
231 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
232 "02820100" // INTEGER length 0x100 (privateExponent) value...
233 "69F377F35F2F584EF075353CCD1CA997"
234 "38DB3DBC7C7FF35F9366CE176DFD1B13"
235 "5AB10030344ABF5FBECF1D4659FDEF1C"
236 "0FC430834BE1BE3911951377BB3D563A"
237 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
238 "2686C7B4B3C09A7B8354133E6F93F790"
239 "D59EAEB92E84C9A4339302CCE28FDF04"
240 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
241 "6AB706645BF074A4E4090D06FB163124"
242 "365FD5EE7A20D350E9958CC30D91326E"
243 "1B292E9EF5DB408EC42DAF737D201497"
244 "04D0A678A0FB5B5446863B099228A352"
245 "D604BA8091A164D01D5AB05397C71EAD"
246 "20BE2A08FC528FE442817809C787FEE4"
247 "AB97F97B9130D022153EDC6EB6CBE7B0"
248 "F8E3473F2E901209B5DB10F93604DB01"
249 "028181" // INTEGER length 0x81 (prime1)
250 "00E83C0998214941EA4F9293F1B77E2E"
251 "99E6CF305FAF358238E126124FEAF2EB"
252 "9724B2EA7B78E6032343821A80E55D1D"
253 "88FB12D220C3F41A56142FEC85796D19"
254 "17F1E8C774F142B67D3D6E7B7E6B4383"
255 "E94DB5929089DBB346D5BDAB40CC2D96"
256 "EE0409475E175C63BF78CFD744136740"
257 "838127EA723FF3FE7FA368C1311B4A4E"
258 "05"
259 "028181" // INTEGER length 0x81 (prime2)
260 "00D240FCC0F5D7715CDE21CB2DC86EA1"
261 "46132EA3B06F61FF2AF54BF38473F59D"
262 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
263 "B1B58C39F95E4798CCBB43E83D0119AC"
264 "F532F359CA743C85199F0286610E2009"
265 "97D7312917179AC9B67558773212EC96"
266 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
267 "94D94E066A0900B7B70E82A44FB30053"
268 "C1"
269 "028181" // INTEGER length 0x81 (exponent1)
270 "00AD15DA1CBD6A492B66851BA8C316D3"
271 "8AB700E2CFDDD926A658003513C54BAA"
272 "152B30021D667D20078F500F8AD3E7F3"
273 "945D74A891ED1A28EAD0FEEAEC8C14A8"
274 "E834CF46A13D1378C99D18940823CFDD"
275 "27EC5810D59339E0C34198AC638E09C8"
276 "7CBB1B634A9864AE9F4D5EB2D53514F6"
277 "7B4CAEC048C8AB849A02E397618F3271"
278 "35"
279 "028180" // INTEGER length 0x80 (exponent2)
280 "1FA2C1A5331880A92D8F3E281C617108"
281 "BF38244F16E352E69ED417C7153F9EC3"
282 "18F211839C643DCF8B4DD67CE2AC312E"
283 "95178D5D952F06B1BF779F4916924B70"
284 "F582A23F11304E02A5E7565AE22A35E7"
285 "4FECC8B6FDC93F92A1A37703E4CF0E63"
286 "783BD02EB716A7ECBBFA606B10B74D01"
287 "579522E7EF84D91FC522292108D902C1"
288 "028180" // INTEGER length 0x80 (coefficient)
289 "796FE3825F9DCC85DF22D58690065D93"
290 "898ACD65C087BEA8DA3A63BF4549B795"
291 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
292 "0D74F40DED8E1102C52152A31B6165F8"
293 "3A6722AECFCC35A493D7634664B888A0"
294 "8D3EB034F12EA28BFEE346E205D33482"
295 "7F778B16ED40872BD29FCB36536B6E93"
296 "FFB06778696B4A9D81BB0A9423E63DE5"
297 // } end SEQUENCE (PrivateKey)
298 // } end SEQUENCE (PrivateKeyInfo)
299);
Selene Huange5727e62021-04-13 22:41:20 -0700300
David Drysdaled2cc8c22021-04-15 13:29:45 +0100301string ec_256_key = hex2str(
302 // RFC 5208 s5
303 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
304 "020100" // INTEGER length 1 value 0 (version)
305 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
306 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
307 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
308 "0608" // OBJECT IDENTIFIER length 8 (param)
309 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
310 // } end SEQUENCE (AlgorithmIdentifier)
311 "046d" // OCTET STRING length 0x6d (privateKey) holding...
312 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
313 "020101" // INTEGER length 1 value 1 (version)
314 "0420" // OCTET STRING length 0x20 (privateKey)
315 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
316 "941eed09366bc03299986481f3a4d859"
317 "a144" // TAG [1] len 0x44 (publicKey) {
318 "03420004bf85d7720d07c25461683bc6"
319 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
320 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
321 "bcc41c6eb00083cf3376d11fd44949e0"
322 "b2183bfe"
323 // } end SEQUENCE (ECPrivateKey)
324 // } end SEQUENCE (PrivateKeyInfo)
325);
Selene Huang31ab4042020-04-29 04:22:39 -0700326
David Drysdaled2cc8c22021-04-15 13:29:45 +0100327string ec_521_key = hex2str(
328 // RFC 5208 s5
329 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
330 "020100" // INTEGER length 1 value 0 (version)
331 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
332 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
333 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
334 "0605" // OBJECT IDENTIFIER length 5 (param)
335 "2B81040023" // 1.3.132.0.35 (secp521r1)
336 // } end SEQUENCE (AlgorithmIdentifier)
337 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
338 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
339 "020101" // INTEGER length 1 value 1 (version)
340 "0442" // OCTET STRING length 0x42 (privateKey)
341 "0011458C586DB5DAA92AFAB03F4FE46A"
342 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
343 "9D18D7D08B5BCFA0E53C75B064AD51C4"
344 "49BAE0258D54B94B1E885DED08ED4FB2"
345 "5CE9"
346 "A18189" // TAG [1] len 0x89 (publicKey) {
347 "03818600040149EC11C6DF0FA122C6A9"
348 "AFD9754A4FA9513A627CA329E349535A"
349 "5629875A8ADFBE27DCB932C051986377"
350 "108D054C28C6F39B6F2C9AF81802F9F3"
351 "26B842FF2E5F3C00AB7635CFB36157FC"
352 "0882D574A10D839C1A0C049DC5E0D775"
353 "E2EE50671A208431BB45E78E70BEFE93"
354 "0DB34818EE4D5C26259F5C6B8E28A652"
355 "950F9F88D7B4B2C9D9"
356 // } end SEQUENCE (ECPrivateKey)
357 // } end SEQUENCE (PrivateKeyInfo)
358);
Selene Huang31ab4042020-04-29 04:22:39 -0700359
David Drysdaled2cc8c22021-04-15 13:29:45 +0100360string ec_256_key_rfc5915 = hex2str(
361 // RFC 5208 s5
362 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
363 "020100" // INTEGER length 1 value 0 (version)
364 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
365 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
366 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
367 "0608" // OBJECT IDENTIFIER length 8 (param)
368 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
369 // } end SEQUENCE (AlgorithmIdentifier)
370 "0479" // OCTET STRING length 0x79 (privateKey) holding...
371 // RFC 5915 s3
372 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
373 "020101" // INTEGER length 1 value 1 (version)
374 "0420" // OCTET STRING length 0x42 (privateKey)
375 "782370a8c8ce5537baadd04dcff079c8"
376 "158cfa9c67b818b38e8d21c9fa750c1d"
377 "a00a" // TAG [0] length 0xa (parameters)
378 "0608" // OBJECT IDENTIFIER length 8
379 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
380 // } end TAG [0]
381 "a144" // TAG [1] length 0x44 (publicKey) {
382 "0342" // BIT STRING length 0x42
383 "00" // no pad bits
384 "04e2cc561ee701da0ad0ef0d176bb0c9"
385 "19d42e79c393fdc1bd6c4010d85cf2cf"
386 "8e68c905464666f98dad4f01573ba810"
387 "78b3428570a439ba3229fbc026c55068"
388 "2f"
389 // } end SEQUENCE (ECPrivateKey)
390 // } end SEQUENCE (PrivateKeyInfo)
391);
Selene Huang31ab4042020-04-29 04:22:39 -0700392
David Drysdaled2cc8c22021-04-15 13:29:45 +0100393string ec_256_key_sec1 = hex2str(
394 // RFC 5208 s5
395 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
396 "020100" // INTEGER length 1 value 0 (version)
397 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
398 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
399 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
400 "0608" // OBJECT IDENTIFIER length 8 (param)
401 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
402 // } end SEQUENCE (AlgorithmIdentifier)
403 "046d" // OCTET STRING length 0x6d (privateKey) holding...
404 // SEC1-v2 C.4
405 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
406 "020101" // INTEGER length 1 value 0x01 (version)
407 "0420" // OCTET STRING length 0x20 (privateKey)
408 "782370a8c8ce5537baadd04dcff079c8"
409 "158cfa9c67b818b38e8d21c9fa750c1d"
410 "a144" // TAG [1] length 0x44 (publicKey) {
411 "0342" // BIT STRING length 0x42
412 "00" // no pad bits
413 "04e2cc561ee701da0ad0ef0d176bb0c9"
414 "19d42e79c393fdc1bd6c4010d85cf2cf"
415 "8e68c905464666f98dad4f01573ba810"
416 "78b3428570a439ba3229fbc026c55068"
417 "2f"
418 // } end TAG [1] (publicKey)
419 // } end SEQUENCE (PrivateKeyInfo)
420);
Selene Huang31ab4042020-04-29 04:22:39 -0700421
David Drysdale42fe1892021-10-14 14:43:46 +0100422/**
423 * Ed25519 key pair generated as follows:
424 * ```
425 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
426 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
427 * Generating a ED25519 private key writing new private key to
428 * 'ed25519_priv.key'
429 * -----
430 * % cat ed25519_priv.key
431 * -----BEGIN PRIVATE KEY-----
432 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
433 * -----END PRIVATE KEY-----
434 * % der2ascii -pem -i ed25519_priv.key
435 * SEQUENCE {
436 * INTEGER { 0 }
437 * SEQUENCE {
438 * # ed25519
439 * OBJECT_IDENTIFIER { 1.3.101.112 }
440 * }
441 * OCTET_STRING {
442 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
443 * }
444 * }
445 * % cat ed25519.pem
446 * -----BEGIN CERTIFICATE-----
447 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
448 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
449 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
450 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
451 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
452 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
453 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
454 * -----END CERTIFICATE-----
455 * % openssl x509 -in ed25519.pem -text -noout
456 * Certificate:
457 * Data:
458 * Version: 3 (0x2)
459 * Serial Number:
460 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
461 * Signature Algorithm: ED25519
462 * Issuer: CN = fake.ed25519.com
463 * Validity
464 * Not Before: Oct 20 08:27:42 2021 GMT
465 * Not After : Sep 20 08:27:42 2023 GMT
466 * Subject: CN = fake.ed25519.com
467 * Subject Public Key Info:
468 * Public Key Algorithm: ED25519
469 * ED25519 Public-Key:
470 * pub:
471 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
472 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
473 * 56:91
474 * X509v3 extensions:
475 * X509v3 Subject Key Identifier:
476 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
477 * X509v3 Authority Key Identifier:
478 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
479 *
480 * X509v3 Basic Constraints: critical
481 * CA:TRUE
482 * Signature Algorithm: ED25519
483 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
484 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
485 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
486 * e7:07:32:60:32:8d:bb:eb:f6:0f
487 * ```
488 */
489string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
490string ed25519_pkcs8_key = hex2str(
491 // RFC 5208 s5
492 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
493 "0201" // INTEGER length 1 (Version)
494 "00" // version 0
495 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
496 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
497 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
498 // } end SEQUENCE (AlgorithmIdentifier)
499 "0422" // OCTET STRING length 0x22 (PrivateKey)
500 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
501 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
502 // } end SEQUENCE (PrivateKeyInfo)
503);
504string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
505
506/**
507 * X25519 key pair generated as follows:
508 * ```
509 * % openssl genpkey -algorithm X25519 > x25519_priv.key
510 * % cat x25519_priv.key
511 * -----BEGIN PRIVATE KEY-----
512 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
513 * -----END PRIVATE KEY-----
514 * % der2ascii -pem -i x25519_priv.key
515 * SEQUENCE {
516 * INTEGER { 0 }
517 * SEQUENCE {
518 * # x25519
519 * OBJECT_IDENTIFIER { 1.3.101.110 }
520 * }
521 * OCTET_STRING {
522 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
523 * }
524 * }
525 * ```
526 */
527
528string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
529string x25519_pkcs8_key = hex2str(
530 // RFC 5208 s5
531 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
532 "0201" // INTEGER length 1 (Version)
533 "00" // version 0
534 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
535 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
536 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
537 "0422" // OCTET STRING length 0x22 (PrivateKey)
538 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
539 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
540string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
541
Selene Huang31ab4042020-04-29 04:22:39 -0700542struct RSA_Delete {
543 void operator()(RSA* p) { RSA_free(p); }
544};
545
Selene Huang31ab4042020-04-29 04:22:39 -0700546std::string make_string(const uint8_t* data, size_t length) {
547 return std::string(reinterpret_cast<const char*>(data), length);
548}
549
550template <size_t N>
551std::string make_string(const uint8_t (&a)[N]) {
552 return make_string(a, N);
553}
554
555class AidlBuf : public vector<uint8_t> {
556 typedef vector<uint8_t> super;
557
558 public:
559 AidlBuf() {}
560 AidlBuf(const super& other) : super(other) {}
561 AidlBuf(super&& other) : super(std::move(other)) {}
562 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
563
564 AidlBuf& operator=(const super& other) {
565 super::operator=(other);
566 return *this;
567 }
568
569 AidlBuf& operator=(super&& other) {
570 super::operator=(std::move(other));
571 return *this;
572 }
573
574 AidlBuf& operator=(const string& other) {
575 resize(other.size());
576 for (size_t i = 0; i < other.size(); ++i) {
577 (*this)[i] = static_cast<uint8_t>(other[i]);
578 }
579 return *this;
580 }
581
582 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
583};
584
David Drysdale4dc01072021-04-01 12:17:35 +0100585string device_suffix(const string& name) {
586 size_t pos = name.find('/');
587 if (pos == string::npos) {
588 return name;
589 }
590 return name.substr(pos + 1);
591}
592
593bool matching_rp_instance(const string& km_name,
594 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
595 string km_suffix = device_suffix(km_name);
596
597 vector<string> rp_names =
598 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
599 for (const string& rp_name : rp_names) {
600 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
601 // KeyMint instance, assume they match.
602 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
603 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
604 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
605 return true;
606 }
607 }
608 return false;
609}
610
Selene Huang31ab4042020-04-29 04:22:39 -0700611} // namespace
612
613class NewKeyGenerationTest : public KeyMintAidlTestBase {
614 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700615 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000616 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700617 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700618
Selene Huang31ab4042020-04-29 04:22:39 -0700619 // Check that some unexpected tags/values are NOT present.
620 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
621 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000622 }
623
624 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
625 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
626 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
627 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
628
629 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000630 }
631
632 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
633 // TODO(swillden): Distinguish which params should be in which auth list.
634 AuthorizationSet auths;
635 for (auto& entry : keyCharacteristics) {
636 auths.push_back(AuthorizationSet(entry.authorizations));
637 }
638 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
639
640 // Verify that App data, ROT and auth timeout are NOT included.
641 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
642 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700643 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
644
David Drysdaled2cc8c22021-04-15 13:29:45 +0100645 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
646 // never adds it.
647 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
648
David Drysdale7de9feb2021-03-05 14:56:19 +0000649 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700650 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000651 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700652 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700653 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000654 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700655 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000656
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000657 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100658 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
659 EXPECT_TRUE(vendor_pl);
660 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000661
662 // Should include boot patchlevel (but there are some test scenarios where this is not
663 // possible).
664 if (check_boot_pl) {
665 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
666 EXPECT_TRUE(boot_pl);
667 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100668
David Drysdale7de9feb2021-03-05 14:56:19 +0000669 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700670 }
671};
672
673/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000674 * NewKeyGenerationTest.Aes
675 *
676 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
677 * have correct characteristics.
678 */
679TEST_P(NewKeyGenerationTest, Aes) {
680 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
681 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
682 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
683 SCOPED_TRACE(testing::Message()
684 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
685 vector<uint8_t> key_blob;
686 vector<KeyCharacteristics> key_characteristics;
687 auto builder = AuthorizationSetBuilder()
688 .AesEncryptionKey(key_size)
689 .BlockMode(block_mode)
690 .Padding(padding_mode)
691 .SetDefaultValidity();
692 if (block_mode == BlockMode::GCM) {
693 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
694 }
695 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
696
697 EXPECT_GT(key_blob.size(), 0U);
698 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100699 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000700
701 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
702
703 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
704 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
705 << "Key size " << key_size << "missing";
706
707 CheckedDeleteKey(&key_blob);
708 }
709 }
710 }
711}
712
713/*
714 * NewKeyGenerationTest.AesInvalidSize
715 *
716 * Verifies that specifying an invalid key size for AES key generation returns
717 * UNSUPPORTED_KEY_SIZE.
718 */
719TEST_P(NewKeyGenerationTest, AesInvalidSize) {
720 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
721 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
722 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
723 SCOPED_TRACE(testing::Message()
724 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
725 vector<uint8_t> key_blob;
726 vector<KeyCharacteristics> key_characteristics;
727 auto builder = AuthorizationSetBuilder()
728 .AesEncryptionKey(key_size)
729 .BlockMode(block_mode)
730 .Padding(padding_mode)
731 .SetDefaultValidity();
732 if (block_mode == BlockMode::GCM) {
733 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
734 }
735 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
736 GenerateKey(builder, &key_blob, &key_characteristics));
737 }
738 }
739 }
740
741 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
742 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
743 vector<uint8_t> key_blob;
744 vector<KeyCharacteristics> key_characteristics;
745 // No key size specified
746 auto builder = AuthorizationSetBuilder()
747 .Authorization(TAG_ALGORITHM, Algorithm::AES)
748 .BlockMode(block_mode)
749 .Padding(padding_mode)
750 .SetDefaultValidity();
751 if (block_mode == BlockMode::GCM) {
752 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
753 }
754 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
755 GenerateKey(builder, &key_blob, &key_characteristics));
756 }
757 }
758}
759
760/*
761 * NewKeyGenerationTest.AesInvalidPadding
762 *
763 * Verifies that specifying an invalid padding on AES keys gives a failure
764 * somewhere along the way.
765 */
766TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
767 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
768 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
769 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
770 SCOPED_TRACE(testing::Message()
771 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000772 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800773 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000774 .AesEncryptionKey(key_size)
775 .BlockMode(block_mode)
776 .Padding(padding_mode)
777 .SetDefaultValidity();
778 if (block_mode == BlockMode::GCM) {
779 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
780 }
781
Tommy Chiu3950b452021-05-03 22:01:46 +0800782 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000783 if (result == ErrorCode::OK) {
784 // Key creation was OK but has generated a key that cannot be used.
785 auto params =
786 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800787 if (block_mode == BlockMode::GCM) {
788 params.Authorization(TAG_MAC_LENGTH, 128);
789 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000790 auto result = Begin(KeyPurpose::ENCRYPT, params);
791 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100792 result == ErrorCode::INVALID_KEY_BLOB)
793 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000794 } else {
795 // The KeyMint implementation detected that the generated key
796 // is unusable.
797 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
798 }
799 }
800 }
801 }
802}
803
804/*
805 * NewKeyGenerationTest.AesGcmMissingMinMac
806 *
807 * Verifies that specifying an invalid key size for AES key generation returns
808 * UNSUPPORTED_KEY_SIZE.
809 */
810TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
811 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
812 BlockMode block_mode = BlockMode::GCM;
813 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
814 SCOPED_TRACE(testing::Message()
815 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
816 vector<uint8_t> key_blob;
817 vector<KeyCharacteristics> key_characteristics;
818 // No MIN_MAC_LENGTH provided.
819 auto builder = AuthorizationSetBuilder()
820 .AesEncryptionKey(key_size)
821 .BlockMode(block_mode)
822 .Padding(padding_mode)
823 .SetDefaultValidity();
824 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
825 GenerateKey(builder, &key_blob, &key_characteristics));
826 }
827 }
828}
829
830/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100831 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
832 *
833 * Verifies that specifying an invalid min MAC size for AES key generation returns
834 * UNSUPPORTED_MIN_MAC_LENGTH.
835 */
836TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
837 for (size_t min_mac_len : {88, 136}) {
838 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
839 BlockMode block_mode = BlockMode::GCM;
840 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
841 SCOPED_TRACE(testing::Message()
842 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
843 vector<uint8_t> key_blob;
844 vector<KeyCharacteristics> key_characteristics;
845 auto builder = AuthorizationSetBuilder()
846 .AesEncryptionKey(key_size)
847 .BlockMode(block_mode)
848 .Padding(padding_mode)
849 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
850 .SetDefaultValidity();
851 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
852 GenerateKey(builder, &key_blob, &key_characteristics));
853 }
854 }
855 }
856}
857
858/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000859 * NewKeyGenerationTest.TripleDes
860 *
861 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
862 * have correct characteristics.
863 */
864TEST_P(NewKeyGenerationTest, TripleDes) {
865 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
866 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
867 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
868 SCOPED_TRACE(testing::Message()
869 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
870 vector<uint8_t> key_blob;
871 vector<KeyCharacteristics> key_characteristics;
872 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
873 .TripleDesEncryptionKey(key_size)
874 .BlockMode(block_mode)
875 .Padding(padding_mode)
876 .Authorization(TAG_NO_AUTH_REQUIRED)
877 .SetDefaultValidity(),
878 &key_blob, &key_characteristics));
879
880 EXPECT_GT(key_blob.size(), 0U);
881 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100882 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000883
884 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
885
886 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
887 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
888 << "Key size " << key_size << "missing";
889
890 CheckedDeleteKey(&key_blob);
891 }
892 }
893 }
894}
895
896/*
897 * NewKeyGenerationTest.TripleDesWithAttestation
898 *
899 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
900 * have correct characteristics.
901 *
902 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
903 * put in a certificate) but which isn't an error.
904 */
905TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
906 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
907 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
908 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
909 SCOPED_TRACE(testing::Message()
910 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
911
912 auto challenge = "hello";
913 auto app_id = "foo";
914
915 vector<uint8_t> key_blob;
916 vector<KeyCharacteristics> key_characteristics;
917 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
918 .TripleDesEncryptionKey(key_size)
919 .BlockMode(block_mode)
920 .Padding(padding_mode)
921 .Authorization(TAG_NO_AUTH_REQUIRED)
922 .AttestationChallenge(challenge)
923 .AttestationApplicationId(app_id)
924 .SetDefaultValidity(),
925 &key_blob, &key_characteristics));
926
927 EXPECT_GT(key_blob.size(), 0U);
928 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100929 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000930
931 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
932
933 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
934 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
935 << "Key size " << key_size << "missing";
936
937 CheckedDeleteKey(&key_blob);
938 }
939 }
940 }
941}
942
943/*
944 * NewKeyGenerationTest.TripleDesInvalidSize
945 *
946 * Verifies that specifying an invalid key size for 3-DES key generation returns
947 * UNSUPPORTED_KEY_SIZE.
948 */
949TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
950 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
951 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
952 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
953 SCOPED_TRACE(testing::Message()
954 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
955 vector<uint8_t> key_blob;
956 vector<KeyCharacteristics> key_characteristics;
957 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
958 GenerateKey(AuthorizationSetBuilder()
959 .TripleDesEncryptionKey(key_size)
960 .BlockMode(block_mode)
961 .Padding(padding_mode)
962 .Authorization(TAG_NO_AUTH_REQUIRED)
963 .SetDefaultValidity(),
964 &key_blob, &key_characteristics));
965 }
966 }
967 }
968
969 // Omitting the key size fails.
970 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
971 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
972 SCOPED_TRACE(testing::Message()
973 << "3DES-default-" << block_mode << "-" << padding_mode);
974 vector<uint8_t> key_blob;
975 vector<KeyCharacteristics> key_characteristics;
976 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
977 GenerateKey(AuthorizationSetBuilder()
978 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
979 .BlockMode(block_mode)
980 .Padding(padding_mode)
981 .Authorization(TAG_NO_AUTH_REQUIRED)
982 .SetDefaultValidity(),
983 &key_blob, &key_characteristics));
984 }
985 }
986}
987
988/*
Selene Huang31ab4042020-04-29 04:22:39 -0700989 * NewKeyGenerationTest.Rsa
990 *
991 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
992 * have correct characteristics.
993 */
994TEST_P(NewKeyGenerationTest, Rsa) {
995 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
996 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700997 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700998 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
999 .RsaSigningKey(key_size, 65537)
1000 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001001 .Padding(PaddingMode::NONE)
1002 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001003 &key_blob, &key_characteristics));
1004
1005 ASSERT_GT(key_blob.size(), 0U);
1006 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001007 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001008
Shawn Willden7f424372021-01-10 18:06:50 -07001009 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001010
1011 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1012 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1013 << "Key size " << key_size << "missing";
1014 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1015
1016 CheckedDeleteKey(&key_blob);
1017 }
1018}
1019
1020/*
Qi Wud22ec842020-11-26 13:27:53 +08001021 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001022 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001023 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1024 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001025 */
1026TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001027 auto challenge = "hello";
1028 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001029
Selene Huang6e46f142021-04-20 19:20:11 -07001030 auto subject = "cert subj 2";
1031 vector<uint8_t> subject_der(make_name_from_str(subject));
1032
1033 uint64_t serial_int = 66;
1034 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1035
Selene Huang4f64c222021-04-13 19:54:36 -07001036 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001037 vector<uint8_t> key_blob;
1038 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001039 ASSERT_EQ(ErrorCode::OK,
1040 GenerateKey(AuthorizationSetBuilder()
1041 .RsaSigningKey(key_size, 65537)
1042 .Digest(Digest::NONE)
1043 .Padding(PaddingMode::NONE)
1044 .AttestationChallenge(challenge)
1045 .AttestationApplicationId(app_id)
1046 .Authorization(TAG_NO_AUTH_REQUIRED)
1047 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1048 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1049 .SetDefaultValidity(),
1050 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001051
1052 ASSERT_GT(key_blob.size(), 0U);
1053 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001054 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001055
1056 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1057
1058 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1059 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1060 << "Key size " << key_size << "missing";
1061 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1062
Selene Huang6e46f142021-04-20 19:20:11 -07001063 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001064 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001065 ASSERT_GT(cert_chain_.size(), 0);
1066
1067 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1068 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001069 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001070 sw_enforced, hw_enforced, SecLevel(),
1071 cert_chain_[0].encodedCertificate));
1072
1073 CheckedDeleteKey(&key_blob);
1074 }
1075}
1076
1077/*
David Drysdale4dc01072021-04-01 12:17:35 +01001078 * NewKeyGenerationTest.RsaWithRpkAttestation
1079 *
1080 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
1081 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale0fce69d2021-04-13 17:22:13 +01001082 *
1083 * This test is disabled because the KeyMint specification does not require that implementations
1084 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
1085 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +01001086 */
David Drysdale0fce69d2021-04-13 17:22:13 +01001087TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +01001088 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
1089 // instance.
1090 std::shared_ptr<IRemotelyProvisionedComponent> rp;
1091 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
1092 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
1093
1094 // Generate a P-256 keypair to use as an attestation key.
1095 MacedPublicKey macedPubKey;
1096 std::vector<uint8_t> privateKeyBlob;
1097 auto status =
1098 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1099 ASSERT_TRUE(status.isOk());
1100 vector<uint8_t> coseKeyData;
1101 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1102
1103 AttestationKey attestation_key;
1104 attestation_key.keyBlob = std::move(privateKeyBlob);
1105 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1106
1107 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1108 auto challenge = "hello";
1109 auto app_id = "foo";
1110
1111 vector<uint8_t> key_blob;
1112 vector<KeyCharacteristics> key_characteristics;
1113 ASSERT_EQ(ErrorCode::OK,
1114 GenerateKey(AuthorizationSetBuilder()
1115 .RsaSigningKey(key_size, 65537)
1116 .Digest(Digest::NONE)
1117 .Padding(PaddingMode::NONE)
1118 .AttestationChallenge(challenge)
1119 .AttestationApplicationId(app_id)
1120 .Authorization(TAG_NO_AUTH_REQUIRED)
1121 .SetDefaultValidity(),
1122 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1123
1124 ASSERT_GT(key_blob.size(), 0U);
1125 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001126 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001127
1128 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1129
1130 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1131 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1132 << "Key size " << key_size << "missing";
1133 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1134
1135 // Attestation by itself is not valid (last entry is not self-signed).
1136 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1137
1138 // The signature over the attested key should correspond to the P256 public key.
1139 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1140 ASSERT_TRUE(key_cert.get());
1141 EVP_PKEY_Ptr signing_pubkey;
1142 p256_pub_key(coseKeyData, &signing_pubkey);
1143 ASSERT_TRUE(signing_pubkey.get());
1144
1145 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1146 << "Verification of attested certificate failed "
1147 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1148
1149 CheckedDeleteKey(&key_blob);
1150 }
1151}
1152
1153/*
Selene Huang4f64c222021-04-13 19:54:36 -07001154 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1155 *
1156 * Verifies that keymint attestation for RSA encryption keys with challenge and
1157 * app id is also successful.
1158 */
1159TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1160 auto key_size = 2048;
1161 auto challenge = "hello";
1162 auto app_id = "foo";
1163
Selene Huang6e46f142021-04-20 19:20:11 -07001164 auto subject = "subj 2";
1165 vector<uint8_t> subject_der(make_name_from_str(subject));
1166
1167 uint64_t serial_int = 111166;
1168 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1169
Selene Huang4f64c222021-04-13 19:54:36 -07001170 vector<uint8_t> key_blob;
1171 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001172 ASSERT_EQ(ErrorCode::OK,
1173 GenerateKey(AuthorizationSetBuilder()
1174 .RsaEncryptionKey(key_size, 65537)
1175 .Padding(PaddingMode::NONE)
1176 .AttestationChallenge(challenge)
1177 .AttestationApplicationId(app_id)
1178 .Authorization(TAG_NO_AUTH_REQUIRED)
1179 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1180 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1181 .SetDefaultValidity(),
1182 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001183
1184 ASSERT_GT(key_blob.size(), 0U);
1185 AuthorizationSet auths;
1186 for (auto& entry : key_characteristics) {
1187 auths.push_back(AuthorizationSet(entry.authorizations));
1188 }
1189
1190 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1191 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1192
1193 // Verify that App data and ROT are NOT included.
1194 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1195 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1196
1197 // Check that some unexpected tags/values are NOT present.
1198 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1199 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1200
1201 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1202
1203 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1204 ASSERT_TRUE(os_ver);
1205 EXPECT_EQ(*os_ver, os_version());
1206
1207 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1208
1209 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1210 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1211 << "Key size " << key_size << "missing";
1212 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1213
Selene Huang6e46f142021-04-20 19:20:11 -07001214 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001215 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1216 ASSERT_GT(cert_chain_.size(), 0);
1217
1218 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1219 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001220 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001221 sw_enforced, hw_enforced, SecLevel(),
1222 cert_chain_[0].encodedCertificate));
1223
1224 CheckedDeleteKey(&key_blob);
1225}
1226
1227/*
1228 * NewKeyGenerationTest.RsaWithSelfSign
1229 *
1230 * Verifies that attesting to RSA key generation is successful, and returns
1231 * self signed certificate if no challenge is provided. And signing etc
1232 * works as expected.
1233 */
1234TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001235 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1236 vector<uint8_t> subject_der(make_name_from_str(subject));
1237
1238 uint64_t serial_int = 0;
1239 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1240
Selene Huang4f64c222021-04-13 19:54:36 -07001241 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1242 vector<uint8_t> key_blob;
1243 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001244 ASSERT_EQ(ErrorCode::OK,
1245 GenerateKey(AuthorizationSetBuilder()
1246 .RsaSigningKey(key_size, 65537)
1247 .Digest(Digest::NONE)
1248 .Padding(PaddingMode::NONE)
1249 .Authorization(TAG_NO_AUTH_REQUIRED)
1250 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1251 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1252 .SetDefaultValidity(),
1253 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001254
1255 ASSERT_GT(key_blob.size(), 0U);
1256 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001257 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001258
1259 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1260
1261 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1262 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1263 << "Key size " << key_size << "missing";
1264 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1265
Selene Huang6e46f142021-04-20 19:20:11 -07001266 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001267 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1268 ASSERT_EQ(cert_chain_.size(), 1);
1269
1270 CheckedDeleteKey(&key_blob);
1271 }
1272}
1273
1274/*
1275 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1276 *
1277 * Verifies that attesting to RSA checks for missing app ID.
1278 */
1279TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1280 auto challenge = "hello";
1281 vector<uint8_t> key_blob;
1282 vector<KeyCharacteristics> key_characteristics;
1283
1284 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1285 GenerateKey(AuthorizationSetBuilder()
1286 .RsaSigningKey(2048, 65537)
1287 .Digest(Digest::NONE)
1288 .Padding(PaddingMode::NONE)
1289 .AttestationChallenge(challenge)
1290 .Authorization(TAG_NO_AUTH_REQUIRED)
1291 .SetDefaultValidity(),
1292 &key_blob, &key_characteristics));
1293}
1294
1295/*
1296 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1297 *
1298 * Verifies that attesting to RSA ignores app id if challenge is missing.
1299 */
1300TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1301 auto key_size = 2048;
1302 auto app_id = "foo";
1303
Selene Huang6e46f142021-04-20 19:20:11 -07001304 auto subject = "cert subj 2";
1305 vector<uint8_t> subject_der(make_name_from_str(subject));
1306
1307 uint64_t serial_int = 1;
1308 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1309
Selene Huang4f64c222021-04-13 19:54:36 -07001310 vector<uint8_t> key_blob;
1311 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001312 ASSERT_EQ(ErrorCode::OK,
1313 GenerateKey(AuthorizationSetBuilder()
1314 .RsaSigningKey(key_size, 65537)
1315 .Digest(Digest::NONE)
1316 .Padding(PaddingMode::NONE)
1317 .AttestationApplicationId(app_id)
1318 .Authorization(TAG_NO_AUTH_REQUIRED)
1319 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1320 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1321 .SetDefaultValidity(),
1322 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001323
1324 ASSERT_GT(key_blob.size(), 0U);
1325 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001326 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001327
1328 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1329
1330 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1331 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1332 << "Key size " << key_size << "missing";
1333 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1334
Selene Huang6e46f142021-04-20 19:20:11 -07001335 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001336 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1337 ASSERT_EQ(cert_chain_.size(), 1);
1338
1339 CheckedDeleteKey(&key_blob);
1340}
1341
1342/*
Qi Wud22ec842020-11-26 13:27:53 +08001343 * NewKeyGenerationTest.LimitedUsageRsa
1344 *
1345 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1346 * resulting keys have correct characteristics.
1347 */
1348TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1349 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1350 vector<uint8_t> key_blob;
1351 vector<KeyCharacteristics> key_characteristics;
1352 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1353 .RsaSigningKey(key_size, 65537)
1354 .Digest(Digest::NONE)
1355 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001356 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1357 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001358 &key_blob, &key_characteristics));
1359
1360 ASSERT_GT(key_blob.size(), 0U);
1361 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001362 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001363
1364 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1365
1366 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1367 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1368 << "Key size " << key_size << "missing";
1369 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1370
1371 // Check the usage count limit tag appears in the authorizations.
1372 AuthorizationSet auths;
1373 for (auto& entry : key_characteristics) {
1374 auths.push_back(AuthorizationSet(entry.authorizations));
1375 }
1376 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1377 << "key usage count limit " << 1U << " missing";
1378
1379 CheckedDeleteKey(&key_blob);
1380 }
1381}
1382
1383/*
Qi Wubeefae42021-01-28 23:16:37 +08001384 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1385 *
1386 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1387 * resulting keys have correct characteristics and attestation.
1388 */
1389TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001390 auto challenge = "hello";
1391 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001392
Selene Huang6e46f142021-04-20 19:20:11 -07001393 auto subject = "cert subj 2";
1394 vector<uint8_t> subject_der(make_name_from_str(subject));
1395
1396 uint64_t serial_int = 66;
1397 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1398
Selene Huang4f64c222021-04-13 19:54:36 -07001399 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001400 vector<uint8_t> key_blob;
1401 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001402 ASSERT_EQ(ErrorCode::OK,
1403 GenerateKey(AuthorizationSetBuilder()
1404 .RsaSigningKey(key_size, 65537)
1405 .Digest(Digest::NONE)
1406 .Padding(PaddingMode::NONE)
1407 .AttestationChallenge(challenge)
1408 .AttestationApplicationId(app_id)
1409 .Authorization(TAG_NO_AUTH_REQUIRED)
1410 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1411 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1412 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1413 .SetDefaultValidity(),
1414 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001415
1416 ASSERT_GT(key_blob.size(), 0U);
1417 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001418 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001419
1420 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1421
1422 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1423 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1424 << "Key size " << key_size << "missing";
1425 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1426
1427 // Check the usage count limit tag appears in the authorizations.
1428 AuthorizationSet auths;
1429 for (auto& entry : key_characteristics) {
1430 auths.push_back(AuthorizationSet(entry.authorizations));
1431 }
1432 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1433 << "key usage count limit " << 1U << " missing";
1434
1435 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001436 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001437 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001438 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001439
1440 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1441 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001442 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001443 sw_enforced, hw_enforced, SecLevel(),
1444 cert_chain_[0].encodedCertificate));
1445
1446 CheckedDeleteKey(&key_blob);
1447 }
1448}
1449
1450/*
Selene Huang31ab4042020-04-29 04:22:39 -07001451 * NewKeyGenerationTest.NoInvalidRsaSizes
1452 *
1453 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1454 */
1455TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1456 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1457 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001458 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001459 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1460 GenerateKey(AuthorizationSetBuilder()
1461 .RsaSigningKey(key_size, 65537)
1462 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001463 .Padding(PaddingMode::NONE)
1464 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001465 &key_blob, &key_characteristics));
1466 }
1467}
1468
1469/*
1470 * NewKeyGenerationTest.RsaNoDefaultSize
1471 *
1472 * Verifies that failing to specify a key size for RSA key generation returns
1473 * UNSUPPORTED_KEY_SIZE.
1474 */
1475TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1476 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1477 GenerateKey(AuthorizationSetBuilder()
1478 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1479 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001480 .SigningKey()
1481 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001482}
1483
1484/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001485 * NewKeyGenerationTest.RsaMissingParams
1486 *
1487 * Verifies that omitting optional tags works.
1488 */
1489TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1490 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1491 ASSERT_EQ(ErrorCode::OK,
1492 GenerateKey(
1493 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1494 CheckedDeleteKey();
1495 }
1496}
1497
1498/*
Selene Huang31ab4042020-04-29 04:22:39 -07001499 * NewKeyGenerationTest.Ecdsa
1500 *
David Drysdale42fe1892021-10-14 14:43:46 +01001501 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001502 * have correct characteristics.
1503 */
1504TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001505 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001506 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001507 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001508 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001509 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001510 .Digest(Digest::NONE)
1511 .SetDefaultValidity(),
1512 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001513 ASSERT_GT(key_blob.size(), 0U);
1514 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001515 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001516
Shawn Willden7f424372021-01-10 18:06:50 -07001517 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001518
1519 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001520 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001521
1522 CheckedDeleteKey(&key_blob);
1523 }
1524}
1525
1526/*
David Drysdale42fe1892021-10-14 14:43:46 +01001527 * NewKeyGenerationTest.EcdsaCurve25519
1528 *
1529 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1530 * has correct characteristics.
1531 */
1532TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1533 if (!Curve25519Supported()) {
1534 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1535 }
1536
1537 EcCurve curve = EcCurve::CURVE_25519;
1538 vector<uint8_t> key_blob;
1539 vector<KeyCharacteristics> key_characteristics;
1540 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1541 .EcdsaSigningKey(curve)
1542 .Digest(Digest::NONE)
1543 .SetDefaultValidity(),
1544 &key_blob, &key_characteristics);
1545 ASSERT_EQ(result, ErrorCode::OK);
1546 ASSERT_GT(key_blob.size(), 0U);
1547
1548 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1549 ASSERT_GT(cert_chain_.size(), 0);
1550
1551 CheckBaseParams(key_characteristics);
1552 CheckCharacteristics(key_blob, key_characteristics);
1553
1554 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1555
1556 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1557 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1558
1559 CheckedDeleteKey(&key_blob);
1560}
1561
1562/*
1563 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1564 *
1565 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1566 * SIGN and AGREE_KEY.
1567 */
1568TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1569 if (!Curve25519Supported()) {
1570 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1571 }
1572
1573 EcCurve curve = EcCurve::CURVE_25519;
1574 vector<uint8_t> key_blob;
1575 vector<KeyCharacteristics> key_characteristics;
1576 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1577 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1578 .EcdsaSigningKey(curve)
1579 .Digest(Digest::NONE)
1580 .SetDefaultValidity(),
1581 &key_blob, &key_characteristics);
1582 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1583}
1584
1585/*
Selene Huang4f64c222021-04-13 19:54:36 -07001586 * NewKeyGenerationTest.EcdsaAttestation
1587 *
1588 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1589 * an attestation will be generated.
1590 */
1591TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1592 auto challenge = "hello";
1593 auto app_id = "foo";
1594
Selene Huang6e46f142021-04-20 19:20:11 -07001595 auto subject = "cert subj 2";
1596 vector<uint8_t> subject_der(make_name_from_str(subject));
1597
1598 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1599 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1600
David Drysdaledf09e542021-06-08 15:46:11 +01001601 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001602 vector<uint8_t> key_blob;
1603 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001604 ASSERT_EQ(ErrorCode::OK,
1605 GenerateKey(AuthorizationSetBuilder()
1606 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001607 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001608 .Digest(Digest::NONE)
1609 .AttestationChallenge(challenge)
1610 .AttestationApplicationId(app_id)
1611 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1612 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1613 .SetDefaultValidity(),
1614 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001615 ASSERT_GT(key_blob.size(), 0U);
1616 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001617 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001618
1619 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1620
1621 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001622 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001623
1624 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1625 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001626 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001627
1628 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1629 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001630 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001631 sw_enforced, hw_enforced, SecLevel(),
1632 cert_chain_[0].encodedCertificate));
1633
1634 CheckedDeleteKey(&key_blob);
1635 }
1636}
1637
1638/*
David Drysdale42fe1892021-10-14 14:43:46 +01001639 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1640 *
1641 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1642 * an attestation will be generated.
1643 */
1644TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1645 if (!Curve25519Supported()) {
1646 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1647 }
1648
1649 EcCurve curve = EcCurve::CURVE_25519;
1650 auto challenge = "hello";
1651 auto app_id = "foo";
1652
1653 auto subject = "cert subj 2";
1654 vector<uint8_t> subject_der(make_name_from_str(subject));
1655
1656 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1657 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1658
1659 vector<uint8_t> key_blob;
1660 vector<KeyCharacteristics> key_characteristics;
1661 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1662 .Authorization(TAG_NO_AUTH_REQUIRED)
1663 .EcdsaSigningKey(curve)
1664 .Digest(Digest::NONE)
1665 .AttestationChallenge(challenge)
1666 .AttestationApplicationId(app_id)
1667 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1668 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1669 .SetDefaultValidity(),
1670 &key_blob, &key_characteristics);
1671 ASSERT_EQ(ErrorCode::OK, result);
1672 ASSERT_GT(key_blob.size(), 0U);
1673 CheckBaseParams(key_characteristics);
1674 CheckCharacteristics(key_blob, key_characteristics);
1675
1676 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1677
1678 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1679 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1680
1681 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1682 ASSERT_GT(cert_chain_.size(), 0);
1683 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1684
1685 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1686 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1687 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1688 sw_enforced, hw_enforced, SecLevel(),
1689 cert_chain_[0].encodedCertificate));
1690
1691 CheckedDeleteKey(&key_blob);
1692}
1693
1694/*
David Drysdale37af4b32021-05-14 16:46:59 +01001695 * NewKeyGenerationTest.EcdsaAttestationTags
1696 *
1697 * Verifies that creation of an attested ECDSA key includes various tags in the
1698 * attestation extension.
1699 */
1700TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1701 auto challenge = "hello";
1702 auto app_id = "foo";
1703 auto subject = "cert subj 2";
1704 vector<uint8_t> subject_der(make_name_from_str(subject));
1705 uint64_t serial_int = 0x1010;
1706 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1707 const AuthorizationSetBuilder base_builder =
1708 AuthorizationSetBuilder()
1709 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001710 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001711 .Digest(Digest::NONE)
1712 .AttestationChallenge(challenge)
1713 .AttestationApplicationId(app_id)
1714 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1715 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1716 .SetDefaultValidity();
1717
1718 // Various tags that map to fields in the attestation extension ASN.1 schema.
1719 auto extra_tags = AuthorizationSetBuilder()
1720 .Authorization(TAG_ROLLBACK_RESISTANCE)
1721 .Authorization(TAG_EARLY_BOOT_ONLY)
1722 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1723 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1724 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1725 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1726 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1727 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1728 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1729 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1730 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1731 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001732
David Drysdale37af4b32021-05-14 16:46:59 +01001733 for (const KeyParameter& tag : extra_tags) {
1734 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1735 vector<uint8_t> key_blob;
1736 vector<KeyCharacteristics> key_characteristics;
1737 AuthorizationSetBuilder builder = base_builder;
1738 builder.push_back(tag);
1739 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1740 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1741 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1742 continue;
1743 }
Seth Mooreb393b082021-07-12 14:18:28 -07001744 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1745 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001746 continue;
1747 }
1748 ASSERT_EQ(result, ErrorCode::OK);
1749 ASSERT_GT(key_blob.size(), 0U);
1750
1751 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1752 ASSERT_GT(cert_chain_.size(), 0);
1753 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1754
1755 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1756 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001757 // Some tags are optional, so don't require them to be in the enforcements.
1758 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001759 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1760 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1761 }
1762
1763 // Verifying the attestation record will check for the specific tag because
1764 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001765 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1766 hw_enforced, SecLevel(),
1767 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01001768
1769 CheckedDeleteKey(&key_blob);
1770 }
1771
David Drysdalec53b7d92021-10-11 12:35:58 +01001772 // Collection of invalid attestation ID tags.
1773 auto invalid_tags =
1774 AuthorizationSetBuilder()
1775 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1776 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1777 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1778 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1779 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
1780 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
1781 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
1782 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01001783 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01001784 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01001785 vector<uint8_t> key_blob;
1786 vector<KeyCharacteristics> key_characteristics;
1787 AuthorizationSetBuilder builder =
1788 AuthorizationSetBuilder()
1789 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001790 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001791 .Digest(Digest::NONE)
1792 .AttestationChallenge(challenge)
1793 .AttestationApplicationId(app_id)
1794 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1795 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1796 .SetDefaultValidity();
1797 builder.push_back(tag);
1798 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1799 GenerateKey(builder, &key_blob, &key_characteristics));
1800 }
1801}
1802
1803/*
David Drysdalec53b7d92021-10-11 12:35:58 +01001804 * NewKeyGenerationTest.EcdsaAttestationIdTags
1805 *
1806 * Verifies that creation of an attested ECDSA key includes various ID tags in the
1807 * attestation extension.
1808 */
1809TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
1810 auto challenge = "hello";
1811 auto app_id = "foo";
1812 auto subject = "cert subj 2";
1813 vector<uint8_t> subject_der(make_name_from_str(subject));
1814 uint64_t serial_int = 0x1010;
1815 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1816 const AuthorizationSetBuilder base_builder =
1817 AuthorizationSetBuilder()
1818 .Authorization(TAG_NO_AUTH_REQUIRED)
1819 .EcdsaSigningKey(EcCurve::P_256)
1820 .Digest(Digest::NONE)
1821 .AttestationChallenge(challenge)
1822 .AttestationApplicationId(app_id)
1823 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1824 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1825 .SetDefaultValidity();
1826
1827 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
1828 auto extra_tags = AuthorizationSetBuilder();
1829 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
1830 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
1831 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
1832 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
1833 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
1834 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
1835
1836 for (const KeyParameter& tag : extra_tags) {
1837 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1838 vector<uint8_t> key_blob;
1839 vector<KeyCharacteristics> key_characteristics;
1840 AuthorizationSetBuilder builder = base_builder;
1841 builder.push_back(tag);
1842 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1843 if (result == ErrorCode::CANNOT_ATTEST_IDS) {
1844 // Device ID attestation is optional; KeyMint may not support it at all.
1845 continue;
1846 }
1847 ASSERT_EQ(result, ErrorCode::OK);
1848 ASSERT_GT(key_blob.size(), 0U);
1849
1850 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1851 ASSERT_GT(cert_chain_.size(), 0);
1852 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1853
1854 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1855 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1856
1857 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
1858 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
1859 // attestation extension should contain them, so make sure the extra tag is added.
1860 hw_enforced.push_back(tag);
1861
1862 // Verifying the attestation record will check for the specific tag because
1863 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001864 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1865 hw_enforced, SecLevel(),
1866 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01001867
1868 CheckedDeleteKey(&key_blob);
1869 }
1870}
1871
1872/*
David Drysdale565ccc72021-10-11 12:49:50 +01001873 * NewKeyGenerationTest.EcdsaAttestationUniqueId
1874 *
1875 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
1876 */
1877TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
1878 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00001879 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01001880 auto challenge = "hello";
1881 auto subject = "cert subj 2";
1882 vector<uint8_t> subject_der(make_name_from_str(subject));
1883 uint64_t serial_int = 0x1010;
1884 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00001885 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01001886 AuthorizationSetBuilder()
1887 .Authorization(TAG_NO_AUTH_REQUIRED)
1888 .Authorization(TAG_INCLUDE_UNIQUE_ID)
1889 .EcdsaSigningKey(EcCurve::P_256)
1890 .Digest(Digest::NONE)
1891 .AttestationChallenge(challenge)
1892 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1893 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1894 .AttestationApplicationId(app_id)
1895 .Authorization(TAG_CREATION_DATETIME, datetime)
1896 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00001897 if (reset) {
1898 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
1899 }
David Drysdale565ccc72021-10-11 12:49:50 +01001900
1901 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
1902 ASSERT_GT(key_blob_.size(), 0U);
1903
1904 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1905 ASSERT_GT(cert_chain_.size(), 0);
1906 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1907
1908 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
1909 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
1910
1911 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001912 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1913 hw_enforced, SecLevel(),
1914 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01001915 EXPECT_GT(unique_id->size(), 0);
1916 CheckedDeleteKey();
1917 };
1918
1919 // Generate unique ID
1920 auto app_id = "foo";
1921 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
1922 vector<uint8_t> unique_id;
1923 get_unique_id(app_id, cert_date, &unique_id);
1924
1925 // Generating a new key with the same parameters should give the same unique ID.
1926 vector<uint8_t> unique_id2;
1927 get_unique_id(app_id, cert_date, &unique_id2);
1928 EXPECT_EQ(unique_id, unique_id2);
1929
1930 // Generating a new key with a slightly different date should give the same unique ID.
1931 uint64_t rounded_date = cert_date / 2592000000LLU;
1932 uint64_t min_date = rounded_date * 2592000000LLU;
1933 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
1934
1935 vector<uint8_t> unique_id3;
1936 get_unique_id(app_id, min_date, &unique_id3);
1937 EXPECT_EQ(unique_id, unique_id3);
1938
1939 vector<uint8_t> unique_id4;
1940 get_unique_id(app_id, max_date, &unique_id4);
1941 EXPECT_EQ(unique_id, unique_id4);
1942
1943 // A different attestation application ID should yield a different unique ID.
1944 auto app_id2 = "different_foo";
1945 vector<uint8_t> unique_id5;
1946 get_unique_id(app_id2, cert_date, &unique_id5);
1947 EXPECT_NE(unique_id, unique_id5);
1948
1949 // A radically different date should yield a different unique ID.
1950 vector<uint8_t> unique_id6;
1951 get_unique_id(app_id, 1611621648000, &unique_id6);
1952 EXPECT_NE(unique_id, unique_id6);
1953
1954 vector<uint8_t> unique_id7;
1955 get_unique_id(app_id, max_date + 1, &unique_id7);
1956 EXPECT_NE(unique_id, unique_id7);
1957
1958 vector<uint8_t> unique_id8;
1959 get_unique_id(app_id, min_date - 1, &unique_id8);
1960 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00001961
1962 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
1963 vector<uint8_t> unique_id9;
1964 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
1965 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01001966}
1967
1968/*
David Drysdale37af4b32021-05-14 16:46:59 +01001969 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1970 *
1971 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1972 */
1973TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1974 auto challenge = "hello";
1975 auto attest_app_id = "foo";
1976 auto subject = "cert subj 2";
1977 vector<uint8_t> subject_der(make_name_from_str(subject));
1978 uint64_t serial_int = 0x1010;
1979 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1980
1981 // Earlier versions of the attestation extension schema included a slot:
1982 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1983 // This should never have been included, and should never be filled in.
1984 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1985 // to confirm that this field never makes it into the attestation extension.
1986 vector<uint8_t> key_blob;
1987 vector<KeyCharacteristics> key_characteristics;
1988 auto result = GenerateKey(AuthorizationSetBuilder()
1989 .Authorization(TAG_NO_AUTH_REQUIRED)
1990 .EcdsaSigningKey(EcCurve::P_256)
1991 .Digest(Digest::NONE)
1992 .AttestationChallenge(challenge)
1993 .AttestationApplicationId(attest_app_id)
1994 .Authorization(TAG_APPLICATION_ID, "client_id")
1995 .Authorization(TAG_APPLICATION_DATA, "appdata")
1996 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1997 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1998 .SetDefaultValidity(),
1999 &key_blob, &key_characteristics);
2000 ASSERT_EQ(result, ErrorCode::OK);
2001 ASSERT_GT(key_blob.size(), 0U);
2002
2003 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2004 ASSERT_GT(cert_chain_.size(), 0);
2005 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2006
2007 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2008 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002009 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2010 hw_enforced, SecLevel(),
2011 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002012
2013 // Check that the app id is not in the cert.
2014 string app_id = "clientid";
2015 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2016 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2017 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2018 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2019 cert_chain_[0].encodedCertificate.end());
2020
2021 CheckedDeleteKey(&key_blob);
2022}
2023
2024/*
Selene Huang4f64c222021-04-13 19:54:36 -07002025 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2026 *
2027 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2028 * the key will generate a self signed attestation.
2029 */
2030TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002031 auto subject = "cert subj 2";
2032 vector<uint8_t> subject_der(make_name_from_str(subject));
2033
2034 uint64_t serial_int = 0x123456FFF1234;
2035 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2036
David Drysdaledf09e542021-06-08 15:46:11 +01002037 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002038 vector<uint8_t> key_blob;
2039 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002040 ASSERT_EQ(ErrorCode::OK,
2041 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002042 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002043 .Digest(Digest::NONE)
2044 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2045 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2046 .SetDefaultValidity(),
2047 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002048 ASSERT_GT(key_blob.size(), 0U);
2049 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002050 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002051
2052 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2053
2054 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002055 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002056
2057 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07002058 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002059 ASSERT_EQ(cert_chain_.size(), 1);
2060
2061 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2062 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2063
2064 CheckedDeleteKey(&key_blob);
2065 }
2066}
2067
2068/*
2069 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2070 *
2071 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2072 * app id must also be provided or else it will fail.
2073 */
2074TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2075 auto challenge = "hello";
2076 vector<uint8_t> key_blob;
2077 vector<KeyCharacteristics> key_characteristics;
2078
2079 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
2080 GenerateKey(AuthorizationSetBuilder()
2081 .EcdsaSigningKey(EcCurve::P_256)
2082 .Digest(Digest::NONE)
2083 .AttestationChallenge(challenge)
2084 .SetDefaultValidity(),
2085 &key_blob, &key_characteristics));
2086}
2087
2088/*
2089 * NewKeyGenerationTest.EcdsaIgnoreAppId
2090 *
2091 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2092 * any appid will be ignored, and keymint will generate a self sign certificate.
2093 */
2094TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2095 auto app_id = "foo";
2096
David Drysdaledf09e542021-06-08 15:46:11 +01002097 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002098 vector<uint8_t> key_blob;
2099 vector<KeyCharacteristics> key_characteristics;
2100 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002101 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002102 .Digest(Digest::NONE)
2103 .AttestationApplicationId(app_id)
2104 .SetDefaultValidity(),
2105 &key_blob, &key_characteristics));
2106
2107 ASSERT_GT(key_blob.size(), 0U);
2108 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002109 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002110
2111 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2112
2113 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002114 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002115
2116 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2117 ASSERT_EQ(cert_chain_.size(), 1);
2118
2119 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2120 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2121
2122 CheckedDeleteKey(&key_blob);
2123 }
2124}
2125
2126/*
2127 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2128 *
2129 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2130 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2131 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2132 * to specify how many following bytes will be used to encode the length.
2133 */
2134TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2135 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002136 std::vector<uint32_t> app_id_lengths{143, 258};
2137
2138 for (uint32_t length : app_id_lengths) {
2139 const string app_id(length, 'a');
2140 vector<uint8_t> key_blob;
2141 vector<KeyCharacteristics> key_characteristics;
2142 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2143 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002144 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07002145 .Digest(Digest::NONE)
2146 .AttestationChallenge(challenge)
2147 .AttestationApplicationId(app_id)
2148 .SetDefaultValidity(),
2149 &key_blob, &key_characteristics));
2150 ASSERT_GT(key_blob.size(), 0U);
2151 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002152 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002153
2154 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2155
2156 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002157 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002158
2159 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2160 ASSERT_GT(cert_chain_.size(), 0);
2161
2162 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2163 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002164 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002165 sw_enforced, hw_enforced, SecLevel(),
2166 cert_chain_[0].encodedCertificate));
2167
2168 CheckedDeleteKey(&key_blob);
2169 }
2170}
2171
2172/*
Qi Wud22ec842020-11-26 13:27:53 +08002173 * NewKeyGenerationTest.LimitedUsageEcdsa
2174 *
2175 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2176 * resulting keys have correct characteristics.
2177 */
2178TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002179 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08002180 vector<uint8_t> key_blob;
2181 vector<KeyCharacteristics> key_characteristics;
2182 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002183 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002184 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002185 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2186 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002187 &key_blob, &key_characteristics));
2188
2189 ASSERT_GT(key_blob.size(), 0U);
2190 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002191 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002192
2193 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2194
2195 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002196 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002197
2198 // Check the usage count limit tag appears in the authorizations.
2199 AuthorizationSet auths;
2200 for (auto& entry : key_characteristics) {
2201 auths.push_back(AuthorizationSet(entry.authorizations));
2202 }
2203 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2204 << "key usage count limit " << 1U << " missing";
2205
2206 CheckedDeleteKey(&key_blob);
2207 }
2208}
2209
2210/*
Selene Huang31ab4042020-04-29 04:22:39 -07002211 * NewKeyGenerationTest.EcdsaDefaultSize
2212 *
David Drysdaledf09e542021-06-08 15:46:11 +01002213 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002214 * UNSUPPORTED_KEY_SIZE.
2215 */
2216TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2217 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2218 GenerateKey(AuthorizationSetBuilder()
2219 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2220 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002221 .Digest(Digest::NONE)
2222 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002223}
2224
2225/*
David Drysdale42fe1892021-10-14 14:43:46 +01002226 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002227 *
David Drysdale42fe1892021-10-14 14:43:46 +01002228 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002229 * UNSUPPORTED_KEY_SIZE.
2230 */
David Drysdale42fe1892021-10-14 14:43:46 +01002231TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002232 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07002233 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002234 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002235 auto result = GenerateKey(AuthorizationSetBuilder()
2236 .EcdsaSigningKey(curve)
2237 .Digest(Digest::NONE)
2238 .SetDefaultValidity(),
2239 &key_blob, &key_characteristics);
2240 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2241 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002242 }
2243
David Drysdaledf09e542021-06-08 15:46:11 +01002244 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2245 GenerateKey(AuthorizationSetBuilder()
2246 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2247 .Authorization(TAG_KEY_SIZE, 190)
2248 .SigningKey()
2249 .Digest(Digest::NONE)
2250 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002251}
2252
2253/*
2254 * NewKeyGenerationTest.EcdsaMismatchKeySize
2255 *
2256 * Verifies that specifying mismatched key size and curve for EC key generation returns
2257 * INVALID_ARGUMENT.
2258 */
2259TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002260 if (SecLevel() == SecurityLevel::STRONGBOX) {
2261 GTEST_SKIP() << "Test not applicable to StrongBox device";
2262 }
Selene Huang31ab4042020-04-29 04:22:39 -07002263
David Drysdaledf09e542021-06-08 15:46:11 +01002264 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002265 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002266 .Authorization(TAG_KEY_SIZE, 224)
2267 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002268 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002269 .Digest(Digest::NONE)
2270 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002271 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002272}
2273
2274/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002275 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002276 *
2277 * Verifies that keymint does not support any curve designated as unsupported.
2278 */
2279TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2280 Digest digest;
2281 if (SecLevel() == SecurityLevel::STRONGBOX) {
2282 digest = Digest::SHA_2_256;
2283 } else {
2284 digest = Digest::SHA_2_512;
2285 }
2286 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08002287 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2288 .EcdsaSigningKey(curve)
2289 .Digest(digest)
2290 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002291 << "Failed to generate key on curve: " << curve;
2292 CheckedDeleteKey();
2293 }
2294}
2295
2296/*
2297 * NewKeyGenerationTest.Hmac
2298 *
2299 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2300 * characteristics.
2301 */
2302TEST_P(NewKeyGenerationTest, Hmac) {
2303 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2304 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002305 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002306 constexpr size_t key_size = 128;
2307 ASSERT_EQ(ErrorCode::OK,
2308 GenerateKey(
2309 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2310 TAG_MIN_MAC_LENGTH, 128),
2311 &key_blob, &key_characteristics));
2312
2313 ASSERT_GT(key_blob.size(), 0U);
2314 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002315 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002316
Shawn Willden7f424372021-01-10 18:06:50 -07002317 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2318 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2319 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2320 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002321
2322 CheckedDeleteKey(&key_blob);
2323 }
2324}
2325
2326/*
Selene Huang4f64c222021-04-13 19:54:36 -07002327 * NewKeyGenerationTest.HmacNoAttestation
2328 *
2329 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2330 * and app id are provided.
2331 */
2332TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2333 auto challenge = "hello";
2334 auto app_id = "foo";
2335
2336 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2337 vector<uint8_t> key_blob;
2338 vector<KeyCharacteristics> key_characteristics;
2339 constexpr size_t key_size = 128;
2340 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2341 .HmacKey(key_size)
2342 .Digest(digest)
2343 .AttestationChallenge(challenge)
2344 .AttestationApplicationId(app_id)
2345 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2346 &key_blob, &key_characteristics));
2347
2348 ASSERT_GT(key_blob.size(), 0U);
2349 ASSERT_EQ(cert_chain_.size(), 0);
2350 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002351 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002352
2353 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2354 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2355 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2356 << "Key size " << key_size << "missing";
2357
2358 CheckedDeleteKey(&key_blob);
2359 }
2360}
2361
2362/*
Qi Wud22ec842020-11-26 13:27:53 +08002363 * NewKeyGenerationTest.LimitedUsageHmac
2364 *
2365 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2366 * resulting keys have correct characteristics.
2367 */
2368TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2369 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2370 vector<uint8_t> key_blob;
2371 vector<KeyCharacteristics> key_characteristics;
2372 constexpr size_t key_size = 128;
2373 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2374 .HmacKey(key_size)
2375 .Digest(digest)
2376 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2377 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2378 &key_blob, &key_characteristics));
2379
2380 ASSERT_GT(key_blob.size(), 0U);
2381 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002382 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002383
2384 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2385 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2386 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2387 << "Key size " << key_size << "missing";
2388
2389 // Check the usage count limit tag appears in the authorizations.
2390 AuthorizationSet auths;
2391 for (auto& entry : key_characteristics) {
2392 auths.push_back(AuthorizationSet(entry.authorizations));
2393 }
2394 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2395 << "key usage count limit " << 1U << " missing";
2396
2397 CheckedDeleteKey(&key_blob);
2398 }
2399}
2400
2401/*
Selene Huang31ab4042020-04-29 04:22:39 -07002402 * NewKeyGenerationTest.HmacCheckKeySizes
2403 *
2404 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2405 */
2406TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2407 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2408 if (key_size < 64 || key_size % 8 != 0) {
2409 // To keep this test from being very slow, we only test a random fraction of
2410 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2411 // them, we expect to run ~40 of them in each run.
2412 if (key_size % 8 == 0 || random() % 10 == 0) {
2413 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2414 GenerateKey(AuthorizationSetBuilder()
2415 .HmacKey(key_size)
2416 .Digest(Digest::SHA_2_256)
2417 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2418 << "HMAC key size " << key_size << " invalid";
2419 }
2420 } else {
2421 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2422 .HmacKey(key_size)
2423 .Digest(Digest::SHA_2_256)
2424 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2425 << "Failed to generate HMAC key of size " << key_size;
2426 CheckedDeleteKey();
2427 }
2428 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002429 if (SecLevel() == SecurityLevel::STRONGBOX) {
2430 // STRONGBOX devices must not support keys larger than 512 bits.
2431 size_t key_size = 520;
2432 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2433 GenerateKey(AuthorizationSetBuilder()
2434 .HmacKey(key_size)
2435 .Digest(Digest::SHA_2_256)
2436 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2437 << "HMAC key size " << key_size << " unexpectedly valid";
2438 }
Selene Huang31ab4042020-04-29 04:22:39 -07002439}
2440
2441/*
2442 * NewKeyGenerationTest.HmacCheckMinMacLengths
2443 *
2444 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2445 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2446 * specific MAC length that failed, so reproducing a failed run will be easy.
2447 */
2448TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2449 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2450 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2451 // To keep this test from being very long, we only test a random fraction of
2452 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2453 // we expect to run ~17 of them in each run.
2454 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2455 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2456 GenerateKey(AuthorizationSetBuilder()
2457 .HmacKey(128)
2458 .Digest(Digest::SHA_2_256)
2459 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2460 << "HMAC min mac length " << min_mac_length << " invalid.";
2461 }
2462 } else {
2463 EXPECT_EQ(ErrorCode::OK,
2464 GenerateKey(AuthorizationSetBuilder()
2465 .HmacKey(128)
2466 .Digest(Digest::SHA_2_256)
2467 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2468 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2469 CheckedDeleteKey();
2470 }
2471 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002472
2473 // Minimum MAC length must be no more than 512 bits.
2474 size_t min_mac_length = 520;
2475 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2476 GenerateKey(AuthorizationSetBuilder()
2477 .HmacKey(128)
2478 .Digest(Digest::SHA_2_256)
2479 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2480 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002481}
2482
2483/*
2484 * NewKeyGenerationTest.HmacMultipleDigests
2485 *
2486 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2487 */
2488TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002489 if (SecLevel() == SecurityLevel::STRONGBOX) {
2490 GTEST_SKIP() << "Test not applicable to StrongBox device";
2491 }
Selene Huang31ab4042020-04-29 04:22:39 -07002492
2493 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2494 GenerateKey(AuthorizationSetBuilder()
2495 .HmacKey(128)
2496 .Digest(Digest::SHA1)
2497 .Digest(Digest::SHA_2_256)
2498 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2499}
2500
2501/*
2502 * NewKeyGenerationTest.HmacDigestNone
2503 *
2504 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2505 */
2506TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2507 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2508 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2509 128)));
2510
2511 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2512 GenerateKey(AuthorizationSetBuilder()
2513 .HmacKey(128)
2514 .Digest(Digest::NONE)
2515 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2516}
2517
Selene Huang4f64c222021-04-13 19:54:36 -07002518/*
2519 * NewKeyGenerationTest.AesNoAttestation
2520 *
2521 * Verifies that attestation parameters to AES keys are ignored and generateKey
2522 * will succeed.
2523 */
2524TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2525 auto challenge = "hello";
2526 auto app_id = "foo";
2527
2528 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2529 .Authorization(TAG_NO_AUTH_REQUIRED)
2530 .AesEncryptionKey(128)
2531 .EcbMode()
2532 .Padding(PaddingMode::PKCS7)
2533 .AttestationChallenge(challenge)
2534 .AttestationApplicationId(app_id)));
2535
2536 ASSERT_EQ(cert_chain_.size(), 0);
2537}
2538
2539/*
2540 * NewKeyGenerationTest.TripleDesNoAttestation
2541 *
2542 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2543 * will be successful. No attestation should be generated.
2544 */
2545TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2546 auto challenge = "hello";
2547 auto app_id = "foo";
2548
2549 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2550 .TripleDesEncryptionKey(168)
2551 .BlockMode(BlockMode::ECB)
2552 .Authorization(TAG_NO_AUTH_REQUIRED)
2553 .Padding(PaddingMode::NONE)
2554 .AttestationChallenge(challenge)
2555 .AttestationApplicationId(app_id)));
2556 ASSERT_EQ(cert_chain_.size(), 0);
2557}
2558
Selene Huang31ab4042020-04-29 04:22:39 -07002559INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2560
2561typedef KeyMintAidlTestBase SigningOperationsTest;
2562
2563/*
2564 * SigningOperationsTest.RsaSuccess
2565 *
2566 * Verifies that raw RSA signature operations succeed.
2567 */
2568TEST_P(SigningOperationsTest, RsaSuccess) {
2569 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2570 .RsaSigningKey(2048, 65537)
2571 .Digest(Digest::NONE)
2572 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002573 .Authorization(TAG_NO_AUTH_REQUIRED)
2574 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002575 string message = "12345678901234567890123456789012";
2576 string signature = SignMessage(
2577 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002578 LocalVerifyMessage(message, signature,
2579 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2580}
2581
2582/*
2583 * SigningOperationsTest.RsaAllPaddingsAndDigests
2584 *
2585 * Verifies RSA signature/verification for all padding modes and digests.
2586 */
2587TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2588 auto authorizations = AuthorizationSetBuilder()
2589 .Authorization(TAG_NO_AUTH_REQUIRED)
2590 .RsaSigningKey(2048, 65537)
2591 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2592 .Padding(PaddingMode::NONE)
2593 .Padding(PaddingMode::RSA_PSS)
2594 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2595 .SetDefaultValidity();
2596
2597 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2598
2599 string message(128, 'a');
2600 string corrupt_message(message);
2601 ++corrupt_message[corrupt_message.size() / 2];
2602
2603 for (auto padding :
2604 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2605 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2606 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2607 // Digesting only makes sense with padding.
2608 continue;
2609 }
2610
2611 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2612 // PSS requires digesting.
2613 continue;
2614 }
2615
2616 string signature =
2617 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2618 LocalVerifyMessage(message, signature,
2619 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2620 }
2621 }
Selene Huang31ab4042020-04-29 04:22:39 -07002622}
2623
2624/*
2625 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2626 *
Shawn Willden7f424372021-01-10 18:06:50 -07002627 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002628 */
2629TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2630 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2631 .Authorization(TAG_NO_AUTH_REQUIRED)
2632 .RsaSigningKey(2048, 65537)
2633 .Digest(Digest::NONE)
2634 .Padding(PaddingMode::NONE)
2635 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002636 .Authorization(TAG_APPLICATION_DATA, "appdata")
2637 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002638
2639 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2640
Selene Huang31ab4042020-04-29 04:22:39 -07002641 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2642 Begin(KeyPurpose::SIGN,
2643 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2644 AbortIfNeeded();
2645 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2646 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2647 .Digest(Digest::NONE)
2648 .Padding(PaddingMode::NONE)
2649 .Authorization(TAG_APPLICATION_ID, "clientid")));
2650 AbortIfNeeded();
2651 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2652 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2653 .Digest(Digest::NONE)
2654 .Padding(PaddingMode::NONE)
2655 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2656 AbortIfNeeded();
2657 EXPECT_EQ(ErrorCode::OK,
2658 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2659 .Digest(Digest::NONE)
2660 .Padding(PaddingMode::NONE)
2661 .Authorization(TAG_APPLICATION_DATA, "appdata")
2662 .Authorization(TAG_APPLICATION_ID, "clientid")));
2663 AbortIfNeeded();
2664}
2665
2666/*
2667 * SigningOperationsTest.RsaPssSha256Success
2668 *
2669 * Verifies that RSA-PSS signature operations succeed.
2670 */
2671TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2672 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2673 .RsaSigningKey(2048, 65537)
2674 .Digest(Digest::SHA_2_256)
2675 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002676 .Authorization(TAG_NO_AUTH_REQUIRED)
2677 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002678 // Use large message, which won't work without digesting.
2679 string message(1024, 'a');
2680 string signature = SignMessage(
2681 message,
2682 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2683}
2684
2685/*
2686 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2687 *
2688 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2689 * supports only unpadded operations.
2690 */
2691TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2692 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2693 .RsaSigningKey(2048, 65537)
2694 .Digest(Digest::NONE)
2695 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002696 .Padding(PaddingMode::NONE)
2697 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002698 string message = "12345678901234567890123456789012";
2699 string signature;
2700
2701 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2702 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2703 .Digest(Digest::NONE)
2704 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2705}
2706
2707/*
2708 * SigningOperationsTest.NoUserConfirmation
2709 *
2710 * Verifies that keymint rejects signing operations for keys with
2711 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2712 * presented.
2713 */
2714TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002715 if (SecLevel() == SecurityLevel::STRONGBOX) {
2716 GTEST_SKIP() << "Test not applicable to StrongBox device";
2717 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002718 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2719 .RsaSigningKey(1024, 65537)
2720 .Digest(Digest::NONE)
2721 .Padding(PaddingMode::NONE)
2722 .Authorization(TAG_NO_AUTH_REQUIRED)
2723 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2724 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002725
2726 const string message = "12345678901234567890123456789012";
2727 EXPECT_EQ(ErrorCode::OK,
2728 Begin(KeyPurpose::SIGN,
2729 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2730 string signature;
2731 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2732}
2733
2734/*
2735 * SigningOperationsTest.RsaPkcs1Sha256Success
2736 *
2737 * Verifies that digested RSA-PKCS1 signature operations succeed.
2738 */
2739TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2740 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2741 .RsaSigningKey(2048, 65537)
2742 .Digest(Digest::SHA_2_256)
2743 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002744 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2745 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002746 string message(1024, 'a');
2747 string signature = SignMessage(message, AuthorizationSetBuilder()
2748 .Digest(Digest::SHA_2_256)
2749 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2750}
2751
2752/*
2753 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2754 *
2755 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2756 */
2757TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2758 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2759 .RsaSigningKey(2048, 65537)
2760 .Digest(Digest::NONE)
2761 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002762 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2763 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002764 string message(53, 'a');
2765 string signature = SignMessage(message, AuthorizationSetBuilder()
2766 .Digest(Digest::NONE)
2767 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2768}
2769
2770/*
2771 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2772 *
2773 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2774 * given a too-long message.
2775 */
2776TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2777 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2778 .RsaSigningKey(2048, 65537)
2779 .Digest(Digest::NONE)
2780 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002781 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2782 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002783 string message(257, 'a');
2784
2785 EXPECT_EQ(ErrorCode::OK,
2786 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2787 .Digest(Digest::NONE)
2788 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2789 string signature;
2790 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2791}
2792
2793/*
2794 * SigningOperationsTest.RsaPssSha512TooSmallKey
2795 *
2796 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2797 * used with a key that is too small for the message.
2798 *
2799 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2800 * keymint specification requires that salt_size == digest_size, so the message will be
2801 * digest_size * 2 +
2802 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2803 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2804 * for a 1024-bit key.
2805 */
2806TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01002807 if (SecLevel() == SecurityLevel::STRONGBOX) {
2808 GTEST_SKIP() << "Test not applicable to StrongBox device";
2809 }
Selene Huang31ab4042020-04-29 04:22:39 -07002810 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2811 .RsaSigningKey(1024, 65537)
2812 .Digest(Digest::SHA_2_512)
2813 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002814 .Padding(PaddingMode::RSA_PSS)
2815 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002816 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2817 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2818 .Digest(Digest::SHA_2_512)
2819 .Padding(PaddingMode::RSA_PSS)));
2820}
2821
2822/*
2823 * SigningOperationsTest.RsaNoPaddingTooLong
2824 *
2825 * Verifies that raw RSA signature operations fail with the correct error code when
2826 * given a too-long message.
2827 */
2828TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2829 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2830 .RsaSigningKey(2048, 65537)
2831 .Digest(Digest::NONE)
2832 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002833 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2834 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002835 // One byte too long
2836 string message(2048 / 8 + 1, 'a');
2837 ASSERT_EQ(ErrorCode::OK,
2838 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2839 .Digest(Digest::NONE)
2840 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2841 string result;
2842 ErrorCode finish_error_code = Finish(message, &result);
2843 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2844 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2845
2846 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2847 message = string(128 * 1024, 'a');
2848 ASSERT_EQ(ErrorCode::OK,
2849 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2850 .Digest(Digest::NONE)
2851 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2852 finish_error_code = Finish(message, &result);
2853 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2854 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2855}
2856
2857/*
2858 * SigningOperationsTest.RsaAbort
2859 *
2860 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2861 * test, but the behavior should be algorithm and purpose-independent.
2862 */
2863TEST_P(SigningOperationsTest, RsaAbort) {
2864 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2865 .RsaSigningKey(2048, 65537)
2866 .Digest(Digest::NONE)
2867 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002868 .Padding(PaddingMode::NONE)
2869 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002870
2871 ASSERT_EQ(ErrorCode::OK,
2872 Begin(KeyPurpose::SIGN,
2873 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2874 EXPECT_EQ(ErrorCode::OK, Abort());
2875
2876 // Another abort should fail
2877 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2878
2879 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002880 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002881}
2882
2883/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002884 * SigningOperationsTest.RsaNonUniqueParams
2885 *
2886 * Verifies that an operation with multiple padding modes is rejected.
2887 */
2888TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2889 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2890 .RsaSigningKey(2048, 65537)
2891 .Digest(Digest::NONE)
2892 .Digest(Digest::SHA1)
2893 .Authorization(TAG_NO_AUTH_REQUIRED)
2894 .Padding(PaddingMode::NONE)
2895 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2896 .SetDefaultValidity()));
2897
2898 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2899 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2900 .Digest(Digest::NONE)
2901 .Padding(PaddingMode::NONE)
2902 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2903
Tommy Chiuc93c4392021-05-11 18:36:50 +08002904 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2905 .Digest(Digest::NONE)
2906 .Digest(Digest::SHA1)
2907 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2908 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002909
2910 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2911 Begin(KeyPurpose::SIGN,
2912 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2913}
2914
2915/*
Selene Huang31ab4042020-04-29 04:22:39 -07002916 * SigningOperationsTest.RsaUnsupportedPadding
2917 *
2918 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2919 * with a padding mode inappropriate for RSA.
2920 */
2921TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2922 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2923 .RsaSigningKey(2048, 65537)
2924 .Authorization(TAG_NO_AUTH_REQUIRED)
2925 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002926 .Padding(PaddingMode::PKCS7)
2927 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002928 ASSERT_EQ(
2929 ErrorCode::UNSUPPORTED_PADDING_MODE,
2930 Begin(KeyPurpose::SIGN,
2931 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002932 CheckedDeleteKey();
2933
2934 ASSERT_EQ(ErrorCode::OK,
2935 GenerateKey(
2936 AuthorizationSetBuilder()
2937 .RsaSigningKey(2048, 65537)
2938 .Authorization(TAG_NO_AUTH_REQUIRED)
2939 .Digest(Digest::SHA_2_256 /* supported digest */)
2940 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2941 .SetDefaultValidity()));
2942 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2943 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2944 .Digest(Digest::SHA_2_256)
2945 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002946}
2947
2948/*
2949 * SigningOperationsTest.RsaPssNoDigest
2950 *
2951 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2952 */
2953TEST_P(SigningOperationsTest, RsaNoDigest) {
2954 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2955 .RsaSigningKey(2048, 65537)
2956 .Authorization(TAG_NO_AUTH_REQUIRED)
2957 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002958 .Padding(PaddingMode::RSA_PSS)
2959 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002960 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2961 Begin(KeyPurpose::SIGN,
2962 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2963
2964 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2965 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2966}
2967
2968/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002969 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002970 *
2971 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2972 * supported in some cases (as validated in other tests), but a mode must be specified.
2973 */
2974TEST_P(SigningOperationsTest, RsaNoPadding) {
2975 // Padding must be specified
2976 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2977 .RsaKey(2048, 65537)
2978 .Authorization(TAG_NO_AUTH_REQUIRED)
2979 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002980 .Digest(Digest::NONE)
2981 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002982 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2983 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2984}
2985
2986/*
2987 * SigningOperationsTest.RsaShortMessage
2988 *
2989 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2990 */
2991TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2992 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2993 .Authorization(TAG_NO_AUTH_REQUIRED)
2994 .RsaSigningKey(2048, 65537)
2995 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002996 .Padding(PaddingMode::NONE)
2997 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002998
2999 // Barely shorter
3000 string message(2048 / 8 - 1, 'a');
3001 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3002
3003 // Much shorter
3004 message = "a";
3005 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3006}
3007
3008/*
3009 * SigningOperationsTest.RsaSignWithEncryptionKey
3010 *
3011 * Verifies that RSA encryption keys cannot be used to sign.
3012 */
3013TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3014 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3015 .Authorization(TAG_NO_AUTH_REQUIRED)
3016 .RsaEncryptionKey(2048, 65537)
3017 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003018 .Padding(PaddingMode::NONE)
3019 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003020 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3021 Begin(KeyPurpose::SIGN,
3022 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3023}
3024
3025/*
3026 * SigningOperationsTest.RsaSignTooLargeMessage
3027 *
3028 * Verifies that attempting a raw signature of a message which is the same length as the key,
3029 * but numerically larger than the public modulus, fails with the correct error.
3030 */
3031TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3032 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3033 .Authorization(TAG_NO_AUTH_REQUIRED)
3034 .RsaSigningKey(2048, 65537)
3035 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003036 .Padding(PaddingMode::NONE)
3037 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003038
3039 // Largest possible message will always be larger than the public modulus.
3040 string message(2048 / 8, static_cast<char>(0xff));
3041 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3042 .Authorization(TAG_NO_AUTH_REQUIRED)
3043 .Digest(Digest::NONE)
3044 .Padding(PaddingMode::NONE)));
3045 string signature;
3046 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3047}
3048
3049/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003050 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3051 *
David Drysdale42fe1892021-10-14 14:43:46 +01003052 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003053 */
3054TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003055
3056 string message = "1234567890";
3057 string corrupt_message = "2234567890";
3058 for (auto curve : ValidCurves()) {
3059 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003060 // Ed25519 only allows Digest::NONE.
3061 auto digests = (curve == EcCurve::CURVE_25519)
3062 ? std::vector<Digest>(1, Digest::NONE)
3063 : ValidDigests(true /* withNone */, false /* withMD5 */);
3064
David Drysdaledf8f52e2021-05-06 08:10:58 +01003065 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3066 .Authorization(TAG_NO_AUTH_REQUIRED)
3067 .EcdsaSigningKey(curve)
3068 .Digest(digests)
3069 .SetDefaultValidity());
3070 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3071 if (error != ErrorCode::OK) {
3072 continue;
3073 }
3074
3075 for (auto digest : digests) {
3076 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3077 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3078 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3079 }
3080
3081 auto rc = DeleteKey();
3082 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3083 }
3084}
3085
3086/*
Selene Huang31ab4042020-04-29 04:22:39 -07003087 * SigningOperationsTest.EcdsaAllCurves
3088 *
David Drysdale42fe1892021-10-14 14:43:46 +01003089 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003090 */
3091TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3092 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003093 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3094 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003095 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3096 .Authorization(TAG_NO_AUTH_REQUIRED)
3097 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003098 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003099 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003100 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3101 if (error != ErrorCode::OK) continue;
3102
3103 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003104 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003105 CheckedDeleteKey();
3106 }
3107}
3108
3109/*
David Drysdale42fe1892021-10-14 14:43:46 +01003110 * SigningOperationsTest.EcdsaCurve25519
3111 *
3112 * Verifies that ECDSA operations succeed with curve25519.
3113 */
3114TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3115 if (!Curve25519Supported()) {
3116 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3117 }
3118
3119 EcCurve curve = EcCurve::CURVE_25519;
3120 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3121 .Authorization(TAG_NO_AUTH_REQUIRED)
3122 .EcdsaSigningKey(curve)
3123 .Digest(Digest::NONE)
3124 .SetDefaultValidity());
3125 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3126
3127 string message(1024, 'a');
3128 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3129 CheckedDeleteKey();
3130}
3131
3132/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003133 * SigningOperationsTest.EcdsaCurve25519MaxSize
3134 *
3135 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3136 */
3137TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3138 if (!Curve25519Supported()) {
3139 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3140 }
3141
3142 EcCurve curve = EcCurve::CURVE_25519;
3143 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3144 .Authorization(TAG_NO_AUTH_REQUIRED)
3145 .EcdsaSigningKey(curve)
3146 .Digest(Digest::NONE)
3147 .SetDefaultValidity());
3148 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3149
3150 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3151
3152 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3153 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3154 string message(msg_size, 'a');
3155
3156 // Attempt to sign via Begin+Finish.
3157 AuthorizationSet out_params;
3158 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3159 EXPECT_TRUE(out_params.empty());
3160 string signature;
3161 auto result = Finish(message, &signature);
3162 EXPECT_EQ(result, ErrorCode::OK);
3163 LocalVerifyMessage(message, signature, params);
3164
3165 // Attempt to sign via Begin+Update+Finish
3166 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3167 EXPECT_TRUE(out_params.empty());
3168 string output;
3169 result = Update(message, &output);
3170 EXPECT_EQ(result, ErrorCode::OK);
3171 EXPECT_EQ(output.size(), 0);
3172 string signature2;
3173 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3174 LocalVerifyMessage(message, signature2, params);
3175 }
3176
3177 CheckedDeleteKey();
3178}
3179
3180/*
3181 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3182 *
3183 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3184 */
3185TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3186 if (!Curve25519Supported()) {
3187 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3188 }
3189
3190 EcCurve curve = EcCurve::CURVE_25519;
3191 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3192 .Authorization(TAG_NO_AUTH_REQUIRED)
3193 .EcdsaSigningKey(curve)
3194 .Digest(Digest::NONE)
3195 .SetDefaultValidity());
3196 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3197
3198 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3199
3200 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3201 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3202 string message(msg_size, 'a');
3203
3204 // Attempt to sign via Begin+Finish.
3205 AuthorizationSet out_params;
3206 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3207 EXPECT_TRUE(out_params.empty());
3208 string signature;
3209 auto result = Finish(message, &signature);
3210 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3211
3212 // Attempt to sign via Begin+Update (but never get to Finish)
3213 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3214 EXPECT_TRUE(out_params.empty());
3215 string output;
3216 result = Update(message, &output);
3217 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3218 }
3219
3220 CheckedDeleteKey();
3221}
3222
3223/*
Selene Huang31ab4042020-04-29 04:22:39 -07003224 * SigningOperationsTest.EcdsaNoDigestHugeData
3225 *
3226 * Verifies that ECDSA operations support very large messages, even without digesting. This
3227 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3228 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3229 * the framework.
3230 */
3231TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3232 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3233 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003234 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003235 .Digest(Digest::NONE)
3236 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003237 string message(1 * 1024, 'a');
3238 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3239}
3240
3241/*
3242 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3243 *
3244 * Verifies that using an EC key requires the correct app ID/data.
3245 */
3246TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3247 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3248 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003249 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003250 .Digest(Digest::NONE)
3251 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003252 .Authorization(TAG_APPLICATION_DATA, "appdata")
3253 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003254
3255 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3256
Selene Huang31ab4042020-04-29 04:22:39 -07003257 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3258 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3259 AbortIfNeeded();
3260 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3261 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3262 .Digest(Digest::NONE)
3263 .Authorization(TAG_APPLICATION_ID, "clientid")));
3264 AbortIfNeeded();
3265 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3266 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3267 .Digest(Digest::NONE)
3268 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3269 AbortIfNeeded();
3270 EXPECT_EQ(ErrorCode::OK,
3271 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3272 .Digest(Digest::NONE)
3273 .Authorization(TAG_APPLICATION_DATA, "appdata")
3274 .Authorization(TAG_APPLICATION_ID, "clientid")));
3275 AbortIfNeeded();
3276}
3277
3278/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003279 * SigningOperationsTest.EcdsaIncompatibleDigest
3280 *
3281 * Verifies that using an EC key requires compatible digest.
3282 */
3283TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3284 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3285 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003286 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003287 .Digest(Digest::NONE)
3288 .Digest(Digest::SHA1)
3289 .SetDefaultValidity()));
3290 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3291 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3292 AbortIfNeeded();
3293}
3294
3295/*
Selene Huang31ab4042020-04-29 04:22:39 -07003296 * SigningOperationsTest.AesEcbSign
3297 *
3298 * Verifies that attempts to use AES keys to sign fail in the correct way.
3299 */
3300TEST_P(SigningOperationsTest, AesEcbSign) {
3301 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3302 .Authorization(TAG_NO_AUTH_REQUIRED)
3303 .SigningKey()
3304 .AesEncryptionKey(128)
3305 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3306
3307 AuthorizationSet out_params;
3308 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3309 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3310 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3311 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3312}
3313
3314/*
3315 * SigningOperationsTest.HmacAllDigests
3316 *
3317 * Verifies that HMAC works with all digests.
3318 */
3319TEST_P(SigningOperationsTest, HmacAllDigests) {
3320 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
3321 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3322 .Authorization(TAG_NO_AUTH_REQUIRED)
3323 .HmacKey(128)
3324 .Digest(digest)
3325 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3326 << "Failed to create HMAC key with digest " << digest;
3327 string message = "12345678901234567890123456789012";
3328 string signature = MacMessage(message, digest, 160);
3329 EXPECT_EQ(160U / 8U, signature.size())
3330 << "Failed to sign with HMAC key with digest " << digest;
3331 CheckedDeleteKey();
3332 }
3333}
3334
3335/*
3336 * SigningOperationsTest.HmacSha256TooLargeMacLength
3337 *
3338 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3339 * digest size.
3340 */
3341TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3342 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3343 .Authorization(TAG_NO_AUTH_REQUIRED)
3344 .HmacKey(128)
3345 .Digest(Digest::SHA_2_256)
3346 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3347 AuthorizationSet output_params;
3348 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3349 AuthorizationSetBuilder()
3350 .Digest(Digest::SHA_2_256)
3351 .Authorization(TAG_MAC_LENGTH, 264),
3352 &output_params));
3353}
3354
3355/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003356 * SigningOperationsTest.HmacSha256InvalidMacLength
3357 *
3358 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3359 * not a multiple of 8.
3360 */
3361TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3362 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3363 .Authorization(TAG_NO_AUTH_REQUIRED)
3364 .HmacKey(128)
3365 .Digest(Digest::SHA_2_256)
3366 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3367 AuthorizationSet output_params;
3368 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3369 AuthorizationSetBuilder()
3370 .Digest(Digest::SHA_2_256)
3371 .Authorization(TAG_MAC_LENGTH, 161),
3372 &output_params));
3373}
3374
3375/*
Selene Huang31ab4042020-04-29 04:22:39 -07003376 * SigningOperationsTest.HmacSha256TooSmallMacLength
3377 *
3378 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3379 * specified minimum MAC length.
3380 */
3381TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3382 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3383 .Authorization(TAG_NO_AUTH_REQUIRED)
3384 .HmacKey(128)
3385 .Digest(Digest::SHA_2_256)
3386 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3387 AuthorizationSet output_params;
3388 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3389 AuthorizationSetBuilder()
3390 .Digest(Digest::SHA_2_256)
3391 .Authorization(TAG_MAC_LENGTH, 120),
3392 &output_params));
3393}
3394
3395/*
3396 * SigningOperationsTest.HmacRfc4231TestCase3
3397 *
3398 * Validates against the test vectors from RFC 4231 test case 3.
3399 */
3400TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3401 string key(20, 0xaa);
3402 string message(50, 0xdd);
3403 uint8_t sha_224_expected[] = {
3404 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3405 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3406 };
3407 uint8_t sha_256_expected[] = {
3408 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3409 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3410 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3411 };
3412 uint8_t sha_384_expected[] = {
3413 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3414 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3415 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3416 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3417 };
3418 uint8_t sha_512_expected[] = {
3419 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3420 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3421 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3422 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3423 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3424 };
3425
3426 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3427 if (SecLevel() != SecurityLevel::STRONGBOX) {
3428 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3429 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3430 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3431 }
3432}
3433
3434/*
3435 * SigningOperationsTest.HmacRfc4231TestCase5
3436 *
3437 * Validates against the test vectors from RFC 4231 test case 5.
3438 */
3439TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3440 string key(20, 0x0c);
3441 string message = "Test With Truncation";
3442
3443 uint8_t sha_224_expected[] = {
3444 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3445 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3446 };
3447 uint8_t sha_256_expected[] = {
3448 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3449 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3450 };
3451 uint8_t sha_384_expected[] = {
3452 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3453 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3454 };
3455 uint8_t sha_512_expected[] = {
3456 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3457 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3458 };
3459
3460 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3461 if (SecLevel() != SecurityLevel::STRONGBOX) {
3462 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3463 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3464 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3465 }
3466}
3467
3468INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3469
3470typedef KeyMintAidlTestBase VerificationOperationsTest;
3471
3472/*
Selene Huang31ab4042020-04-29 04:22:39 -07003473 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3474 *
3475 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3476 */
3477TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3478 string key_material = "HelloThisIsAKey";
3479
3480 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003481 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003482 EXPECT_EQ(ErrorCode::OK,
3483 ImportKey(AuthorizationSetBuilder()
3484 .Authorization(TAG_NO_AUTH_REQUIRED)
3485 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3486 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3487 .Digest(Digest::SHA_2_256)
3488 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3489 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3490 EXPECT_EQ(ErrorCode::OK,
3491 ImportKey(AuthorizationSetBuilder()
3492 .Authorization(TAG_NO_AUTH_REQUIRED)
3493 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3494 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3495 .Digest(Digest::SHA_2_256)
3496 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3497 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3498
3499 string message = "This is a message.";
3500 string signature = SignMessage(
3501 signing_key, message,
3502 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3503
3504 // Signing key should not work.
3505 AuthorizationSet out_params;
3506 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3507 Begin(KeyPurpose::VERIFY, signing_key,
3508 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3509
3510 // Verification key should work.
3511 VerifyMessage(verification_key, message, signature,
3512 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3513
3514 CheckedDeleteKey(&signing_key);
3515 CheckedDeleteKey(&verification_key);
3516}
3517
Prashant Patildec9fdc2021-12-08 15:25:47 +00003518/*
3519 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3520 *
3521 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3522 */
3523TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3524 string key_material = "HelloThisIsAKey";
3525
3526 vector<uint8_t> signing_key, verification_key;
3527 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3528 EXPECT_EQ(ErrorCode::OK,
3529 ImportKey(AuthorizationSetBuilder()
3530 .Authorization(TAG_NO_AUTH_REQUIRED)
3531 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3532 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3533 .Digest(Digest::SHA_2_256)
3534 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3535 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3536 EXPECT_EQ(ErrorCode::OK,
3537 ImportKey(AuthorizationSetBuilder()
3538 .Authorization(TAG_NO_AUTH_REQUIRED)
3539 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3540 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3541 .Digest(Digest::SHA_2_256)
3542 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3543 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3544
3545 string message = "This is a message.";
3546 string signature = SignMessage(
3547 signing_key, message,
3548 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3549
3550 AuthorizationSet begin_out_params;
3551 ASSERT_EQ(ErrorCode::OK,
3552 Begin(KeyPurpose::VERIFY, verification_key,
3553 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3554
3555 string corruptMessage = "This is b message."; // Corrupted message
3556 string output;
3557 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3558
3559 ASSERT_EQ(ErrorCode::OK,
3560 Begin(KeyPurpose::VERIFY, verification_key,
3561 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3562
3563 signature[0] += 1; // Corrupt a signature
3564 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3565
3566 CheckedDeleteKey(&signing_key);
3567 CheckedDeleteKey(&verification_key);
3568}
3569
Selene Huang31ab4042020-04-29 04:22:39 -07003570INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3571
3572typedef KeyMintAidlTestBase ExportKeyTest;
3573
3574/*
3575 * ExportKeyTest.RsaUnsupportedKeyFormat
3576 *
3577 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3578 */
3579// TODO(seleneh) add ExportKey to GenerateKey
3580// check result
3581
3582class ImportKeyTest : public KeyMintAidlTestBase {
3583 public:
3584 template <TagType tag_type, Tag tag, typename ValueT>
3585 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3586 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003587 for (auto& entry : key_characteristics_) {
3588 if (entry.securityLevel == SecLevel()) {
3589 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3590 << "Tag " << tag << " with value " << expected
3591 << " not found at security level" << entry.securityLevel;
3592 } else {
3593 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3594 << "Tag " << tag << " found at security level " << entry.securityLevel;
3595 }
Selene Huang31ab4042020-04-29 04:22:39 -07003596 }
3597 }
3598
3599 void CheckOrigin() {
3600 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003601 // Origin isn't a crypto param, but it always lives with them.
3602 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003603 }
3604};
3605
3606/*
3607 * ImportKeyTest.RsaSuccess
3608 *
3609 * Verifies that importing and using an RSA key pair works correctly.
3610 */
3611TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003612 uint32_t key_size;
3613 string key;
3614
3615 if (SecLevel() == SecurityLevel::STRONGBOX) {
3616 key_size = 2048;
3617 key = rsa_2048_key;
3618 } else {
3619 key_size = 1024;
3620 key = rsa_key;
3621 }
3622
Selene Huang31ab4042020-04-29 04:22:39 -07003623 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3624 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003625 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003626 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003627 .Padding(PaddingMode::RSA_PSS)
3628 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003629 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003630
3631 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003632 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003633 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3634 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3635 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3636 CheckOrigin();
3637
3638 string message(1024 / 8, 'a');
3639 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3640 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003641 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003642}
3643
3644/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003645 * ImportKeyTest.RsaSuccessWithoutParams
3646 *
3647 * Verifies that importing and using an RSA key pair without specifying parameters
3648 * works correctly.
3649 */
3650TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3651 uint32_t key_size;
3652 string key;
3653
3654 if (SecLevel() == SecurityLevel::STRONGBOX) {
3655 key_size = 2048;
3656 key = rsa_2048_key;
3657 } else {
3658 key_size = 1024;
3659 key = rsa_key;
3660 }
3661
3662 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3663 .Authorization(TAG_NO_AUTH_REQUIRED)
3664 .SigningKey()
3665 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3666 .Digest(Digest::SHA_2_256)
3667 .Padding(PaddingMode::RSA_PSS)
3668 .SetDefaultValidity(),
3669 KeyFormat::PKCS8, key));
3670
3671 // Key size and public exponent are determined from the imported key material.
3672 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3673 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3674
3675 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3676 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3677 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3678 CheckOrigin();
3679
3680 string message(1024 / 8, 'a');
3681 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3682 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003683 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003684}
3685
3686/*
Selene Huang31ab4042020-04-29 04:22:39 -07003687 * ImportKeyTest.RsaKeySizeMismatch
3688 *
3689 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3690 * correct way.
3691 */
3692TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3693 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3694 ImportKey(AuthorizationSetBuilder()
3695 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3696 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003697 .Padding(PaddingMode::NONE)
3698 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003699 KeyFormat::PKCS8, rsa_key));
3700}
3701
3702/*
3703 * ImportKeyTest.RsaPublicExponentMismatch
3704 *
3705 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3706 * fails in the correct way.
3707 */
3708TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3709 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3710 ImportKey(AuthorizationSetBuilder()
3711 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3712 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003713 .Padding(PaddingMode::NONE)
3714 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003715 KeyFormat::PKCS8, rsa_key));
3716}
3717
3718/*
David Drysdalee60248c2021-10-04 12:54:13 +01003719 * ImportKeyTest.RsaAttestMultiPurposeFail
3720 *
3721 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
3722 */
3723TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
3724 uint32_t key_size = 2048;
3725 string key = rsa_2048_key;
3726
3727 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3728 ImportKey(AuthorizationSetBuilder()
3729 .Authorization(TAG_NO_AUTH_REQUIRED)
3730 .RsaSigningKey(key_size, 65537)
3731 .AttestKey()
3732 .Digest(Digest::SHA_2_256)
3733 .Padding(PaddingMode::RSA_PSS)
3734 .SetDefaultValidity(),
3735 KeyFormat::PKCS8, key));
3736}
3737
3738/*
Selene Huang31ab4042020-04-29 04:22:39 -07003739 * ImportKeyTest.EcdsaSuccess
3740 *
3741 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3742 */
3743TEST_P(ImportKeyTest, EcdsaSuccess) {
3744 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3745 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003746 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003747 .Digest(Digest::SHA_2_256)
3748 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003749 KeyFormat::PKCS8, ec_256_key));
3750
3751 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003752 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3753 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3754
3755 CheckOrigin();
3756
3757 string message(32, 'a');
3758 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3759 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003760 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003761}
3762
3763/*
3764 * ImportKeyTest.EcdsaP256RFC5915Success
3765 *
3766 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3767 * correctly.
3768 */
3769TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3770 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3771 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003772 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003773 .Digest(Digest::SHA_2_256)
3774 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003775 KeyFormat::PKCS8, ec_256_key_rfc5915));
3776
3777 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003778 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3779 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3780
3781 CheckOrigin();
3782
3783 string message(32, 'a');
3784 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3785 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003786 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003787}
3788
3789/*
3790 * ImportKeyTest.EcdsaP256SEC1Success
3791 *
3792 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3793 */
3794TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3795 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3796 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003797 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003798 .Digest(Digest::SHA_2_256)
3799 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003800 KeyFormat::PKCS8, ec_256_key_sec1));
3801
3802 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003803 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3804 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3805
3806 CheckOrigin();
3807
3808 string message(32, 'a');
3809 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3810 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003811 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003812}
3813
3814/*
3815 * ImportKeyTest.Ecdsa521Success
3816 *
3817 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3818 */
3819TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01003820 if (SecLevel() == SecurityLevel::STRONGBOX) {
3821 GTEST_SKIP() << "Test not applicable to StrongBox device";
3822 }
Selene Huang31ab4042020-04-29 04:22:39 -07003823 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3824 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003825 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003826 .Digest(Digest::SHA_2_256)
3827 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003828 KeyFormat::PKCS8, ec_521_key));
3829
3830 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003831 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3832 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3833 CheckOrigin();
3834
3835 string message(32, 'a');
3836 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3837 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003838 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003839}
3840
3841/*
Selene Huang31ab4042020-04-29 04:22:39 -07003842 * ImportKeyTest.EcdsaCurveMismatch
3843 *
3844 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3845 * the correct way.
3846 */
3847TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3848 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3849 ImportKey(AuthorizationSetBuilder()
3850 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003851 .Digest(Digest::NONE)
3852 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003853 KeyFormat::PKCS8, ec_256_key));
3854}
3855
3856/*
David Drysdalee60248c2021-10-04 12:54:13 +01003857 * ImportKeyTest.EcdsaAttestMultiPurposeFail
3858 *
3859 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
3860 */
3861TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
3862 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3863 ImportKey(AuthorizationSetBuilder()
3864 .Authorization(TAG_NO_AUTH_REQUIRED)
3865 .EcdsaSigningKey(EcCurve::P_256)
3866 .AttestKey()
3867 .Digest(Digest::SHA_2_256)
3868 .SetDefaultValidity(),
3869 KeyFormat::PKCS8, ec_256_key));
3870}
3871
3872/*
David Drysdale42fe1892021-10-14 14:43:46 +01003873 * ImportKeyTest.Ed25519RawSuccess
3874 *
3875 * Verifies that importing and using a raw Ed25519 private key works correctly.
3876 */
3877TEST_P(ImportKeyTest, Ed25519RawSuccess) {
3878 if (!Curve25519Supported()) {
3879 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3880 }
3881
3882 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3883 .Authorization(TAG_NO_AUTH_REQUIRED)
3884 .EcdsaSigningKey(EcCurve::CURVE_25519)
3885 .Digest(Digest::NONE)
3886 .SetDefaultValidity(),
3887 KeyFormat::RAW, ed25519_key));
3888 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3889 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
3890 CheckOrigin();
3891
3892 // The returned cert should hold the correct public key.
3893 ASSERT_GT(cert_chain_.size(), 0);
3894 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
3895 ASSERT_NE(kmKeyCert, nullptr);
3896 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
3897 ASSERT_NE(kmPubKey.get(), nullptr);
3898 size_t kmPubKeySize = 32;
3899 uint8_t kmPubKeyData[32];
3900 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
3901 ASSERT_EQ(kmPubKeySize, 32);
3902 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
3903
3904 string message(32, 'a');
3905 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3906 string signature = SignMessage(message, params);
3907 LocalVerifyMessage(message, signature, params);
3908}
3909
3910/*
3911 * ImportKeyTest.Ed25519Pkcs8Success
3912 *
3913 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
3914 */
3915TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
3916 if (!Curve25519Supported()) {
3917 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3918 }
3919
3920 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3921 .Authorization(TAG_NO_AUTH_REQUIRED)
3922 .EcdsaSigningKey(EcCurve::CURVE_25519)
3923 .Digest(Digest::NONE)
3924 .SetDefaultValidity(),
3925 KeyFormat::PKCS8, ed25519_pkcs8_key));
3926 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3927 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
3928 CheckOrigin();
3929
3930 // The returned cert should hold the correct public key.
3931 ASSERT_GT(cert_chain_.size(), 0);
3932 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
3933 ASSERT_NE(kmKeyCert, nullptr);
3934 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
3935 ASSERT_NE(kmPubKey.get(), nullptr);
3936 size_t kmPubKeySize = 32;
3937 uint8_t kmPubKeyData[32];
3938 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
3939 ASSERT_EQ(kmPubKeySize, 32);
3940 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
3941
3942 string message(32, 'a');
3943 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3944 string signature = SignMessage(message, params);
3945 LocalVerifyMessage(message, signature, params);
3946}
3947
3948/*
3949 * ImportKeyTest.Ed25519CurveMismatch
3950 *
3951 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
3952 * the correct way.
3953 */
3954TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
3955 if (!Curve25519Supported()) {
3956 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3957 }
3958
3959 ASSERT_NE(ErrorCode::OK,
3960 ImportKey(AuthorizationSetBuilder()
3961 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
3962 .Digest(Digest::NONE)
3963 .SetDefaultValidity(),
3964 KeyFormat::RAW, ed25519_key));
3965}
3966
3967/*
3968 * ImportKeyTest.Ed25519FormatMismatch
3969 *
3970 * Verifies that importing an Ed25519 key pair with an invalid format fails.
3971 */
3972TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
3973 if (!Curve25519Supported()) {
3974 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3975 }
3976
3977 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3978 .EcdsaSigningKey(EcCurve::CURVE_25519)
3979 .Digest(Digest::NONE)
3980 .SetDefaultValidity(),
3981 KeyFormat::PKCS8, ed25519_key));
3982 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3983 .EcdsaSigningKey(EcCurve::CURVE_25519)
3984 .Digest(Digest::NONE)
3985 .SetDefaultValidity(),
3986 KeyFormat::RAW, ed25519_pkcs8_key));
3987}
3988
3989/*
3990 * ImportKeyTest.Ed25519PurposeMismatch
3991 *
3992 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
3993 */
3994TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
3995 if (!Curve25519Supported()) {
3996 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3997 }
3998
3999 // Can't have both SIGN and ATTEST_KEY
4000 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4001 .EcdsaSigningKey(EcCurve::CURVE_25519)
4002 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4003 .Digest(Digest::NONE)
4004 .SetDefaultValidity(),
4005 KeyFormat::RAW, ed25519_key));
4006 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4007 // PKCS#8 format and so includes an OID).
4008 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4009 .EcdsaKey(EcCurve::CURVE_25519)
4010 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4011 .Digest(Digest::NONE)
4012 .SetDefaultValidity(),
4013 KeyFormat::PKCS8, ed25519_pkcs8_key));
4014}
4015
4016/*
4017 * ImportKeyTest.X25519RawSuccess
4018 *
4019 * Verifies that importing and using a raw X25519 private key works correctly.
4020 */
4021TEST_P(ImportKeyTest, X25519RawSuccess) {
4022 if (!Curve25519Supported()) {
4023 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4024 }
4025
4026 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4027 .Authorization(TAG_NO_AUTH_REQUIRED)
4028 .EcdsaKey(EcCurve::CURVE_25519)
4029 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4030 .SetDefaultValidity(),
4031 KeyFormat::RAW, x25519_key));
4032
4033 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4034 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4035 CheckOrigin();
4036}
4037
4038/*
4039 * ImportKeyTest.X25519Pkcs8Success
4040 *
4041 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4042 */
4043TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4044 if (!Curve25519Supported()) {
4045 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4046 }
4047
4048 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4049 .Authorization(TAG_NO_AUTH_REQUIRED)
4050 .EcdsaKey(EcCurve::CURVE_25519)
4051 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4052 .SetDefaultValidity(),
4053 KeyFormat::PKCS8, x25519_pkcs8_key));
4054
4055 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4056 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4057 CheckOrigin();
4058}
4059
4060/*
4061 * ImportKeyTest.X25519CurveMismatch
4062 *
4063 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4064 * the correct way.
4065 */
4066TEST_P(ImportKeyTest, X25519CurveMismatch) {
4067 if (!Curve25519Supported()) {
4068 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4069 }
4070
4071 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4072 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4073 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4074 .SetDefaultValidity(),
4075 KeyFormat::RAW, x25519_key));
4076}
4077
4078/*
4079 * ImportKeyTest.X25519FormatMismatch
4080 *
4081 * Verifies that importing an X25519 key with an invalid format fails.
4082 */
4083TEST_P(ImportKeyTest, X25519FormatMismatch) {
4084 if (!Curve25519Supported()) {
4085 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4086 }
4087
4088 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4089 .EcdsaKey(EcCurve::CURVE_25519)
4090 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4091 .SetDefaultValidity(),
4092 KeyFormat::PKCS8, x25519_key));
4093 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4094 .EcdsaKey(EcCurve::CURVE_25519)
4095 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4096 .SetDefaultValidity(),
4097 KeyFormat::RAW, x25519_pkcs8_key));
4098}
4099
4100/*
4101 * ImportKeyTest.X25519PurposeMismatch
4102 *
4103 * Verifies that importing an X25519 key pair with an invalid format fails.
4104 */
4105TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4106 if (!Curve25519Supported()) {
4107 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4108 }
4109
4110 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4111 .EcdsaKey(EcCurve::CURVE_25519)
4112 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4113 .SetDefaultValidity(),
4114 KeyFormat::PKCS8, x25519_pkcs8_key));
4115 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4116 .EcdsaSigningKey(EcCurve::CURVE_25519)
4117 .SetDefaultValidity(),
4118 KeyFormat::PKCS8, x25519_pkcs8_key));
4119}
4120
4121/*
Selene Huang31ab4042020-04-29 04:22:39 -07004122 * ImportKeyTest.AesSuccess
4123 *
4124 * Verifies that importing and using an AES key works.
4125 */
4126TEST_P(ImportKeyTest, AesSuccess) {
4127 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4128 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4129 .Authorization(TAG_NO_AUTH_REQUIRED)
4130 .AesEncryptionKey(key.size() * 8)
4131 .EcbMode()
4132 .Padding(PaddingMode::PKCS7),
4133 KeyFormat::RAW, key));
4134
4135 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4136 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4137 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4138 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4139 CheckOrigin();
4140
4141 string message = "Hello World!";
4142 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4143 string ciphertext = EncryptMessage(message, params);
4144 string plaintext = DecryptMessage(ciphertext, params);
4145 EXPECT_EQ(message, plaintext);
4146}
4147
4148/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004149 * ImportKeyTest.AesFailure
4150 *
4151 * Verifies that importing an invalid AES key fails.
4152 */
4153TEST_P(ImportKeyTest, AesFailure) {
4154 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4155 uint32_t bitlen = key.size() * 8;
4156 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004157 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004158 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004159 .Authorization(TAG_NO_AUTH_REQUIRED)
4160 .AesEncryptionKey(key_size)
4161 .EcbMode()
4162 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004163 KeyFormat::RAW, key);
4164 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004165 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4166 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004167 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004168
4169 // Explicit key size matches that of the provided key, but it's not a valid size.
4170 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4171 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4172 ImportKey(AuthorizationSetBuilder()
4173 .Authorization(TAG_NO_AUTH_REQUIRED)
4174 .AesEncryptionKey(long_key.size() * 8)
4175 .EcbMode()
4176 .Padding(PaddingMode::PKCS7),
4177 KeyFormat::RAW, long_key));
4178 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4179 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4180 ImportKey(AuthorizationSetBuilder()
4181 .Authorization(TAG_NO_AUTH_REQUIRED)
4182 .AesEncryptionKey(short_key.size() * 8)
4183 .EcbMode()
4184 .Padding(PaddingMode::PKCS7),
4185 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004186}
4187
4188/*
4189 * ImportKeyTest.TripleDesSuccess
4190 *
4191 * Verifies that importing and using a 3DES key works.
4192 */
4193TEST_P(ImportKeyTest, TripleDesSuccess) {
4194 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4195 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4196 .Authorization(TAG_NO_AUTH_REQUIRED)
4197 .TripleDesEncryptionKey(168)
4198 .EcbMode()
4199 .Padding(PaddingMode::PKCS7),
4200 KeyFormat::RAW, key));
4201
4202 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4203 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4204 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4205 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4206 CheckOrigin();
4207
4208 string message = "Hello World!";
4209 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4210 string ciphertext = EncryptMessage(message, params);
4211 string plaintext = DecryptMessage(ciphertext, params);
4212 EXPECT_EQ(message, plaintext);
4213}
4214
4215/*
4216 * ImportKeyTest.TripleDesFailure
4217 *
4218 * Verifies that importing an invalid 3DES key fails.
4219 */
4220TEST_P(ImportKeyTest, TripleDesFailure) {
4221 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004222 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004223 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004224 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004225 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004226 .Authorization(TAG_NO_AUTH_REQUIRED)
4227 .TripleDesEncryptionKey(key_size)
4228 .EcbMode()
4229 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004230 KeyFormat::RAW, key);
4231 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004232 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4233 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004234 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004235 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004236 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004237 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4238 ImportKey(AuthorizationSetBuilder()
4239 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004240 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004241 .EcbMode()
4242 .Padding(PaddingMode::PKCS7),
4243 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004244 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004245 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4246 ImportKey(AuthorizationSetBuilder()
4247 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004248 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004249 .EcbMode()
4250 .Padding(PaddingMode::PKCS7),
4251 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004252}
4253
4254/*
4255 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004256 *
4257 * Verifies that importing and using an HMAC key works.
4258 */
4259TEST_P(ImportKeyTest, HmacKeySuccess) {
4260 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4261 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4262 .Authorization(TAG_NO_AUTH_REQUIRED)
4263 .HmacKey(key.size() * 8)
4264 .Digest(Digest::SHA_2_256)
4265 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4266 KeyFormat::RAW, key));
4267
4268 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4269 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4270 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4271 CheckOrigin();
4272
4273 string message = "Hello World!";
4274 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4275 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4276}
4277
4278INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4279
4280auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004281 // IKeyMintDevice.aidl
4282 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4283 "020100" // INTEGER length 1 value 0x00 (version)
4284 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4285 "934bf94e2aa28a3f83c9f79297250262"
4286 "fbe3276b5a1c91159bbfa3ef8957aac8"
4287 "4b59b30b455a79c2973480823d8b3863"
4288 "c3deef4a8e243590268d80e18751a0e1"
4289 "30f67ce6a1ace9f79b95e097474febc9"
4290 "81195b1d13a69086c0863f66a7b7fdb4"
4291 "8792227b1ac5e2489febdf087ab54864"
4292 "83033a6f001ca5d1ec1e27f5c30f4cec"
4293 "2642074a39ae68aee552e196627a8e3d"
4294 "867e67a8c01b11e75f13cca0a97ab668"
4295 "b50cda07a8ecb7cd8e3dd7009c963653"
4296 "4f6f239cffe1fc8daa466f78b676c711"
4297 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4298 "99b801597d5220e307eaa5bee507fb94"
4299 "d1fa69f9e519b2de315bac92c36f2ea1"
4300 "fa1df4478c0ddedeae8c70e0233cd098"
4301 "040c" // OCTET STRING length 0x0c (initializationVector)
4302 "d796b02c370f1fa4cc0124f1"
4303 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4304 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4305 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4306 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4307 "3106" // SET length 0x06
4308 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4309 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4310 // } end SET
4311 // } end [1]
4312 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4313 "020120" // INTEGER length 1 value 0x20 (AES)
4314 // } end [2]
4315 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4316 "02020100" // INTEGER length 2 value 0x100
4317 // } end [3]
4318 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4319 "3103" // SET length 0x03 {
4320 "020101" // INTEGER length 1 value 0x01 (ECB)
4321 // } end SET
4322 // } end [4]
4323 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4324 "3103" // SET length 0x03 {
4325 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4326 // } end SET
4327 // } end [5]
4328 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4329 // (noAuthRequired)
4330 "0500" // NULL
4331 // } end [503]
4332 // } end SEQUENCE (AuthorizationList)
4333 // } end SEQUENCE (KeyDescription)
4334 "0420" // OCTET STRING length 0x20 (encryptedKey)
4335 "ccd540855f833a5e1480bfd2d36faf3a"
4336 "eee15df5beabe2691bc82dde2a7aa910"
4337 "0410" // OCTET STRING length 0x10 (tag)
4338 "64c9f689c60ff6223ab6e6999e0eb6e5"
4339 // } SEQUENCE (SecureKeyWrapper)
4340);
Selene Huang31ab4042020-04-29 04:22:39 -07004341
4342auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004343 // IKeyMintDevice.aidl
4344 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4345 "020100" // INTEGER length 1 value 0x00 (version)
4346 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4347 "aad93ed5924f283b4bb5526fbe7a1412"
4348 "f9d9749ec30db9062b29e574a8546f33"
4349 "c88732452f5b8e6a391ee76c39ed1712"
4350 "c61d8df6213dec1cffbc17a8c6d04c7b"
4351 "30893d8daa9b2015213e219468215532"
4352 "07f8f9931c4caba23ed3bee28b36947e"
4353 "47f10e0a5c3dc51c988a628daad3e5e1"
4354 "f4005e79c2d5a96c284b4b8d7e4948f3"
4355 "31e5b85dd5a236f85579f3ea1d1b8484"
4356 "87470bdb0ab4f81a12bee42c99fe0df4"
4357 "bee3759453e69ad1d68a809ce06b949f"
4358 "7694a990429b2fe81e066ff43e56a216"
4359 "02db70757922a4bcc23ab89f1e35da77"
4360 "586775f423e519c2ea394caf48a28d0c"
4361 "8020f1dcf6b3a68ec246f615ae96dae9"
4362 "a079b1f6eb959033c1af5c125fd94168"
4363 "040c" // OCTET STRING length 0x0c (initializationVector)
4364 "6d9721d08589581ab49204a3"
4365 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4366 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4367 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4368 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4369 "3106" // SET length 0x06
4370 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4371 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4372 // } end SET
4373 // } end [1]
4374 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4375 "020120" // INTEGER length 1 value 0x20 (AES)
4376 // } end [2]
4377 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4378 "02020100" // INTEGER length 2 value 0x100
4379 // } end [3]
4380 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4381 "3103" // SET length 0x03 {
4382 "020101" // INTEGER length 1 value 0x01 (ECB)
4383 // } end SET
4384 // } end [4]
4385 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4386 "3103" // SET length 0x03 {
4387 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4388 // } end SET
4389 // } end [5]
4390 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4391 // (noAuthRequired)
4392 "0500" // NULL
4393 // } end [503]
4394 // } end SEQUENCE (AuthorizationList)
4395 // } end SEQUENCE (KeyDescription)
4396 "0420" // OCTET STRING length 0x20 (encryptedKey)
4397 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4398 "c20d1f99a9a024a76f35c8e2cab9b68d"
4399 "0410" // OCTET STRING length 0x10 (tag)
4400 "2560c70109ae67c030f00b98b512a670"
4401 // } SEQUENCE (SecureKeyWrapper)
4402);
Selene Huang31ab4042020-04-29 04:22:39 -07004403
4404auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004405 // RFC 5208 s5
4406 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4407 "020100" // INTEGER length 1 value 0x00 (version)
4408 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4409 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4410 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4411 "0500" // NULL (parameters)
4412 // } SEQUENCE (AlgorithmIdentifier)
4413 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4414 // RFC 8017 A.1.2
4415 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4416 "020100" // INTEGER length 1 value 0x00 (version)
4417 "02820101" // INTEGER length 0x0101 (modulus) value...
4418 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4419 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4420 "7b06e673a837313d56b1c725150a3fef" // 0x30
4421 "86acbddc41bb759c2854eae32d35841e" // 0x40
4422 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4423 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4424 "312d7bd5921ffaea1347c157406fef71" // 0x70
4425 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4426 "f4645c11f5c1374c3886427411c44979" // 0x90
4427 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4428 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4429 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4430 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4431 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4432 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4433 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4434 "55" // 0x101
4435 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4436 "02820100" // INTEGER length 0x100 (privateExponent) value...
4437 "431447b6251908112b1ee76f99f3711a" // 0x10
4438 "52b6630960046c2de70de188d833f8b8" // 0x20
4439 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4440 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4441 "e710b630a03adc683b5d2c43080e52be" // 0x50
4442 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4443 "822bccff087d63c940ba8a45f670feb2" // 0x70
4444 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4445 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4446 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4447 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4448 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4449 "52659d5a5ba05b663737a8696281865b" // 0xd0
4450 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4451 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4452 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4453 "028181" // INTEGER length 0x81 (prime1) value...
4454 "00de392e18d682c829266cc3454e1d61" // 0x10
4455 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4456 "ff841be5bac82a164c5970007047b8c5" // 0x30
4457 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4458 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4459 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4460 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4461 "9e91346130748a6e3c124f9149d71c74" // 0x80
4462 "35"
4463 "028181" // INTEGER length 0x81 (prime2) value...
4464 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4465 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4466 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4467 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4468 "9ed39a2d934c880440aed8832f984316" // 0x50
4469 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4470 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4471 "b880677c068e1be936e81288815252a8" // 0x80
4472 "a1"
4473 "028180" // INTEGER length 0x80 (exponent1) value...
4474 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4475 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4476 "5a063212a4f105a3764743e53281988a" // 0x30
4477 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4478 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4479 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4480 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4481 "4719d6e2b9439823719cd08bcd031781" // 0x80
4482 "028181" // INTEGER length 0x81 (exponent2) value...
4483 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4484 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4485 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4486 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4487 "1254186af30b22c10582a8a43e34fe94" // 0x50
4488 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4489 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4490 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4491 "61"
4492 "028181" // INTEGER length 0x81 (coefficient) value...
4493 "00c931617c77829dfb1270502be9195c" // 0x10
4494 "8f2830885f57dba869536811e6864236" // 0x20
4495 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4496 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4497 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4498 "959356210723287b0affcc9f727044d4" // 0x60
4499 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4500 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4501 "22"
4502 // } SEQUENCE
4503 // } SEQUENCE ()
4504);
Selene Huang31ab4042020-04-29 04:22:39 -07004505
4506string zero_masking_key =
4507 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4508string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4509
4510class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4511
4512TEST_P(ImportWrappedKeyTest, Success) {
4513 auto wrapping_key_desc = AuthorizationSetBuilder()
4514 .RsaEncryptionKey(2048, 65537)
4515 .Digest(Digest::SHA_2_256)
4516 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004517 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4518 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004519
4520 ASSERT_EQ(ErrorCode::OK,
4521 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4522 AuthorizationSetBuilder()
4523 .Digest(Digest::SHA_2_256)
4524 .Padding(PaddingMode::RSA_OAEP)));
4525
4526 string message = "Hello World!";
4527 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4528 string ciphertext = EncryptMessage(message, params);
4529 string plaintext = DecryptMessage(ciphertext, params);
4530 EXPECT_EQ(message, plaintext);
4531}
4532
David Drysdaled2cc8c22021-04-15 13:29:45 +01004533/*
4534 * ImportWrappedKeyTest.SuccessSidsIgnored
4535 *
4536 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
4537 * include Tag:USER_SECURE_ID.
4538 */
4539TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
4540 auto wrapping_key_desc = AuthorizationSetBuilder()
4541 .RsaEncryptionKey(2048, 65537)
4542 .Digest(Digest::SHA_2_256)
4543 .Padding(PaddingMode::RSA_OAEP)
4544 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4545 .SetDefaultValidity();
4546
4547 int64_t password_sid = 42;
4548 int64_t biometric_sid = 24;
4549 ASSERT_EQ(ErrorCode::OK,
4550 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4551 AuthorizationSetBuilder()
4552 .Digest(Digest::SHA_2_256)
4553 .Padding(PaddingMode::RSA_OAEP),
4554 password_sid, biometric_sid));
4555
4556 string message = "Hello World!";
4557 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4558 string ciphertext = EncryptMessage(message, params);
4559 string plaintext = DecryptMessage(ciphertext, params);
4560 EXPECT_EQ(message, plaintext);
4561}
4562
Selene Huang31ab4042020-04-29 04:22:39 -07004563TEST_P(ImportWrappedKeyTest, SuccessMasked) {
4564 auto wrapping_key_desc = AuthorizationSetBuilder()
4565 .RsaEncryptionKey(2048, 65537)
4566 .Digest(Digest::SHA_2_256)
4567 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004568 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4569 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004570
4571 ASSERT_EQ(ErrorCode::OK,
4572 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
4573 AuthorizationSetBuilder()
4574 .Digest(Digest::SHA_2_256)
4575 .Padding(PaddingMode::RSA_OAEP)));
4576}
4577
4578TEST_P(ImportWrappedKeyTest, WrongMask) {
4579 auto wrapping_key_desc = AuthorizationSetBuilder()
4580 .RsaEncryptionKey(2048, 65537)
4581 .Digest(Digest::SHA_2_256)
4582 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004583 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4584 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004585
4586 ASSERT_EQ(
4587 ErrorCode::VERIFICATION_FAILED,
4588 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4589 AuthorizationSetBuilder()
4590 .Digest(Digest::SHA_2_256)
4591 .Padding(PaddingMode::RSA_OAEP)));
4592}
4593
4594TEST_P(ImportWrappedKeyTest, WrongPurpose) {
4595 auto wrapping_key_desc = AuthorizationSetBuilder()
4596 .RsaEncryptionKey(2048, 65537)
4597 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004598 .Padding(PaddingMode::RSA_OAEP)
4599 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004600
4601 ASSERT_EQ(
4602 ErrorCode::INCOMPATIBLE_PURPOSE,
4603 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4604 AuthorizationSetBuilder()
4605 .Digest(Digest::SHA_2_256)
4606 .Padding(PaddingMode::RSA_OAEP)));
4607}
4608
David Drysdaled2cc8c22021-04-15 13:29:45 +01004609TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
4610 auto wrapping_key_desc = AuthorizationSetBuilder()
4611 .RsaEncryptionKey(2048, 65537)
4612 .Digest(Digest::SHA_2_256)
4613 .Padding(PaddingMode::RSA_PSS)
4614 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4615 .SetDefaultValidity();
4616
4617 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
4618 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4619 AuthorizationSetBuilder()
4620 .Digest(Digest::SHA_2_256)
4621 .Padding(PaddingMode::RSA_OAEP)));
4622}
4623
4624TEST_P(ImportWrappedKeyTest, WrongDigest) {
4625 auto wrapping_key_desc = AuthorizationSetBuilder()
4626 .RsaEncryptionKey(2048, 65537)
4627 .Digest(Digest::SHA_2_512)
4628 .Padding(PaddingMode::RSA_OAEP)
4629 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4630 .SetDefaultValidity();
4631
4632 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
4633 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4634 AuthorizationSetBuilder()
4635 .Digest(Digest::SHA_2_256)
4636 .Padding(PaddingMode::RSA_OAEP)));
4637}
4638
Selene Huang31ab4042020-04-29 04:22:39 -07004639INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
4640
4641typedef KeyMintAidlTestBase EncryptionOperationsTest;
4642
4643/*
4644 * EncryptionOperationsTest.RsaNoPaddingSuccess
4645 *
David Drysdale59cae642021-05-12 13:52:03 +01004646 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07004647 */
4648TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01004649 for (uint64_t exponent : {3, 65537}) {
4650 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4651 .Authorization(TAG_NO_AUTH_REQUIRED)
4652 .RsaEncryptionKey(2048, exponent)
4653 .Padding(PaddingMode::NONE)
4654 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004655
David Drysdaled2cc8c22021-04-15 13:29:45 +01004656 string message = string(2048 / 8, 'a');
4657 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004658 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004659 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004660
David Drysdale59cae642021-05-12 13:52:03 +01004661 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004662 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004663
David Drysdaled2cc8c22021-04-15 13:29:45 +01004664 // Unpadded RSA is deterministic
4665 EXPECT_EQ(ciphertext1, ciphertext2);
4666
4667 CheckedDeleteKey();
4668 }
Selene Huang31ab4042020-04-29 04:22:39 -07004669}
4670
4671/*
4672 * EncryptionOperationsTest.RsaNoPaddingShortMessage
4673 *
David Drysdale59cae642021-05-12 13:52:03 +01004674 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07004675 */
4676TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
4677 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4678 .Authorization(TAG_NO_AUTH_REQUIRED)
4679 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004680 .Padding(PaddingMode::NONE)
4681 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004682
4683 string message = "1";
4684 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4685
David Drysdale59cae642021-05-12 13:52:03 +01004686 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004687 EXPECT_EQ(2048U / 8, ciphertext.size());
4688
4689 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
4690 string plaintext = DecryptMessage(ciphertext, params);
4691
4692 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07004693}
4694
4695/*
Selene Huang31ab4042020-04-29 04:22:39 -07004696 * EncryptionOperationsTest.RsaOaepSuccess
4697 *
David Drysdale59cae642021-05-12 13:52:03 +01004698 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07004699 */
4700TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
4701 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4702
4703 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01004704 ASSERT_EQ(ErrorCode::OK,
4705 GenerateKey(AuthorizationSetBuilder()
4706 .Authorization(TAG_NO_AUTH_REQUIRED)
4707 .RsaEncryptionKey(key_size, 65537)
4708 .Padding(PaddingMode::RSA_OAEP)
4709 .Digest(digests)
4710 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
4711 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004712
4713 string message = "Hello";
4714
4715 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01004716 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4717
4718 auto params = AuthorizationSetBuilder()
4719 .Digest(digest)
4720 .Padding(PaddingMode::RSA_OAEP)
4721 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
4722 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004723 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4724 EXPECT_EQ(key_size / 8, ciphertext1.size());
4725
David Drysdale59cae642021-05-12 13:52:03 +01004726 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004727 EXPECT_EQ(key_size / 8, ciphertext2.size());
4728
4729 // OAEP randomizes padding so every result should be different (with astronomically high
4730 // probability).
4731 EXPECT_NE(ciphertext1, ciphertext2);
4732
4733 string plaintext1 = DecryptMessage(ciphertext1, params);
4734 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4735 string plaintext2 = DecryptMessage(ciphertext2, params);
4736 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4737
4738 // Decrypting corrupted ciphertext should fail.
4739 size_t offset_to_corrupt = random() % ciphertext1.size();
4740 char corrupt_byte;
4741 do {
4742 corrupt_byte = static_cast<char>(random() % 256);
4743 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4744 ciphertext1[offset_to_corrupt] = corrupt_byte;
4745
4746 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4747 string result;
4748 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4749 EXPECT_EQ(0U, result.size());
4750 }
4751}
4752
4753/*
4754 * EncryptionOperationsTest.RsaOaepInvalidDigest
4755 *
David Drysdale59cae642021-05-12 13:52:03 +01004756 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07004757 * without a digest.
4758 */
4759TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
4760 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4761 .Authorization(TAG_NO_AUTH_REQUIRED)
4762 .RsaEncryptionKey(2048, 65537)
4763 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004764 .Digest(Digest::NONE)
4765 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004766
4767 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004768 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07004769}
4770
4771/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004772 * EncryptionOperationsTest.RsaOaepInvalidPadding
4773 *
David Drysdale59cae642021-05-12 13:52:03 +01004774 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01004775 * with a padding value that is only suitable for signing/verifying.
4776 */
4777TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
4778 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4779 .Authorization(TAG_NO_AUTH_REQUIRED)
4780 .RsaEncryptionKey(2048, 65537)
4781 .Padding(PaddingMode::RSA_PSS)
4782 .Digest(Digest::NONE)
4783 .SetDefaultValidity()));
4784
4785 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004786 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01004787}
4788
4789/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004790 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07004791 *
David Drysdale59cae642021-05-12 13:52:03 +01004792 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07004793 * with a different digest than was used to encrypt.
4794 */
4795TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01004796 if (SecLevel() == SecurityLevel::STRONGBOX) {
4797 GTEST_SKIP() << "Test not applicable to StrongBox device";
4798 }
Selene Huang31ab4042020-04-29 04:22:39 -07004799
4800 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4801 .Authorization(TAG_NO_AUTH_REQUIRED)
4802 .RsaEncryptionKey(1024, 65537)
4803 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004804 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
4805 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004806 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01004807 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07004808 message,
4809 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
4810
4811 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4812 .Digest(Digest::SHA_2_256)
4813 .Padding(PaddingMode::RSA_OAEP)));
4814 string result;
4815 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
4816 EXPECT_EQ(0U, result.size());
4817}
4818
4819/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004820 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
4821 *
David Drysdale59cae642021-05-12 13:52:03 +01004822 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004823 * digests.
4824 */
4825TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
4826 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4827
4828 size_t key_size = 2048; // Need largish key for SHA-512 test.
4829 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4830 .OaepMGFDigest(digests)
4831 .Authorization(TAG_NO_AUTH_REQUIRED)
4832 .RsaEncryptionKey(key_size, 65537)
4833 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004834 .Digest(Digest::SHA_2_256)
4835 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004836
4837 string message = "Hello";
4838
4839 for (auto digest : digests) {
4840 auto params = AuthorizationSetBuilder()
4841 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4842 .Digest(Digest::SHA_2_256)
4843 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01004844 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004845 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4846 EXPECT_EQ(key_size / 8, ciphertext1.size());
4847
David Drysdale59cae642021-05-12 13:52:03 +01004848 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004849 EXPECT_EQ(key_size / 8, ciphertext2.size());
4850
4851 // OAEP randomizes padding so every result should be different (with astronomically high
4852 // probability).
4853 EXPECT_NE(ciphertext1, ciphertext2);
4854
4855 string plaintext1 = DecryptMessage(ciphertext1, params);
4856 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4857 string plaintext2 = DecryptMessage(ciphertext2, params);
4858 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4859
4860 // Decrypting corrupted ciphertext should fail.
4861 size_t offset_to_corrupt = random() % ciphertext1.size();
4862 char corrupt_byte;
4863 do {
4864 corrupt_byte = static_cast<char>(random() % 256);
4865 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4866 ciphertext1[offset_to_corrupt] = corrupt_byte;
4867
4868 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4869 string result;
4870 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4871 EXPECT_EQ(0U, result.size());
4872 }
4873}
4874
4875/*
4876 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
4877 *
David Drysdale59cae642021-05-12 13:52:03 +01004878 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004879 * with incompatible MGF digest.
4880 */
4881TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4882 ASSERT_EQ(ErrorCode::OK,
4883 GenerateKey(AuthorizationSetBuilder()
4884 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4885 .Authorization(TAG_NO_AUTH_REQUIRED)
4886 .RsaEncryptionKey(2048, 65537)
4887 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004888 .Digest(Digest::SHA_2_256)
4889 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004890 string message = "Hello World!";
4891
4892 auto params = AuthorizationSetBuilder()
4893 .Padding(PaddingMode::RSA_OAEP)
4894 .Digest(Digest::SHA_2_256)
4895 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004896 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004897}
4898
4899/*
4900 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4901 *
4902 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4903 * with unsupported MGF digest.
4904 */
4905TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4906 ASSERT_EQ(ErrorCode::OK,
4907 GenerateKey(AuthorizationSetBuilder()
4908 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4909 .Authorization(TAG_NO_AUTH_REQUIRED)
4910 .RsaEncryptionKey(2048, 65537)
4911 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004912 .Digest(Digest::SHA_2_256)
4913 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004914 string message = "Hello World!";
4915
4916 auto params = AuthorizationSetBuilder()
4917 .Padding(PaddingMode::RSA_OAEP)
4918 .Digest(Digest::SHA_2_256)
4919 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004920 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004921}
4922
4923/*
Selene Huang31ab4042020-04-29 04:22:39 -07004924 * EncryptionOperationsTest.RsaPkcs1Success
4925 *
4926 * Verifies that RSA PKCS encryption/decrypts works.
4927 */
4928TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4929 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4930 .Authorization(TAG_NO_AUTH_REQUIRED)
4931 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004932 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4933 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004934
4935 string message = "Hello World!";
4936 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01004937 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004938 EXPECT_EQ(2048U / 8, ciphertext1.size());
4939
David Drysdale59cae642021-05-12 13:52:03 +01004940 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004941 EXPECT_EQ(2048U / 8, ciphertext2.size());
4942
4943 // PKCS1 v1.5 randomizes padding so every result should be different.
4944 EXPECT_NE(ciphertext1, ciphertext2);
4945
4946 string plaintext = DecryptMessage(ciphertext1, params);
4947 EXPECT_EQ(message, plaintext);
4948
4949 // Decrypting corrupted ciphertext should fail.
4950 size_t offset_to_corrupt = random() % ciphertext1.size();
4951 char corrupt_byte;
4952 do {
4953 corrupt_byte = static_cast<char>(random() % 256);
4954 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4955 ciphertext1[offset_to_corrupt] = corrupt_byte;
4956
4957 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4958 string result;
4959 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4960 EXPECT_EQ(0U, result.size());
4961}
4962
4963/*
Selene Huang31ab4042020-04-29 04:22:39 -07004964 * EncryptionOperationsTest.EcdsaEncrypt
4965 *
4966 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4967 */
4968TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4969 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4970 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004971 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004972 .Digest(Digest::NONE)
4973 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004974 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4975 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4976 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4977}
4978
4979/*
4980 * EncryptionOperationsTest.HmacEncrypt
4981 *
4982 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4983 */
4984TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4985 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4986 .Authorization(TAG_NO_AUTH_REQUIRED)
4987 .HmacKey(128)
4988 .Digest(Digest::SHA_2_256)
4989 .Padding(PaddingMode::NONE)
4990 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4991 auto params = AuthorizationSetBuilder()
4992 .Digest(Digest::SHA_2_256)
4993 .Padding(PaddingMode::NONE)
4994 .Authorization(TAG_MAC_LENGTH, 128);
4995 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4996 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4997}
4998
4999/*
5000 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5001 *
5002 * Verifies that AES ECB mode works.
5003 */
5004TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5005 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5006 .Authorization(TAG_NO_AUTH_REQUIRED)
5007 .AesEncryptionKey(128)
5008 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5009 .Padding(PaddingMode::NONE)));
5010
5011 ASSERT_GT(key_blob_.size(), 0U);
5012 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5013
5014 // Two-block message.
5015 string message = "12345678901234567890123456789012";
5016 string ciphertext1 = EncryptMessage(message, params);
5017 EXPECT_EQ(message.size(), ciphertext1.size());
5018
5019 string ciphertext2 = EncryptMessage(string(message), params);
5020 EXPECT_EQ(message.size(), ciphertext2.size());
5021
5022 // ECB is deterministic.
5023 EXPECT_EQ(ciphertext1, ciphertext2);
5024
5025 string plaintext = DecryptMessage(ciphertext1, params);
5026 EXPECT_EQ(message, plaintext);
5027}
5028
5029/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005030 * EncryptionOperationsTest.AesEcbUnknownTag
5031 *
5032 * Verifies that AES ECB operations ignore unknown tags.
5033 */
5034TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5035 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5036 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5037 KeyParameter unknown_param;
5038 unknown_param.tag = unknown_tag;
5039
5040 vector<KeyCharacteristics> key_characteristics;
5041 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5042 .Authorization(TAG_NO_AUTH_REQUIRED)
5043 .AesEncryptionKey(128)
5044 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5045 .Padding(PaddingMode::NONE)
5046 .Authorization(unknown_param),
5047 &key_blob_, &key_characteristics));
5048 ASSERT_GT(key_blob_.size(), 0U);
5049
5050 // Unknown tags should not be returned in key characteristics.
5051 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5052 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5053 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5054 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5055
5056 // Encrypt without mentioning the unknown parameter.
5057 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5058 string message = "12345678901234567890123456789012";
5059 string ciphertext = EncryptMessage(message, params);
5060 EXPECT_EQ(message.size(), ciphertext.size());
5061
5062 // Decrypt including the unknown parameter.
5063 auto decrypt_params = AuthorizationSetBuilder()
5064 .BlockMode(BlockMode::ECB)
5065 .Padding(PaddingMode::NONE)
5066 .Authorization(unknown_param);
5067 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5068 EXPECT_EQ(message, plaintext);
5069}
5070
5071/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005072 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005073 *
5074 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5075 */
5076TEST_P(EncryptionOperationsTest, AesWrongMode) {
5077 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5078 .Authorization(TAG_NO_AUTH_REQUIRED)
5079 .AesEncryptionKey(128)
5080 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5081 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005082 ASSERT_GT(key_blob_.size(), 0U);
5083
Selene Huang31ab4042020-04-29 04:22:39 -07005084 EXPECT_EQ(
5085 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5086 Begin(KeyPurpose::ENCRYPT,
5087 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5088}
5089
5090/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005091 * EncryptionOperationsTest.AesWrongPadding
5092 *
5093 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5094 */
5095TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5096 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5097 .Authorization(TAG_NO_AUTH_REQUIRED)
5098 .AesEncryptionKey(128)
5099 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5100 .Padding(PaddingMode::NONE)));
5101 ASSERT_GT(key_blob_.size(), 0U);
5102
5103 EXPECT_EQ(
5104 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5105 Begin(KeyPurpose::ENCRYPT,
5106 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5107}
5108
5109/*
5110 * EncryptionOperationsTest.AesInvalidParams
5111 *
5112 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5113 */
5114TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5115 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5116 .Authorization(TAG_NO_AUTH_REQUIRED)
5117 .AesEncryptionKey(128)
5118 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5119 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5120 .Padding(PaddingMode::NONE)
5121 .Padding(PaddingMode::PKCS7)));
5122 ASSERT_GT(key_blob_.size(), 0U);
5123
5124 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5125 .BlockMode(BlockMode::CBC)
5126 .BlockMode(BlockMode::ECB)
5127 .Padding(PaddingMode::NONE));
5128 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5129 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5130
5131 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5132 .BlockMode(BlockMode::ECB)
5133 .Padding(PaddingMode::NONE)
5134 .Padding(PaddingMode::PKCS7));
5135 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5136 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5137}
5138
5139/*
Selene Huang31ab4042020-04-29 04:22:39 -07005140 * EncryptionOperationsTest.AesWrongPurpose
5141 *
5142 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5143 * specified.
5144 */
5145TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5146 auto err = GenerateKey(AuthorizationSetBuilder()
5147 .Authorization(TAG_NO_AUTH_REQUIRED)
5148 .AesKey(128)
5149 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5150 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5151 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5152 .Padding(PaddingMode::NONE));
5153 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5154 ASSERT_GT(key_blob_.size(), 0U);
5155
5156 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5157 .BlockMode(BlockMode::GCM)
5158 .Padding(PaddingMode::NONE)
5159 .Authorization(TAG_MAC_LENGTH, 128));
5160 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5161
5162 CheckedDeleteKey();
5163
5164 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5165 .Authorization(TAG_NO_AUTH_REQUIRED)
5166 .AesKey(128)
5167 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5168 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5169 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5170 .Padding(PaddingMode::NONE)));
5171
5172 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5173 .BlockMode(BlockMode::GCM)
5174 .Padding(PaddingMode::NONE)
5175 .Authorization(TAG_MAC_LENGTH, 128));
5176 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5177}
5178
5179/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005180 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005181 *
5182 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5183 * multiple of the block size and no padding is specified.
5184 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005185TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5186 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5187 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5188 .Authorization(TAG_NO_AUTH_REQUIRED)
5189 .AesEncryptionKey(128)
5190 .Authorization(TAG_BLOCK_MODE, blockMode)
5191 .Padding(PaddingMode::NONE)));
5192 // Message is slightly shorter than two blocks.
5193 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005194
David Drysdaled2cc8c22021-04-15 13:29:45 +01005195 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5196 AuthorizationSet out_params;
5197 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5198 string ciphertext;
5199 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5200 EXPECT_EQ(0U, ciphertext.size());
5201
5202 CheckedDeleteKey();
5203 }
Selene Huang31ab4042020-04-29 04:22:39 -07005204}
5205
5206/*
5207 * EncryptionOperationsTest.AesEcbPkcs7Padding
5208 *
5209 * Verifies that AES PKCS7 padding works for any message length.
5210 */
5211TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5212 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5213 .Authorization(TAG_NO_AUTH_REQUIRED)
5214 .AesEncryptionKey(128)
5215 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5216 .Padding(PaddingMode::PKCS7)));
5217
5218 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5219
5220 // Try various message lengths; all should work.
5221 for (size_t i = 0; i < 32; ++i) {
5222 string message(i, 'a');
5223 string ciphertext = EncryptMessage(message, params);
5224 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5225 string plaintext = DecryptMessage(ciphertext, params);
5226 EXPECT_EQ(message, plaintext);
5227 }
5228}
5229
5230/*
5231 * EncryptionOperationsTest.AesEcbWrongPadding
5232 *
5233 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5234 * specified.
5235 */
5236TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5237 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5238 .Authorization(TAG_NO_AUTH_REQUIRED)
5239 .AesEncryptionKey(128)
5240 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5241 .Padding(PaddingMode::NONE)));
5242
5243 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5244
5245 // Try various message lengths; all should fail
5246 for (size_t i = 0; i < 32; ++i) {
5247 string message(i, 'a');
5248 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5249 }
5250}
5251
5252/*
5253 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5254 *
5255 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5256 */
5257TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5258 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5259 .Authorization(TAG_NO_AUTH_REQUIRED)
5260 .AesEncryptionKey(128)
5261 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5262 .Padding(PaddingMode::PKCS7)));
5263
5264 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5265
5266 string message = "a";
5267 string ciphertext = EncryptMessage(message, params);
5268 EXPECT_EQ(16U, ciphertext.size());
5269 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005270
Seth Moore7a55ae32021-06-23 14:28:11 -07005271 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5272 ++ciphertext[ciphertext.size() / 2];
5273
5274 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5275 string plaintext;
5276 ErrorCode error = Finish(message, &plaintext);
5277 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
5278 // This is the expected error, we can exit the test now.
5279 return;
5280 } else {
5281 // Very small chance we got valid decryption, so try again.
5282 ASSERT_EQ(error, ErrorCode::OK);
5283 }
5284 }
5285 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005286}
5287
5288vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5289 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005290 EXPECT_TRUE(iv);
5291 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005292}
5293
5294/*
5295 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5296 *
5297 * Verifies that AES CTR mode works.
5298 */
5299TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5300 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5301 .Authorization(TAG_NO_AUTH_REQUIRED)
5302 .AesEncryptionKey(128)
5303 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5304 .Padding(PaddingMode::NONE)));
5305
5306 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5307
5308 string message = "123";
5309 AuthorizationSet out_params;
5310 string ciphertext1 = EncryptMessage(message, params, &out_params);
5311 vector<uint8_t> iv1 = CopyIv(out_params);
5312 EXPECT_EQ(16U, iv1.size());
5313
5314 EXPECT_EQ(message.size(), ciphertext1.size());
5315
5316 out_params.Clear();
5317 string ciphertext2 = EncryptMessage(message, params, &out_params);
5318 vector<uint8_t> iv2 = CopyIv(out_params);
5319 EXPECT_EQ(16U, iv2.size());
5320
5321 // IVs should be random, so ciphertexts should differ.
5322 EXPECT_NE(ciphertext1, ciphertext2);
5323
5324 auto params_iv1 =
5325 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5326 auto params_iv2 =
5327 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5328
5329 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5330 EXPECT_EQ(message, plaintext);
5331 plaintext = DecryptMessage(ciphertext2, params_iv2);
5332 EXPECT_EQ(message, plaintext);
5333
5334 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5335 plaintext = DecryptMessage(ciphertext1, params_iv2);
5336 EXPECT_NE(message, plaintext);
5337 plaintext = DecryptMessage(ciphertext2, params_iv1);
5338 EXPECT_NE(message, plaintext);
5339}
5340
5341/*
5342 * EncryptionOperationsTest.AesIncremental
5343 *
5344 * Verifies that AES works, all modes, when provided data in various size increments.
5345 */
5346TEST_P(EncryptionOperationsTest, AesIncremental) {
5347 auto block_modes = {
5348 BlockMode::ECB,
5349 BlockMode::CBC,
5350 BlockMode::CTR,
5351 BlockMode::GCM,
5352 };
5353
5354 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5355 .Authorization(TAG_NO_AUTH_REQUIRED)
5356 .AesEncryptionKey(128)
5357 .BlockMode(block_modes)
5358 .Padding(PaddingMode::NONE)
5359 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5360
5361 for (int increment = 1; increment <= 240; ++increment) {
5362 for (auto block_mode : block_modes) {
5363 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07005364 auto params =
5365 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
5366 if (block_mode == BlockMode::GCM) {
5367 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
5368 }
Selene Huang31ab4042020-04-29 04:22:39 -07005369
5370 AuthorizationSet output_params;
5371 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
5372
5373 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005374 string to_send;
5375 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07005376 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005377 }
Shawn Willden92d79c02021-02-19 07:31:55 -07005378 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
5379 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07005380
5381 switch (block_mode) {
5382 case BlockMode::GCM:
5383 EXPECT_EQ(message.size() + 16, ciphertext.size());
5384 break;
5385 case BlockMode::CTR:
5386 EXPECT_EQ(message.size(), ciphertext.size());
5387 break;
5388 case BlockMode::CBC:
5389 case BlockMode::ECB:
5390 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
5391 break;
5392 }
5393
5394 auto iv = output_params.GetTagValue(TAG_NONCE);
5395 switch (block_mode) {
5396 case BlockMode::CBC:
5397 case BlockMode::GCM:
5398 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005399 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
5400 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
5401 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005402 break;
5403
5404 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005405 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07005406 break;
5407 }
5408
5409 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
5410 << "Decrypt begin() failed for block mode " << block_mode;
5411
5412 string plaintext;
5413 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07005414 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005415 }
5416 ErrorCode error = Finish(to_send, &plaintext);
5417 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
5418 << " and increment " << increment;
5419 if (error == ErrorCode::OK) {
5420 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
5421 << block_mode << " and increment " << increment;
5422 }
5423 }
5424 }
5425}
5426
5427struct AesCtrSp80038aTestVector {
5428 const char* key;
5429 const char* nonce;
5430 const char* plaintext;
5431 const char* ciphertext;
5432};
5433
5434// These test vectors are taken from
5435// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
5436static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
5437 // AES-128
5438 {
5439 "2b7e151628aed2a6abf7158809cf4f3c",
5440 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5441 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5442 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5443 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
5444 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
5445 },
5446 // AES-192
5447 {
5448 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
5449 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5450 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5451 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5452 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
5453 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
5454 },
5455 // AES-256
5456 {
5457 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
5458 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5459 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5460 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5461 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
5462 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
5463 },
5464};
5465
5466/*
5467 * EncryptionOperationsTest.AesCtrSp80038aTestVector
5468 *
5469 * Verifies AES CTR implementation against SP800-38A test vectors.
5470 */
5471TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
5472 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
5473 for (size_t i = 0; i < 3; i++) {
5474 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
5475 const string key = hex2str(test.key);
5476 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
5477 InvalidSizes.end())
5478 continue;
5479 const string nonce = hex2str(test.nonce);
5480 const string plaintext = hex2str(test.plaintext);
5481 const string ciphertext = hex2str(test.ciphertext);
5482 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
5483 }
5484}
5485
5486/*
5487 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
5488 *
5489 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
5490 */
5491TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
5492 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5493 .Authorization(TAG_NO_AUTH_REQUIRED)
5494 .AesEncryptionKey(128)
5495 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5496 .Padding(PaddingMode::PKCS7)));
5497 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5498 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5499}
5500
5501/*
5502 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
5503 *
5504 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5505 */
5506TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
5507 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5508 .Authorization(TAG_NO_AUTH_REQUIRED)
5509 .AesEncryptionKey(128)
5510 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5511 .Authorization(TAG_CALLER_NONCE)
5512 .Padding(PaddingMode::NONE)));
5513
5514 auto params = AuthorizationSetBuilder()
5515 .BlockMode(BlockMode::CTR)
5516 .Padding(PaddingMode::NONE)
5517 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
5518 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5519
5520 params = AuthorizationSetBuilder()
5521 .BlockMode(BlockMode::CTR)
5522 .Padding(PaddingMode::NONE)
5523 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
5524 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5525
5526 params = AuthorizationSetBuilder()
5527 .BlockMode(BlockMode::CTR)
5528 .Padding(PaddingMode::NONE)
5529 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
5530 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5531}
5532
5533/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005534 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07005535 *
5536 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5537 */
5538TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
5539 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5540 .Authorization(TAG_NO_AUTH_REQUIRED)
5541 .AesEncryptionKey(128)
5542 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5543 .Padding(PaddingMode::NONE)));
5544 // Two-block message.
5545 string message = "12345678901234567890123456789012";
5546 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5547 AuthorizationSet out_params;
5548 string ciphertext1 = EncryptMessage(message, params, &out_params);
5549 vector<uint8_t> iv1 = CopyIv(out_params);
5550 EXPECT_EQ(message.size(), ciphertext1.size());
5551
5552 out_params.Clear();
5553
5554 string ciphertext2 = EncryptMessage(message, params, &out_params);
5555 vector<uint8_t> iv2 = CopyIv(out_params);
5556 EXPECT_EQ(message.size(), ciphertext2.size());
5557
5558 // IVs should be random, so ciphertexts should differ.
5559 EXPECT_NE(ciphertext1, ciphertext2);
5560
5561 params.push_back(TAG_NONCE, iv1);
5562 string plaintext = DecryptMessage(ciphertext1, params);
5563 EXPECT_EQ(message, plaintext);
5564}
5565
5566/*
5567 * EncryptionOperationsTest.AesCallerNonce
5568 *
5569 * Verifies that AES caller-provided nonces work correctly.
5570 */
5571TEST_P(EncryptionOperationsTest, AesCallerNonce) {
5572 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5573 .Authorization(TAG_NO_AUTH_REQUIRED)
5574 .AesEncryptionKey(128)
5575 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5576 .Authorization(TAG_CALLER_NONCE)
5577 .Padding(PaddingMode::NONE)));
5578
5579 string message = "12345678901234567890123456789012";
5580
5581 // Don't specify nonce, should get a random one.
5582 AuthorizationSetBuilder params =
5583 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5584 AuthorizationSet out_params;
5585 string ciphertext = EncryptMessage(message, params, &out_params);
5586 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005587 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005588
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005589 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005590 string plaintext = DecryptMessage(ciphertext, params);
5591 EXPECT_EQ(message, plaintext);
5592
5593 // Now specify a nonce, should also work.
5594 params = AuthorizationSetBuilder()
5595 .BlockMode(BlockMode::CBC)
5596 .Padding(PaddingMode::NONE)
5597 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5598 out_params.Clear();
5599 ciphertext = EncryptMessage(message, params, &out_params);
5600
5601 // Decrypt with correct nonce.
5602 plaintext = DecryptMessage(ciphertext, params);
5603 EXPECT_EQ(message, plaintext);
5604
5605 // Try with wrong nonce.
5606 params = AuthorizationSetBuilder()
5607 .BlockMode(BlockMode::CBC)
5608 .Padding(PaddingMode::NONE)
5609 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
5610 plaintext = DecryptMessage(ciphertext, params);
5611 EXPECT_NE(message, plaintext);
5612}
5613
5614/*
5615 * EncryptionOperationsTest.AesCallerNonceProhibited
5616 *
5617 * Verifies that caller-provided nonces are not permitted when not specified in the key
5618 * authorizations.
5619 */
5620TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
5621 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5622 .Authorization(TAG_NO_AUTH_REQUIRED)
5623 .AesEncryptionKey(128)
5624 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5625 .Padding(PaddingMode::NONE)));
5626
5627 string message = "12345678901234567890123456789012";
5628
5629 // Don't specify nonce, should get a random one.
5630 AuthorizationSetBuilder params =
5631 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5632 AuthorizationSet out_params;
5633 string ciphertext = EncryptMessage(message, params, &out_params);
5634 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005635 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005636
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005637 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005638 string plaintext = DecryptMessage(ciphertext, params);
5639 EXPECT_EQ(message, plaintext);
5640
5641 // Now specify a nonce, should fail
5642 params = AuthorizationSetBuilder()
5643 .BlockMode(BlockMode::CBC)
5644 .Padding(PaddingMode::NONE)
5645 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5646 out_params.Clear();
5647 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5648}
5649
5650/*
5651 * EncryptionOperationsTest.AesGcmRoundTripSuccess
5652 *
5653 * Verifies that AES GCM mode works.
5654 */
5655TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
5656 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5657 .Authorization(TAG_NO_AUTH_REQUIRED)
5658 .AesEncryptionKey(128)
5659 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5660 .Padding(PaddingMode::NONE)
5661 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5662
5663 string aad = "foobar";
5664 string message = "123456789012345678901234567890123456";
5665
5666 auto begin_params = AuthorizationSetBuilder()
5667 .BlockMode(BlockMode::GCM)
5668 .Padding(PaddingMode::NONE)
5669 .Authorization(TAG_MAC_LENGTH, 128);
5670
Selene Huang31ab4042020-04-29 04:22:39 -07005671 // Encrypt
5672 AuthorizationSet begin_out_params;
5673 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5674 << "Begin encrypt";
5675 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005676 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5677 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005678 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5679
5680 // Grab nonce
5681 begin_params.push_back(begin_out_params);
5682
5683 // Decrypt.
5684 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07005685 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005686 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005687 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005688 EXPECT_EQ(message.length(), plaintext.length());
5689 EXPECT_EQ(message, plaintext);
5690}
5691
5692/*
5693 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
5694 *
5695 * Verifies that AES GCM mode works, even when there's a long delay
5696 * between operations.
5697 */
5698TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
5699 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5700 .Authorization(TAG_NO_AUTH_REQUIRED)
5701 .AesEncryptionKey(128)
5702 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5703 .Padding(PaddingMode::NONE)
5704 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5705
5706 string aad = "foobar";
5707 string message = "123456789012345678901234567890123456";
5708
5709 auto begin_params = AuthorizationSetBuilder()
5710 .BlockMode(BlockMode::GCM)
5711 .Padding(PaddingMode::NONE)
5712 .Authorization(TAG_MAC_LENGTH, 128);
5713
Selene Huang31ab4042020-04-29 04:22:39 -07005714 // Encrypt
5715 AuthorizationSet begin_out_params;
5716 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5717 << "Begin encrypt";
5718 string ciphertext;
5719 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005720 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005721 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005722 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005723
5724 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5725
5726 // Grab nonce
5727 begin_params.push_back(begin_out_params);
5728
5729 // Decrypt.
5730 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
5731 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005732 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005733 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005734 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005735 sleep(5);
5736 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
5737 EXPECT_EQ(message.length(), plaintext.length());
5738 EXPECT_EQ(message, plaintext);
5739}
5740
5741/*
5742 * EncryptionOperationsTest.AesGcmDifferentNonces
5743 *
5744 * Verifies that encrypting the same data with different nonces produces different outputs.
5745 */
5746TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
5747 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5748 .Authorization(TAG_NO_AUTH_REQUIRED)
5749 .AesEncryptionKey(128)
5750 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5751 .Padding(PaddingMode::NONE)
5752 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5753 .Authorization(TAG_CALLER_NONCE)));
5754
5755 string aad = "foobar";
5756 string message = "123456789012345678901234567890123456";
5757 string nonce1 = "000000000000";
5758 string nonce2 = "111111111111";
5759 string nonce3 = "222222222222";
5760
5761 string ciphertext1 =
5762 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
5763 string ciphertext2 =
5764 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
5765 string ciphertext3 =
5766 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
5767
5768 ASSERT_NE(ciphertext1, ciphertext2);
5769 ASSERT_NE(ciphertext1, ciphertext3);
5770 ASSERT_NE(ciphertext2, ciphertext3);
5771}
5772
5773/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005774 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
5775 *
5776 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
5777 */
5778TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
5779 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5780 .Authorization(TAG_NO_AUTH_REQUIRED)
5781 .AesEncryptionKey(128)
5782 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5783 .Padding(PaddingMode::NONE)
5784 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5785
5786 string aad = "foobar";
5787 string message = "123456789012345678901234567890123456";
5788
5789 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5790 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5791 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5792
5793 ASSERT_NE(ciphertext1, ciphertext2);
5794 ASSERT_NE(ciphertext1, ciphertext3);
5795 ASSERT_NE(ciphertext2, ciphertext3);
5796}
5797
5798/*
Selene Huang31ab4042020-04-29 04:22:39 -07005799 * EncryptionOperationsTest.AesGcmTooShortTag
5800 *
5801 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
5802 */
5803TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
5804 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5805 .Authorization(TAG_NO_AUTH_REQUIRED)
5806 .AesEncryptionKey(128)
5807 .BlockMode(BlockMode::GCM)
5808 .Padding(PaddingMode::NONE)
5809 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5810 string message = "123456789012345678901234567890123456";
5811 auto params = AuthorizationSetBuilder()
5812 .BlockMode(BlockMode::GCM)
5813 .Padding(PaddingMode::NONE)
5814 .Authorization(TAG_MAC_LENGTH, 96);
5815
5816 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
5817}
5818
5819/*
5820 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
5821 *
5822 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
5823 */
5824TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
5825 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5826 .Authorization(TAG_NO_AUTH_REQUIRED)
5827 .AesEncryptionKey(128)
5828 .BlockMode(BlockMode::GCM)
5829 .Padding(PaddingMode::NONE)
5830 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5831 string aad = "foobar";
5832 string message = "123456789012345678901234567890123456";
5833 auto params = AuthorizationSetBuilder()
5834 .BlockMode(BlockMode::GCM)
5835 .Padding(PaddingMode::NONE)
5836 .Authorization(TAG_MAC_LENGTH, 128);
5837
Selene Huang31ab4042020-04-29 04:22:39 -07005838 // Encrypt
5839 AuthorizationSet begin_out_params;
5840 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5841 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005842 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005843
5844 AuthorizationSet finish_out_params;
5845 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005846 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5847 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005848
5849 params = AuthorizationSetBuilder()
5850 .Authorizations(begin_out_params)
5851 .BlockMode(BlockMode::GCM)
5852 .Padding(PaddingMode::NONE)
5853 .Authorization(TAG_MAC_LENGTH, 96);
5854
5855 // Decrypt.
5856 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
5857}
5858
5859/*
5860 * EncryptionOperationsTest.AesGcmCorruptKey
5861 *
5862 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
5863 */
5864TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
5865 const uint8_t nonce_bytes[] = {
5866 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
5867 };
5868 string nonce = make_string(nonce_bytes);
5869 const uint8_t ciphertext_bytes[] = {
5870 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
5871 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
5872 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
5873 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5874 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5875 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5876 };
5877 string ciphertext = make_string(ciphertext_bytes);
5878
5879 auto params = AuthorizationSetBuilder()
5880 .BlockMode(BlockMode::GCM)
5881 .Padding(PaddingMode::NONE)
5882 .Authorization(TAG_MAC_LENGTH, 128)
5883 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5884
5885 auto import_params = AuthorizationSetBuilder()
5886 .Authorization(TAG_NO_AUTH_REQUIRED)
5887 .AesEncryptionKey(128)
5888 .BlockMode(BlockMode::GCM)
5889 .Padding(PaddingMode::NONE)
5890 .Authorization(TAG_CALLER_NONCE)
5891 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5892
5893 // Import correct key and decrypt
5894 const uint8_t key_bytes[] = {
5895 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5896 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5897 };
5898 string key = make_string(key_bytes);
5899 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5900 string plaintext = DecryptMessage(ciphertext, params);
5901 CheckedDeleteKey();
5902
5903 // Corrupt key and attempt to decrypt
5904 key[0] = 0;
5905 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5906 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5907 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5908 CheckedDeleteKey();
5909}
5910
5911/*
5912 * EncryptionOperationsTest.AesGcmAadNoData
5913 *
5914 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5915 * encrypt.
5916 */
5917TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5918 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5919 .Authorization(TAG_NO_AUTH_REQUIRED)
5920 .AesEncryptionKey(128)
5921 .BlockMode(BlockMode::GCM)
5922 .Padding(PaddingMode::NONE)
5923 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5924
5925 string aad = "1234567890123456";
5926 auto params = AuthorizationSetBuilder()
5927 .BlockMode(BlockMode::GCM)
5928 .Padding(PaddingMode::NONE)
5929 .Authorization(TAG_MAC_LENGTH, 128);
5930
Selene Huang31ab4042020-04-29 04:22:39 -07005931 // Encrypt
5932 AuthorizationSet begin_out_params;
5933 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5934 string ciphertext;
5935 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005936 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5937 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005938 EXPECT_TRUE(finish_out_params.empty());
5939
5940 // Grab nonce
5941 params.push_back(begin_out_params);
5942
5943 // Decrypt.
5944 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005945 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005946 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005947 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005948
5949 EXPECT_TRUE(finish_out_params.empty());
5950
5951 EXPECT_EQ("", plaintext);
5952}
5953
5954/*
5955 * EncryptionOperationsTest.AesGcmMultiPartAad
5956 *
5957 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5958 * chunks.
5959 */
5960TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5961 const size_t tag_bits = 128;
5962 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5963 .Authorization(TAG_NO_AUTH_REQUIRED)
5964 .AesEncryptionKey(128)
5965 .BlockMode(BlockMode::GCM)
5966 .Padding(PaddingMode::NONE)
5967 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5968
5969 string message = "123456789012345678901234567890123456";
5970 auto begin_params = AuthorizationSetBuilder()
5971 .BlockMode(BlockMode::GCM)
5972 .Padding(PaddingMode::NONE)
5973 .Authorization(TAG_MAC_LENGTH, tag_bits);
5974 AuthorizationSet begin_out_params;
5975
Selene Huang31ab4042020-04-29 04:22:39 -07005976 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5977
5978 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005979 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5980 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005981 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005982 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5983 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005984
Selene Huang31ab4042020-04-29 04:22:39 -07005985 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005986 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005987
5988 // Grab nonce.
5989 begin_params.push_back(begin_out_params);
5990
5991 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005992 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005993 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005994 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005995 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005996 EXPECT_EQ(message, plaintext);
5997}
5998
5999/*
6000 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6001 *
6002 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6003 */
6004TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6005 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6006 .Authorization(TAG_NO_AUTH_REQUIRED)
6007 .AesEncryptionKey(128)
6008 .BlockMode(BlockMode::GCM)
6009 .Padding(PaddingMode::NONE)
6010 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6011
6012 string message = "123456789012345678901234567890123456";
6013 auto begin_params = AuthorizationSetBuilder()
6014 .BlockMode(BlockMode::GCM)
6015 .Padding(PaddingMode::NONE)
6016 .Authorization(TAG_MAC_LENGTH, 128);
6017 AuthorizationSet begin_out_params;
6018
Selene Huang31ab4042020-04-29 04:22:39 -07006019 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
6020
Shawn Willden92d79c02021-02-19 07:31:55 -07006021 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006022 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006023 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6024 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006025
David Drysdaled2cc8c22021-04-15 13:29:45 +01006026 // The failure should have already cancelled the operation.
6027 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6028
Shawn Willden92d79c02021-02-19 07:31:55 -07006029 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006030}
6031
6032/*
6033 * EncryptionOperationsTest.AesGcmBadAad
6034 *
6035 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6036 */
6037TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6038 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6039 .Authorization(TAG_NO_AUTH_REQUIRED)
6040 .AesEncryptionKey(128)
6041 .BlockMode(BlockMode::GCM)
6042 .Padding(PaddingMode::NONE)
6043 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6044
6045 string message = "12345678901234567890123456789012";
6046 auto begin_params = AuthorizationSetBuilder()
6047 .BlockMode(BlockMode::GCM)
6048 .Padding(PaddingMode::NONE)
6049 .Authorization(TAG_MAC_LENGTH, 128);
6050
Selene Huang31ab4042020-04-29 04:22:39 -07006051 // Encrypt
6052 AuthorizationSet begin_out_params;
6053 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006054 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006055 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006056 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006057
6058 // Grab nonce
6059 begin_params.push_back(begin_out_params);
6060
Selene Huang31ab4042020-04-29 04:22:39 -07006061 // Decrypt.
6062 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006063 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006064 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006065 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006066}
6067
6068/*
6069 * EncryptionOperationsTest.AesGcmWrongNonce
6070 *
6071 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6072 */
6073TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6074 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6075 .Authorization(TAG_NO_AUTH_REQUIRED)
6076 .AesEncryptionKey(128)
6077 .BlockMode(BlockMode::GCM)
6078 .Padding(PaddingMode::NONE)
6079 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6080
6081 string message = "12345678901234567890123456789012";
6082 auto begin_params = AuthorizationSetBuilder()
6083 .BlockMode(BlockMode::GCM)
6084 .Padding(PaddingMode::NONE)
6085 .Authorization(TAG_MAC_LENGTH, 128);
6086
Selene Huang31ab4042020-04-29 04:22:39 -07006087 // Encrypt
6088 AuthorizationSet begin_out_params;
6089 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006090 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006091 string ciphertext;
6092 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006093 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006094
6095 // Wrong nonce
6096 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6097
6098 // Decrypt.
6099 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006100 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006101 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006102 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006103
6104 // With wrong nonce, should have gotten garbage plaintext (or none).
6105 EXPECT_NE(message, plaintext);
6106}
6107
6108/*
6109 * EncryptionOperationsTest.AesGcmCorruptTag
6110 *
6111 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6112 */
6113TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6114 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6115 .Authorization(TAG_NO_AUTH_REQUIRED)
6116 .AesEncryptionKey(128)
6117 .BlockMode(BlockMode::GCM)
6118 .Padding(PaddingMode::NONE)
6119 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6120
6121 string aad = "1234567890123456";
6122 string message = "123456789012345678901234567890123456";
6123
6124 auto params = AuthorizationSetBuilder()
6125 .BlockMode(BlockMode::GCM)
6126 .Padding(PaddingMode::NONE)
6127 .Authorization(TAG_MAC_LENGTH, 128);
6128
Selene Huang31ab4042020-04-29 04:22:39 -07006129 // Encrypt
6130 AuthorizationSet begin_out_params;
6131 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006132 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006133 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006134 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006135
6136 // Corrupt tag
6137 ++(*ciphertext.rbegin());
6138
6139 // Grab nonce
6140 params.push_back(begin_out_params);
6141
6142 // Decrypt.
6143 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006144 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006145 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006146 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006147}
6148
6149/*
6150 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
6151 *
6152 * Verifies that 3DES is basically functional.
6153 */
6154TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
6155 auto auths = AuthorizationSetBuilder()
6156 .TripleDesEncryptionKey(168)
6157 .BlockMode(BlockMode::ECB)
6158 .Authorization(TAG_NO_AUTH_REQUIRED)
6159 .Padding(PaddingMode::NONE);
6160
6161 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
6162 // Two-block message.
6163 string message = "1234567890123456";
6164 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6165 string ciphertext1 = EncryptMessage(message, inParams);
6166 EXPECT_EQ(message.size(), ciphertext1.size());
6167
6168 string ciphertext2 = EncryptMessage(string(message), inParams);
6169 EXPECT_EQ(message.size(), ciphertext2.size());
6170
6171 // ECB is deterministic.
6172 EXPECT_EQ(ciphertext1, ciphertext2);
6173
6174 string plaintext = DecryptMessage(ciphertext1, inParams);
6175 EXPECT_EQ(message, plaintext);
6176}
6177
6178/*
6179 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
6180 *
6181 * Verifies that CBC keys reject ECB usage.
6182 */
6183TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
6184 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6185 .TripleDesEncryptionKey(168)
6186 .BlockMode(BlockMode::CBC)
6187 .Authorization(TAG_NO_AUTH_REQUIRED)
6188 .Padding(PaddingMode::NONE)));
6189
6190 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6191 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
6192}
6193
6194/*
6195 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
6196 *
6197 * Tests ECB mode with PKCS#7 padding, various message sizes.
6198 */
6199TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
6200 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6201 .TripleDesEncryptionKey(168)
6202 .BlockMode(BlockMode::ECB)
6203 .Authorization(TAG_NO_AUTH_REQUIRED)
6204 .Padding(PaddingMode::PKCS7)));
6205
6206 for (size_t i = 0; i < 32; ++i) {
6207 string message(i, 'a');
6208 auto inParams =
6209 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6210 string ciphertext = EncryptMessage(message, inParams);
6211 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6212 string plaintext = DecryptMessage(ciphertext, inParams);
6213 EXPECT_EQ(message, plaintext);
6214 }
6215}
6216
6217/*
6218 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
6219 *
6220 * Verifies that keys configured for no padding reject PKCS7 padding
6221 */
6222TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
6223 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6224 .TripleDesEncryptionKey(168)
6225 .BlockMode(BlockMode::ECB)
6226 .Authorization(TAG_NO_AUTH_REQUIRED)
6227 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00006228 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6229 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07006230}
6231
6232/*
6233 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
6234 *
6235 * Verifies that corrupted padding is detected.
6236 */
6237TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
6238 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6239 .TripleDesEncryptionKey(168)
6240 .BlockMode(BlockMode::ECB)
6241 .Authorization(TAG_NO_AUTH_REQUIRED)
6242 .Padding(PaddingMode::PKCS7)));
6243
6244 string message = "a";
6245 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
6246 EXPECT_EQ(8U, ciphertext.size());
6247 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006248
6249 AuthorizationSetBuilder begin_params;
6250 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
6251 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07006252
6253 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
6254 ++ciphertext[ciphertext.size() / 2];
6255
6256 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
6257 string plaintext;
6258 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6259 ErrorCode error = Finish(&plaintext);
6260 if (error == ErrorCode::INVALID_ARGUMENT) {
6261 // This is the expected error, we can exit the test now.
6262 return;
6263 } else {
6264 // Very small chance we got valid decryption, so try again.
6265 ASSERT_EQ(error, ErrorCode::OK);
6266 }
6267 }
6268 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006269}
6270
6271struct TripleDesTestVector {
6272 const char* name;
6273 const KeyPurpose purpose;
6274 const BlockMode block_mode;
6275 const PaddingMode padding_mode;
6276 const char* key;
6277 const char* iv;
6278 const char* input;
6279 const char* output;
6280};
6281
6282// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
6283// of the NIST vectors are multiples of the block size.
6284static const TripleDesTestVector kTripleDesTestVectors[] = {
6285 {
6286 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6287 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
6288 "", // IV
6289 "329d86bdf1bc5af4", // input
6290 "d946c2756d78633f", // output
6291 },
6292 {
6293 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6294 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
6295 "", // IV
6296 "6b1540781b01ce1997adae102dbf3c5b", // input
6297 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
6298 },
6299 {
6300 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6301 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
6302 "", // IV
6303 "6daad94ce08acfe7", // input
6304 "660e7d32dcc90e79", // output
6305 },
6306 {
6307 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6308 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
6309 "", // IV
6310 "e9653a0a1f05d31b9acd12d73aa9879d", // input
6311 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
6312 },
6313 {
6314 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6315 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
6316 "43f791134c5647ba", // IV
6317 "dcc153cef81d6f24", // input
6318 "92538bd8af18d3ba", // output
6319 },
6320 {
6321 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6322 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6323 "c2e999cb6249023c", // IV
6324 "c689aee38a301bb316da75db36f110b5", // input
6325 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
6326 },
6327 {
6328 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
6329 PaddingMode::PKCS7,
6330 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6331 "c2e999cb6249023c", // IV
6332 "c689aee38a301bb316da75db36f110b500", // input
6333 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
6334 },
6335 {
6336 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
6337 PaddingMode::PKCS7,
6338 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6339 "c2e999cb6249023c", // IV
6340 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
6341 "c689aee38a301bb316da75db36f110b500", // output
6342 },
6343 {
6344 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6345 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
6346 "41746c7e442d3681", // IV
6347 "c53a7b0ec40600fe", // input
6348 "d4f00eb455de1034", // output
6349 },
6350 {
6351 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6352 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
6353 "3982bc02c3727d45", // IV
6354 "6006f10adef52991fcc777a1238bbb65", // input
6355 "edae09288e9e3bc05746d872b48e3b29", // output
6356 },
6357};
6358
6359/*
6360 * EncryptionOperationsTest.TripleDesTestVector
6361 *
6362 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
6363 */
6364TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
6365 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
6366 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
6367 SCOPED_TRACE(test->name);
6368 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
6369 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
6370 hex2str(test->output));
6371 }
6372}
6373
6374/*
6375 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
6376 *
6377 * Validates CBC mode functionality.
6378 */
6379TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
6380 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6381 .TripleDesEncryptionKey(168)
6382 .BlockMode(BlockMode::CBC)
6383 .Authorization(TAG_NO_AUTH_REQUIRED)
6384 .Padding(PaddingMode::NONE)));
6385
6386 ASSERT_GT(key_blob_.size(), 0U);
6387
6388 // Two-block message.
6389 string message = "1234567890123456";
6390 vector<uint8_t> iv1;
6391 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
6392 EXPECT_EQ(message.size(), ciphertext1.size());
6393
6394 vector<uint8_t> iv2;
6395 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
6396 EXPECT_EQ(message.size(), ciphertext2.size());
6397
6398 // IVs should be random, so ciphertexts should differ.
6399 EXPECT_NE(iv1, iv2);
6400 EXPECT_NE(ciphertext1, ciphertext2);
6401
6402 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
6403 EXPECT_EQ(message, plaintext);
6404}
6405
6406/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006407 * EncryptionOperationsTest.TripleDesInvalidCallerIv
6408 *
6409 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
6410 */
6411TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
6412 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6413 .TripleDesEncryptionKey(168)
6414 .BlockMode(BlockMode::CBC)
6415 .Authorization(TAG_NO_AUTH_REQUIRED)
6416 .Authorization(TAG_CALLER_NONCE)
6417 .Padding(PaddingMode::NONE)));
6418 auto params = AuthorizationSetBuilder()
6419 .BlockMode(BlockMode::CBC)
6420 .Padding(PaddingMode::NONE)
6421 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
6422 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6423}
6424
6425/*
Selene Huang31ab4042020-04-29 04:22:39 -07006426 * EncryptionOperationsTest.TripleDesCallerIv
6427 *
6428 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
6429 */
6430TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
6431 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6432 .TripleDesEncryptionKey(168)
6433 .BlockMode(BlockMode::CBC)
6434 .Authorization(TAG_NO_AUTH_REQUIRED)
6435 .Authorization(TAG_CALLER_NONCE)
6436 .Padding(PaddingMode::NONE)));
6437 string message = "1234567890123456";
6438 vector<uint8_t> iv;
6439 // Don't specify IV, should get a random one.
6440 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6441 EXPECT_EQ(message.size(), ciphertext1.size());
6442 EXPECT_EQ(8U, iv.size());
6443
6444 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6445 EXPECT_EQ(message, plaintext);
6446
6447 // Now specify an IV, should also work.
6448 iv = AidlBuf("abcdefgh");
6449 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
6450
6451 // Decrypt with correct IV.
6452 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
6453 EXPECT_EQ(message, plaintext);
6454
6455 // Now try with wrong IV.
6456 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
6457 EXPECT_NE(message, plaintext);
6458}
6459
6460/*
6461 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
6462 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01006463 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07006464 */
6465TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
6466 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6467 .TripleDesEncryptionKey(168)
6468 .BlockMode(BlockMode::CBC)
6469 .Authorization(TAG_NO_AUTH_REQUIRED)
6470 .Padding(PaddingMode::NONE)));
6471
6472 string message = "12345678901234567890123456789012";
6473 vector<uint8_t> iv;
6474 // Don't specify nonce, should get a random one.
6475 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6476 EXPECT_EQ(message.size(), ciphertext1.size());
6477 EXPECT_EQ(8U, iv.size());
6478
6479 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6480 EXPECT_EQ(message, plaintext);
6481
6482 // Now specify a nonce, should fail.
6483 auto input_params = AuthorizationSetBuilder()
6484 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
6485 .BlockMode(BlockMode::CBC)
6486 .Padding(PaddingMode::NONE);
6487 AuthorizationSet output_params;
6488 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
6489 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6490}
6491
6492/*
6493 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
6494 *
6495 * Verifies that 3DES ECB-only keys do not allow CBC usage.
6496 */
6497TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
6498 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6499 .TripleDesEncryptionKey(168)
6500 .BlockMode(BlockMode::ECB)
6501 .Authorization(TAG_NO_AUTH_REQUIRED)
6502 .Padding(PaddingMode::NONE)));
6503 // Two-block message.
6504 string message = "1234567890123456";
6505 auto begin_params =
6506 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6507 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6508}
6509
6510/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006511 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07006512 *
6513 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
6514 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01006515TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
6516 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
6517 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6518 .TripleDesEncryptionKey(168)
6519 .BlockMode(blockMode)
6520 .Authorization(TAG_NO_AUTH_REQUIRED)
6521 .Padding(PaddingMode::NONE)));
6522 // Message is slightly shorter than two blocks.
6523 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07006524
David Drysdaled2cc8c22021-04-15 13:29:45 +01006525 auto begin_params =
6526 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
6527 AuthorizationSet output_params;
6528 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
6529 string ciphertext;
6530 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
6531
6532 CheckedDeleteKey();
6533 }
Selene Huang31ab4042020-04-29 04:22:39 -07006534}
6535
6536/*
6537 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
6538 *
6539 * Verifies that PKCS7 padding works correctly in CBC mode.
6540 */
6541TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
6542 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6543 .TripleDesEncryptionKey(168)
6544 .BlockMode(BlockMode::CBC)
6545 .Authorization(TAG_NO_AUTH_REQUIRED)
6546 .Padding(PaddingMode::PKCS7)));
6547
6548 // Try various message lengths; all should work.
6549 for (size_t i = 0; i < 32; ++i) {
6550 string message(i, 'a');
6551 vector<uint8_t> iv;
6552 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6553 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6554 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
6555 EXPECT_EQ(message, plaintext);
6556 }
6557}
6558
6559/*
6560 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
6561 *
6562 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
6563 */
6564TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
6565 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6566 .TripleDesEncryptionKey(168)
6567 .BlockMode(BlockMode::CBC)
6568 .Authorization(TAG_NO_AUTH_REQUIRED)
6569 .Padding(PaddingMode::NONE)));
6570
6571 // Try various message lengths; all should fail.
6572 for (size_t i = 0; i < 32; ++i) {
6573 auto begin_params =
6574 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
6575 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6576 }
6577}
6578
6579/*
6580 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
6581 *
6582 * Verifies that corrupted PKCS7 padding is rejected during decryption.
6583 */
6584TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
6585 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6586 .TripleDesEncryptionKey(168)
6587 .BlockMode(BlockMode::CBC)
6588 .Authorization(TAG_NO_AUTH_REQUIRED)
6589 .Padding(PaddingMode::PKCS7)));
6590
6591 string message = "a";
6592 vector<uint8_t> iv;
6593 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6594 EXPECT_EQ(8U, ciphertext.size());
6595 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006596
6597 auto begin_params = AuthorizationSetBuilder()
6598 .BlockMode(BlockMode::CBC)
6599 .Padding(PaddingMode::PKCS7)
6600 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07006601
6602 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
6603 ++ciphertext[ciphertext.size() / 2];
6604 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
6605 string plaintext;
6606 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6607 ErrorCode error = Finish(&plaintext);
6608 if (error == ErrorCode::INVALID_ARGUMENT) {
6609 // This is the expected error, we can exit the test now.
6610 return;
6611 } else {
6612 // Very small chance we got valid decryption, so try again.
6613 ASSERT_EQ(error, ErrorCode::OK);
6614 }
6615 }
6616 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006617}
6618
6619/*
6620 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
6621 *
6622 * Verifies that 3DES CBC works with many different input sizes.
6623 */
6624TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
6625 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6626 .TripleDesEncryptionKey(168)
6627 .BlockMode(BlockMode::CBC)
6628 .Authorization(TAG_NO_AUTH_REQUIRED)
6629 .Padding(PaddingMode::NONE)));
6630
6631 int increment = 7;
6632 string message(240, 'a');
6633 AuthorizationSet input_params =
6634 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6635 AuthorizationSet output_params;
6636 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6637
6638 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07006639 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006640 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006641 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
6642 EXPECT_EQ(message.size(), ciphertext.size());
6643
6644 // Move TAG_NONCE into input_params
6645 input_params = output_params;
6646 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
6647 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
6648 output_params.Clear();
6649
6650 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
6651 string plaintext;
6652 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006653 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006654 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
6655 EXPECT_EQ(ciphertext.size(), plaintext.size());
6656 EXPECT_EQ(message, plaintext);
6657}
6658
6659INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
6660
6661typedef KeyMintAidlTestBase MaxOperationsTest;
6662
6663/*
6664 * MaxOperationsTest.TestLimitAes
6665 *
6666 * Verifies that the max uses per boot tag works correctly with AES keys.
6667 */
6668TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006669 if (SecLevel() == SecurityLevel::STRONGBOX) {
6670 GTEST_SKIP() << "Test not applicable to StrongBox device";
6671 }
Selene Huang31ab4042020-04-29 04:22:39 -07006672
6673 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6674 .Authorization(TAG_NO_AUTH_REQUIRED)
6675 .AesEncryptionKey(128)
6676 .EcbMode()
6677 .Padding(PaddingMode::NONE)
6678 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
6679
6680 string message = "1234567890123456";
6681
6682 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6683
6684 EncryptMessage(message, params);
6685 EncryptMessage(message, params);
6686 EncryptMessage(message, params);
6687
6688 // Fourth time should fail.
6689 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
6690}
6691
6692/*
Qi Wud22ec842020-11-26 13:27:53 +08006693 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07006694 *
6695 * Verifies that the max uses per boot tag works correctly with RSA keys.
6696 */
6697TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006698 if (SecLevel() == SecurityLevel::STRONGBOX) {
6699 GTEST_SKIP() << "Test not applicable to StrongBox device";
6700 }
Selene Huang31ab4042020-04-29 04:22:39 -07006701
6702 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6703 .Authorization(TAG_NO_AUTH_REQUIRED)
6704 .RsaSigningKey(1024, 65537)
6705 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006706 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
6707 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006708
6709 string message = "1234567890123456";
6710
6711 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6712
6713 SignMessage(message, params);
6714 SignMessage(message, params);
6715 SignMessage(message, params);
6716
6717 // Fourth time should fail.
6718 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
6719}
6720
6721INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
6722
Qi Wud22ec842020-11-26 13:27:53 +08006723typedef KeyMintAidlTestBase UsageCountLimitTest;
6724
6725/*
Qi Wubeefae42021-01-28 23:16:37 +08006726 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006727 *
Qi Wubeefae42021-01-28 23:16:37 +08006728 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006729 */
Qi Wubeefae42021-01-28 23:16:37 +08006730TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006731 if (SecLevel() == SecurityLevel::STRONGBOX) {
6732 GTEST_SKIP() << "Test not applicable to StrongBox device";
6733 }
Qi Wud22ec842020-11-26 13:27:53 +08006734
6735 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6736 .Authorization(TAG_NO_AUTH_REQUIRED)
6737 .AesEncryptionKey(128)
6738 .EcbMode()
6739 .Padding(PaddingMode::NONE)
6740 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
6741
6742 // Check the usage count limit tag appears in the authorizations.
6743 AuthorizationSet auths;
6744 for (auto& entry : key_characteristics_) {
6745 auths.push_back(AuthorizationSet(entry.authorizations));
6746 }
6747 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6748 << "key usage count limit " << 1U << " missing";
6749
6750 string message = "1234567890123456";
6751 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6752
Qi Wubeefae42021-01-28 23:16:37 +08006753 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6754 AuthorizationSet keystore_auths =
6755 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6756
Qi Wud22ec842020-11-26 13:27:53 +08006757 // First usage of AES key should work.
6758 EncryptMessage(message, params);
6759
Qi Wud22ec842020-11-26 13:27:53 +08006760 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6761 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6762 // must be invalidated from secure storage (such as RPMB partition).
6763 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6764 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006765 // Usage count limit tag is enforced by keystore, keymint does nothing.
6766 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08006767 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6768 }
6769}
6770
6771/*
Qi Wubeefae42021-01-28 23:16:37 +08006772 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006773 *
Qi Wubeefae42021-01-28 23:16:37 +08006774 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006775 */
Qi Wubeefae42021-01-28 23:16:37 +08006776TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006777 if (SecLevel() == SecurityLevel::STRONGBOX) {
6778 GTEST_SKIP() << "Test not applicable to StrongBox device";
6779 }
Qi Wubeefae42021-01-28 23:16:37 +08006780
6781 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6782 .Authorization(TAG_NO_AUTH_REQUIRED)
6783 .AesEncryptionKey(128)
6784 .EcbMode()
6785 .Padding(PaddingMode::NONE)
6786 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
6787
6788 // Check the usage count limit tag appears in the authorizations.
6789 AuthorizationSet auths;
6790 for (auto& entry : key_characteristics_) {
6791 auths.push_back(AuthorizationSet(entry.authorizations));
6792 }
6793 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6794 << "key usage count limit " << 3U << " missing";
6795
6796 string message = "1234567890123456";
6797 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6798
6799 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6800 AuthorizationSet keystore_auths =
6801 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6802
6803 EncryptMessage(message, params);
6804 EncryptMessage(message, params);
6805 EncryptMessage(message, params);
6806
6807 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6808 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6809 // must be invalidated from secure storage (such as RPMB partition).
6810 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6811 } else {
6812 // Usage count limit tag is enforced by keystore, keymint does nothing.
6813 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
6814 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6815 }
6816}
6817
6818/*
6819 * UsageCountLimitTest.TestSingleUseRsa
6820 *
6821 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
6822 */
6823TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006824 if (SecLevel() == SecurityLevel::STRONGBOX) {
6825 GTEST_SKIP() << "Test not applicable to StrongBox device";
6826 }
Qi Wud22ec842020-11-26 13:27:53 +08006827
6828 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6829 .Authorization(TAG_NO_AUTH_REQUIRED)
6830 .RsaSigningKey(1024, 65537)
6831 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006832 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6833 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08006834
6835 // Check the usage count limit tag appears in the authorizations.
6836 AuthorizationSet auths;
6837 for (auto& entry : key_characteristics_) {
6838 auths.push_back(AuthorizationSet(entry.authorizations));
6839 }
6840 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6841 << "key usage count limit " << 1U << " missing";
6842
6843 string message = "1234567890123456";
6844 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6845
Qi Wubeefae42021-01-28 23:16:37 +08006846 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6847 AuthorizationSet keystore_auths =
6848 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6849
Qi Wud22ec842020-11-26 13:27:53 +08006850 // First usage of RSA key should work.
6851 SignMessage(message, params);
6852
Qi Wud22ec842020-11-26 13:27:53 +08006853 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6854 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6855 // must be invalidated from secure storage (such as RPMB partition).
6856 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6857 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006858 // Usage count limit tag is enforced by keystore, keymint does nothing.
6859 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
6860 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6861 }
6862}
6863
6864/*
6865 * UsageCountLimitTest.TestLimitUseRsa
6866 *
6867 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
6868 */
6869TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006870 if (SecLevel() == SecurityLevel::STRONGBOX) {
6871 GTEST_SKIP() << "Test not applicable to StrongBox device";
6872 }
Qi Wubeefae42021-01-28 23:16:37 +08006873
6874 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6875 .Authorization(TAG_NO_AUTH_REQUIRED)
6876 .RsaSigningKey(1024, 65537)
6877 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006878 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
6879 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08006880
6881 // Check the usage count limit tag appears in the authorizations.
6882 AuthorizationSet auths;
6883 for (auto& entry : key_characteristics_) {
6884 auths.push_back(AuthorizationSet(entry.authorizations));
6885 }
6886 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6887 << "key usage count limit " << 3U << " missing";
6888
6889 string message = "1234567890123456";
6890 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6891
6892 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6893 AuthorizationSet keystore_auths =
6894 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6895
6896 SignMessage(message, params);
6897 SignMessage(message, params);
6898 SignMessage(message, params);
6899
6900 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6901 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6902 // must be invalidated from secure storage (such as RPMB partition).
6903 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6904 } else {
6905 // Usage count limit tag is enforced by keystore, keymint does nothing.
6906 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006907 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6908 }
6909}
6910
Qi Wu8e727f72021-02-11 02:49:33 +08006911/*
6912 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6913 *
6914 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6915 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6916 * in hardware.
6917 */
6918TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01006919 if (SecLevel() == SecurityLevel::STRONGBOX) {
6920 GTEST_SKIP() << "Test not applicable to StrongBox device";
6921 }
Qi Wu8e727f72021-02-11 02:49:33 +08006922
6923 auto error = GenerateKey(AuthorizationSetBuilder()
6924 .RsaSigningKey(2048, 65537)
6925 .Digest(Digest::NONE)
6926 .Padding(PaddingMode::NONE)
6927 .Authorization(TAG_NO_AUTH_REQUIRED)
6928 .Authorization(TAG_ROLLBACK_RESISTANCE)
6929 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006930 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6931 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08006932 }
David Drysdale513bf122021-10-06 11:53:13 +01006933
6934 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6935 ASSERT_EQ(ErrorCode::OK, error);
6936 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6937 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6938 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6939
6940 // The KeyMint should also enforce single use key in hardware when it supports rollback
6941 // resistance.
6942 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6943 .Authorization(TAG_NO_AUTH_REQUIRED)
6944 .RsaSigningKey(1024, 65537)
6945 .NoDigestOrPadding()
6946 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6947 .SetDefaultValidity()));
6948
6949 // Check the usage count limit tag appears in the hardware authorizations.
6950 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6951 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6952 << "key usage count limit " << 1U << " missing";
6953
6954 string message = "1234567890123456";
6955 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6956
6957 // First usage of RSA key should work.
6958 SignMessage(message, params);
6959
6960 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6961 // must be invalidated from secure storage (such as RPMB partition).
6962 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08006963}
6964
Qi Wud22ec842020-11-26 13:27:53 +08006965INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6966
David Drysdale7de9feb2021-03-05 14:56:19 +00006967typedef KeyMintAidlTestBase GetHardwareInfoTest;
6968
6969TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6970 // Retrieving hardware info should give the same result each time.
6971 KeyMintHardwareInfo info;
6972 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6973 KeyMintHardwareInfo info2;
6974 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6975 EXPECT_EQ(info, info2);
6976}
6977
6978INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6979
Selene Huang31ab4042020-04-29 04:22:39 -07006980typedef KeyMintAidlTestBase AddEntropyTest;
6981
6982/*
6983 * AddEntropyTest.AddEntropy
6984 *
6985 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6986 * is actually added.
6987 */
6988TEST_P(AddEntropyTest, AddEntropy) {
6989 string data = "foo";
6990 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6991}
6992
6993/*
6994 * AddEntropyTest.AddEmptyEntropy
6995 *
6996 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6997 */
6998TEST_P(AddEntropyTest, AddEmptyEntropy) {
6999 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7000}
7001
7002/*
7003 * AddEntropyTest.AddLargeEntropy
7004 *
7005 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7006 */
7007TEST_P(AddEntropyTest, AddLargeEntropy) {
7008 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7009}
7010
David Drysdalebb3d85e2021-04-13 11:15:51 +01007011/*
7012 * AddEntropyTest.AddTooLargeEntropy
7013 *
7014 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7015 */
7016TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7017 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7018 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7019}
7020
Selene Huang31ab4042020-04-29 04:22:39 -07007021INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7022
Selene Huang31ab4042020-04-29 04:22:39 -07007023typedef KeyMintAidlTestBase KeyDeletionTest;
7024
7025/**
7026 * KeyDeletionTest.DeleteKey
7027 *
7028 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7029 * valid key blob.
7030 */
7031TEST_P(KeyDeletionTest, DeleteKey) {
7032 auto error = GenerateKey(AuthorizationSetBuilder()
7033 .RsaSigningKey(2048, 65537)
7034 .Digest(Digest::NONE)
7035 .Padding(PaddingMode::NONE)
7036 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007037 .Authorization(TAG_ROLLBACK_RESISTANCE)
7038 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007039 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7040 GTEST_SKIP() << "Rollback resistance not supported";
7041 }
Selene Huang31ab4042020-04-29 04:22:39 -07007042
7043 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007044 ASSERT_EQ(ErrorCode::OK, error);
7045 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7046 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007047
David Drysdale513bf122021-10-06 11:53:13 +01007048 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007049
David Drysdale513bf122021-10-06 11:53:13 +01007050 string message = "12345678901234567890123456789012";
7051 AuthorizationSet begin_out_params;
7052 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7053 Begin(KeyPurpose::SIGN, key_blob_,
7054 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7055 &begin_out_params));
7056 AbortIfNeeded();
7057 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007058}
7059
7060/**
7061 * KeyDeletionTest.DeleteInvalidKey
7062 *
7063 * This test checks that the HAL excepts invalid key blobs..
7064 */
7065TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7066 // Generate key just to check if rollback protection is implemented
7067 auto error = GenerateKey(AuthorizationSetBuilder()
7068 .RsaSigningKey(2048, 65537)
7069 .Digest(Digest::NONE)
7070 .Padding(PaddingMode::NONE)
7071 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007072 .Authorization(TAG_ROLLBACK_RESISTANCE)
7073 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007074 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7075 GTEST_SKIP() << "Rollback resistance not supported";
7076 }
Selene Huang31ab4042020-04-29 04:22:39 -07007077
7078 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007079 ASSERT_EQ(ErrorCode::OK, error);
7080 AuthorizationSet enforced(SecLevelAuthorizations());
7081 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007082
David Drysdale513bf122021-10-06 11:53:13 +01007083 // Delete the key we don't care about the result at this point.
7084 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007085
David Drysdale513bf122021-10-06 11:53:13 +01007086 // Now create an invalid key blob and delete it.
7087 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007088
David Drysdale513bf122021-10-06 11:53:13 +01007089 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007090}
7091
7092/**
7093 * KeyDeletionTest.DeleteAllKeys
7094 *
7095 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7096 *
7097 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7098 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7099 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7100 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7101 * credentials stored in Keystore/Keymint.
7102 */
7103TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007104 if (!arm_deleteAllKeys) {
7105 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7106 return;
7107 }
Selene Huang31ab4042020-04-29 04:22:39 -07007108 auto error = GenerateKey(AuthorizationSetBuilder()
7109 .RsaSigningKey(2048, 65537)
7110 .Digest(Digest::NONE)
7111 .Padding(PaddingMode::NONE)
7112 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007113 .Authorization(TAG_ROLLBACK_RESISTANCE)
7114 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007115 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7116 GTEST_SKIP() << "Rollback resistance not supported";
7117 }
Selene Huang31ab4042020-04-29 04:22:39 -07007118
7119 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007120 ASSERT_EQ(ErrorCode::OK, error);
7121 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7122 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007123
David Drysdale513bf122021-10-06 11:53:13 +01007124 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007125
David Drysdale513bf122021-10-06 11:53:13 +01007126 string message = "12345678901234567890123456789012";
7127 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07007128
David Drysdale513bf122021-10-06 11:53:13 +01007129 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7130 Begin(KeyPurpose::SIGN, key_blob_,
7131 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7132 &begin_out_params));
7133 AbortIfNeeded();
7134 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007135}
7136
7137INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
7138
David Drysdaled2cc8c22021-04-15 13:29:45 +01007139typedef KeyMintAidlTestBase KeyUpgradeTest;
7140
7141/**
7142 * KeyUpgradeTest.UpgradeInvalidKey
7143 *
7144 * This test checks that the HAL excepts invalid key blobs..
7145 */
7146TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
7147 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
7148
7149 std::vector<uint8_t> new_blob;
7150 Status result = keymint_->upgradeKey(key_blob,
7151 AuthorizationSetBuilder()
7152 .Authorization(TAG_APPLICATION_ID, "clientid")
7153 .Authorization(TAG_APPLICATION_DATA, "appdata")
7154 .vector_data(),
7155 &new_blob);
7156 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
7157}
7158
7159INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
7160
Selene Huang31ab4042020-04-29 04:22:39 -07007161using UpgradeKeyTest = KeyMintAidlTestBase;
7162
7163/*
7164 * UpgradeKeyTest.UpgradeKey
7165 *
7166 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
7167 */
7168TEST_P(UpgradeKeyTest, UpgradeKey) {
7169 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7170 .AesEncryptionKey(128)
7171 .Padding(PaddingMode::NONE)
7172 .Authorization(TAG_NO_AUTH_REQUIRED)));
7173
7174 auto result = UpgradeKey(key_blob_);
7175
7176 // Key doesn't need upgrading. Should get okay, but no new key blob.
7177 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
7178}
7179
7180INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
7181
7182using ClearOperationsTest = KeyMintAidlTestBase;
7183
7184/*
7185 * ClearSlotsTest.TooManyOperations
7186 *
7187 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
7188 * operations are started without being finished or aborted. Also verifies
7189 * that aborting the operations clears the operations.
7190 *
7191 */
7192TEST_P(ClearOperationsTest, TooManyOperations) {
7193 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7194 .Authorization(TAG_NO_AUTH_REQUIRED)
7195 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08007196 .Padding(PaddingMode::NONE)
7197 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007198
7199 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
7200 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08007201 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07007202 AuthorizationSet out_params;
7203 ErrorCode result;
7204 size_t i;
7205
7206 for (i = 0; i < max_operations; i++) {
7207 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
7208 if (ErrorCode::OK != result) {
7209 break;
7210 }
7211 }
7212 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
7213 // Try again just in case there's a weird overflow bug
7214 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
7215 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
7216 for (size_t j = 0; j < i; j++) {
7217 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
7218 << "Aboort failed for i = " << j << std::endl;
7219 }
7220 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
7221 AbortIfNeeded();
7222}
7223
7224INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
7225
7226typedef KeyMintAidlTestBase TransportLimitTest;
7227
7228/*
David Drysdale7de9feb2021-03-05 14:56:19 +00007229 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07007230 *
7231 * Verifies that passing input data to finish succeeds as expected.
7232 */
7233TEST_P(TransportLimitTest, LargeFinishInput) {
7234 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7235 .Authorization(TAG_NO_AUTH_REQUIRED)
7236 .AesEncryptionKey(128)
7237 .BlockMode(BlockMode::ECB)
7238 .Padding(PaddingMode::NONE)));
7239
7240 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
7241 auto cipher_params =
7242 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7243
7244 AuthorizationSet out_params;
7245 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
7246
7247 string plain_message = std::string(1 << msg_size, 'x');
7248 string encrypted_message;
7249 auto rc = Finish(plain_message, &encrypted_message);
7250
7251 EXPECT_EQ(ErrorCode::OK, rc);
7252 EXPECT_EQ(plain_message.size(), encrypted_message.size())
7253 << "Encrypt finish returned OK, but did not consume all of the given input";
7254 cipher_params.push_back(out_params);
7255
7256 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
7257
7258 string decrypted_message;
7259 rc = Finish(encrypted_message, &decrypted_message);
7260 EXPECT_EQ(ErrorCode::OK, rc);
7261 EXPECT_EQ(plain_message.size(), decrypted_message.size())
7262 << "Decrypt finish returned OK, did not consume all of the given input";
7263 }
7264}
7265
7266INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
7267
Seth Moored79a0ec2021-12-13 20:03:33 +00007268static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05007269 switch (curve) {
7270 case EcCurve::P_224:
7271 return NID_secp224r1;
7272 case EcCurve::P_256:
7273 return NID_X9_62_prime256v1;
7274 case EcCurve::P_384:
7275 return NID_secp384r1;
7276 case EcCurve::P_521:
7277 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00007278 case EcCurve::CURVE_25519:
7279 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05007280 }
7281}
7282
David Drysdale42fe1892021-10-14 14:43:46 +01007283class KeyAgreementTest : public KeyMintAidlTestBase {
7284 protected:
7285 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
7286 std::vector<uint8_t>* localPublicKey) {
7287 // Generate EC key locally (with access to private key material)
7288 if (localCurve == EcCurve::CURVE_25519) {
7289 uint8_t privKeyData[32];
7290 uint8_t pubKeyData[32];
7291 X25519_keypair(pubKeyData, privKeyData);
7292 *localPublicKey = vector<uint8_t>(pubKeyData, pubKeyData + 32);
7293 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
7294 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
7295 } else {
7296 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
7297 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
7298 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
7299 ASSERT_NE(group, nullptr);
7300 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
7301 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
7302 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
7303 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
7304
7305 // Get encoded form of the public part of the locally generated key...
7306 unsigned char* p = nullptr;
7307 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
7308 ASSERT_GT(localPublicKeySize, 0);
7309 *localPublicKey =
7310 vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
7311 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
7312 OPENSSL_free(p);
7313 }
7314 }
7315
7316 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
7317 vector<uint8_t> challenge = {0x41, 0x42};
7318 ErrorCode result =
7319 GenerateKey(AuthorizationSetBuilder()
7320 .Authorization(TAG_NO_AUTH_REQUIRED)
7321 .Authorization(TAG_EC_CURVE, curve)
7322 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7323 .Authorization(TAG_ALGORITHM, Algorithm::EC)
7324 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
7325 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
7326 .SetDefaultValidity());
7327 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
7328 ASSERT_GT(cert_chain_.size(), 0);
7329 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7330 ASSERT_NE(kmKeyCert, nullptr);
7331 // Check that keyAgreement (bit 4) is set in KeyUsage
7332 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
7333 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
7334 ASSERT_NE(*kmPubKey, nullptr);
7335 if (dump_Attestations) {
7336 for (size_t n = 0; n < cert_chain_.size(); n++) {
7337 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
7338 }
7339 }
7340 }
7341
7342 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
7343 const std::vector<uint8_t>& localPublicKey) {
7344 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7345 string ZabFromKeyMintStr;
7346 ASSERT_EQ(ErrorCode::OK,
7347 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
7348 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
7349 vector<uint8_t> ZabFromTest;
7350
7351 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
7352 size_t kmPubKeySize = 32;
7353 uint8_t kmPubKeyData[32];
7354 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7355 ASSERT_EQ(kmPubKeySize, 32);
7356
7357 uint8_t localPrivKeyData[32];
7358 size_t localPrivKeySize = 32;
7359 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
7360 &localPrivKeySize));
7361 ASSERT_EQ(localPrivKeySize, 32);
7362
7363 uint8_t sharedKey[32];
7364 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
7365 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
7366 } else {
7367 // Perform local ECDH between the two keys so we can check if we get the same Zab..
7368 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
7369 ASSERT_NE(ctx, nullptr);
7370 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
7371 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
7372 size_t ZabFromTestLen = 0;
7373 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
7374 ZabFromTest.resize(ZabFromTestLen);
7375 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
7376 }
7377 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
7378 }
7379};
7380
David Zeuthene0c40892021-01-08 12:54:11 -05007381/*
7382 * KeyAgreementTest.Ecdh
7383 *
David Drysdale42fe1892021-10-14 14:43:46 +01007384 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05007385 */
7386TEST_P(KeyAgreementTest, Ecdh) {
7387 // Because it's possible to use this API with keys on different curves, we
7388 // check all N^2 combinations where N is the number of supported
7389 // curves.
7390 //
7391 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
7392 // lot more curves we can be smart about things and just pick |otherCurve| so
7393 // it's not |curve| and that way we end up with only 2*N runs
7394 //
7395 for (auto curve : ValidCurves()) {
7396 for (auto localCurve : ValidCurves()) {
7397 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007398 EVP_PKEY_Ptr localPrivKey;
7399 vector<uint8_t> localPublicKey;
7400 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007401
7402 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007403 EVP_PKEY_Ptr kmPubKey;
7404 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007405
7406 // Now that we have the two keys, we ask KeyMint to perform ECDH...
7407 if (curve != localCurve) {
7408 // If the keys are using different curves KeyMint should fail with
7409 // ErrorCode:INVALID_ARGUMENT. Check that.
7410 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7411 string ZabFromKeyMintStr;
7412 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01007413 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05007414 &ZabFromKeyMintStr));
7415
7416 } else {
7417 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01007418 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007419 }
7420
7421 CheckedDeleteKey();
7422 }
7423 }
7424}
7425
David Drysdale42fe1892021-10-14 14:43:46 +01007426/*
7427 * KeyAgreementTest.EcdhCurve25519
7428 *
7429 * Verifies that ECDH works for curve25519. This is also covered by the general
7430 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
7431 * KeyMint 1.0.
7432 */
7433TEST_P(KeyAgreementTest, EcdhCurve25519) {
7434 if (!Curve25519Supported()) {
7435 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7436 }
7437
7438 // Generate EC key in KeyMint (only access to public key material)
7439 EcCurve curve = EcCurve::CURVE_25519;
7440 EVP_PKEY_Ptr kmPubKey = nullptr;
7441 GenerateKeyMintEcKey(curve, &kmPubKey);
7442
7443 // Generate EC key on same curve locally (with access to private key material).
7444 EVP_PKEY_Ptr privKey;
7445 vector<uint8_t> encodedPublicKey;
7446 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7447
7448 // Agree on a key between local and KeyMint and check it.
7449 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7450
7451 CheckedDeleteKey();
7452}
7453
7454/*
7455 * KeyAgreementTest.EcdhCurve25519Imported
7456 *
7457 * Verifies that ECDH works for an imported curve25519 key.
7458 */
7459TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
7460 if (!Curve25519Supported()) {
7461 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7462 }
7463
7464 // Import x25519 key into KeyMint.
7465 EcCurve curve = EcCurve::CURVE_25519;
7466 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
7467 .Authorization(TAG_NO_AUTH_REQUIRED)
7468 .EcdsaKey(EcCurve::CURVE_25519)
7469 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7470 .SetDefaultValidity(),
7471 KeyFormat::PKCS8, x25519_pkcs8_key));
7472 ASSERT_GT(cert_chain_.size(), 0);
7473 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7474 ASSERT_NE(kmKeyCert, nullptr);
7475 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
7476 ASSERT_NE(kmPubKey.get(), nullptr);
7477
7478 // Expect the import to emit corresponding public key data.
7479 size_t kmPubKeySize = 32;
7480 uint8_t kmPubKeyData[32];
7481 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7482 ASSERT_EQ(kmPubKeySize, 32);
7483 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
7484 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
7485
7486 // Generate EC key on same curve locally (with access to private key material).
7487 EVP_PKEY_Ptr privKey;
7488 vector<uint8_t> encodedPublicKey;
7489 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7490
7491 // Agree on a key between local and KeyMint and check it.
7492 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7493
7494 CheckedDeleteKey();
7495}
7496
7497/*
7498 * KeyAgreementTest.EcdhCurve25519InvalidSize
7499 *
7500 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
7501 */
7502TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
7503 if (!Curve25519Supported()) {
7504 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7505 }
7506
7507 // Generate EC key in KeyMint (only access to public key material)
7508 EcCurve curve = EcCurve::CURVE_25519;
7509 EVP_PKEY_Ptr kmPubKey = nullptr;
7510 GenerateKeyMintEcKey(curve, &kmPubKey);
7511
7512 // Generate EC key on same curve locally (with access to private key material).
7513 EVP_PKEY_Ptr privKey;
7514 vector<uint8_t> encodedPublicKey;
7515 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7516
7517 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7518 string ZabFromKeyMintStr;
7519 // Send in an incomplete public key.
7520 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
7521 &ZabFromKeyMintStr));
7522
7523 CheckedDeleteKey();
7524}
7525
7526/*
7527 * KeyAgreementTest.EcdhCurve25519Mismatch
7528 *
7529 * Verifies that ECDH fails between curve25519 and other curves.
7530 */
7531TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
7532 if (!Curve25519Supported()) {
7533 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7534 }
7535
7536 // Generate EC key in KeyMint (only access to public key material)
7537 EcCurve curve = EcCurve::CURVE_25519;
7538 EVP_PKEY_Ptr kmPubKey = nullptr;
7539 GenerateKeyMintEcKey(curve, &kmPubKey);
7540
7541 for (auto localCurve : ValidCurves()) {
7542 if (localCurve == curve) {
7543 continue;
7544 }
7545 // Generate EC key on a different curve locally (with access to private key material).
7546 EVP_PKEY_Ptr privKey;
7547 vector<uint8_t> encodedPublicKey;
7548 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
7549
7550 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7551 string ZabFromKeyMintStr;
7552 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
7553 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
7554 &ZabFromKeyMintStr));
7555 }
7556
7557 CheckedDeleteKey();
7558}
7559
David Zeuthene0c40892021-01-08 12:54:11 -05007560INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
7561
David Drysdaled2cc8c22021-04-15 13:29:45 +01007562using DestroyAttestationIdsTest = KeyMintAidlTestBase;
7563
7564// This is a problematic test, as it can render the device under test permanently unusable.
7565// Re-enable and run at your own risk.
7566TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
7567 auto result = DestroyAttestationIds();
7568 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
7569}
7570
7571INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
7572
Shawn Willdend659c7c2021-02-19 14:51:51 -07007573using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007574
David Drysdaledb0dcf52021-05-18 11:43:31 +01007575/*
7576 * EarlyBootKeyTest.CreateEarlyBootKeys
7577 *
7578 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
7579 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007580TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01007581 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007582 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7583 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7584
David Drysdaleadfe6112021-05-27 12:00:53 +01007585 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
7586 ASSERT_GT(keyData.blob.size(), 0U);
7587 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7588 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7589 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007590 CheckedDeleteKey(&aesKeyData.blob);
7591 CheckedDeleteKey(&hmacKeyData.blob);
7592 CheckedDeleteKey(&rsaKeyData.blob);
7593 CheckedDeleteKey(&ecdsaKeyData.blob);
7594}
7595
David Drysdaledb0dcf52021-05-18 11:43:31 +01007596/*
David Drysdaleadfe6112021-05-27 12:00:53 +01007597 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
7598 *
7599 * Verifies that creating an early boot key with attestation succeeds.
7600 */
7601TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
7602 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
7603 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
7604 builder->AttestationChallenge("challenge");
7605 builder->AttestationApplicationId("app_id");
7606 });
7607
7608 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
7609 ASSERT_GT(keyData.blob.size(), 0U);
7610 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7611 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7612 }
7613 CheckedDeleteKey(&aesKeyData.blob);
7614 CheckedDeleteKey(&hmacKeyData.blob);
7615 CheckedDeleteKey(&rsaKeyData.blob);
7616 CheckedDeleteKey(&ecdsaKeyData.blob);
7617}
7618
7619/*
7620 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01007621 *
7622 * Verifies that using early boot keys at a later stage fails.
7623 */
7624TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
7625 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7626 .Authorization(TAG_NO_AUTH_REQUIRED)
7627 .Authorization(TAG_EARLY_BOOT_ONLY)
7628 .HmacKey(128)
7629 .Digest(Digest::SHA_2_256)
7630 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
7631 AuthorizationSet output_params;
7632 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
7633 AuthorizationSetBuilder()
7634 .Digest(Digest::SHA_2_256)
7635 .Authorization(TAG_MAC_LENGTH, 256),
7636 &output_params));
7637}
7638
7639/*
7640 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
7641 *
7642 * Verifies that importing early boot keys fails.
7643 */
7644TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
7645 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
7646 .Authorization(TAG_NO_AUTH_REQUIRED)
7647 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01007648 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01007649 .Digest(Digest::SHA_2_256)
7650 .SetDefaultValidity(),
7651 KeyFormat::PKCS8, ec_256_key));
7652}
7653
David Drysdaled2cc8c22021-04-15 13:29:45 +01007654// 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 +00007655// boot stage, which no proper Android device is by the time we can run VTS. To use this,
7656// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
7657// early boot, so you'll have to reboot between runs.
7658TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
7659 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7660 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7661 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
7662 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7663 EXPECT_TRUE(
7664 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7665 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7666 EXPECT_TRUE(
7667 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7668
7669 // Should be able to use keys, since early boot has not ended
7670 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7671 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
7672 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
7673 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
7674
7675 // End early boot
7676 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
7677 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
7678
7679 // Should not be able to use already-created keys.
7680 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
7681 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
7682 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
7683 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
7684
7685 CheckedDeleteKey(&aesKeyData.blob);
7686 CheckedDeleteKey(&hmacKeyData.blob);
7687 CheckedDeleteKey(&rsaKeyData.blob);
7688 CheckedDeleteKey(&ecdsaKeyData.blob);
7689
7690 // Should not be able to create new keys
7691 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
7692 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
7693
7694 CheckedDeleteKey(&aesKeyData.blob);
7695 CheckedDeleteKey(&hmacKeyData.blob);
7696 CheckedDeleteKey(&rsaKeyData.blob);
7697 CheckedDeleteKey(&ecdsaKeyData.blob);
7698}
Shawn Willdend659c7c2021-02-19 14:51:51 -07007699
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007700INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
7701
Shawn Willdend659c7c2021-02-19 14:51:51 -07007702using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007703
7704// This may be a problematic test. It can't be run repeatedly without unlocking the device in
7705// between runs... and on most test devices there are no enrolled credentials so it can't be
7706// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
7707// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
7708// a manual test process, which includes unlocking between runs, which is why it's included here.
7709// Well, that and the fact that it's the only test we can do without also making calls into the
7710// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
7711// implications might be, so that may or may not be a solution.
7712TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
7713 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7714 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
7715
7716 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7717 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
7718 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
7719 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
7720
7721 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01007722 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007723 ASSERT_EQ(ErrorCode::OK, rc);
7724 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
7725 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
7726 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
7727 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
7728
7729 CheckedDeleteKey(&aesKeyData.blob);
7730 CheckedDeleteKey(&hmacKeyData.blob);
7731 CheckedDeleteKey(&rsaKeyData.blob);
7732 CheckedDeleteKey(&ecdsaKeyData.blob);
7733}
Shawn Willdend659c7c2021-02-19 14:51:51 -07007734
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007735INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
7736
Janis Danisevskis24c04702020-12-16 18:28:39 -08007737} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07007738
7739int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07007740 std::cout << "Testing ";
7741 auto halInstances =
7742 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
7743 std::cout << "HAL instances:\n";
7744 for (auto& entry : halInstances) {
7745 std::cout << " " << entry << '\n';
7746 }
7747
Selene Huang31ab4042020-04-29 04:22:39 -07007748 ::testing::InitGoogleTest(&argc, argv);
7749 for (int i = 1; i < argc; ++i) {
7750 if (argv[i][0] == '-') {
7751 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07007752 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
7753 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07007754 }
7755 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07007756 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
7757 dump_Attestations = true;
7758 } else {
7759 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07007760 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00007761 if (std::string(argv[i]) == "--skip_boot_pl_check") {
7762 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
7763 // be run in emulated environments that don't have the normal bootloader
7764 // interactions.
7765 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
7766 }
Selene Huang31ab4042020-04-29 04:22:39 -07007767 }
7768 }
Shawn Willden08a7e432020-12-11 13:05:27 +00007769 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07007770}