blob: 62f22bb67b8498a63ed42778764e7102d7264b5e [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.
Brian J Murray734c8412022-01-13 14:55:30 -08005221 for (size_t i = 0; i <= 48; i++) {
5222 SCOPED_TRACE(testing::Message() << "i = " << i);
5223 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5224 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005225 string ciphertext = EncryptMessage(message, params);
5226 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5227 string plaintext = DecryptMessage(ciphertext, params);
5228 EXPECT_EQ(message, plaintext);
5229 }
5230}
5231
5232/*
5233 * EncryptionOperationsTest.AesEcbWrongPadding
5234 *
5235 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5236 * specified.
5237 */
5238TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5239 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5240 .Authorization(TAG_NO_AUTH_REQUIRED)
5241 .AesEncryptionKey(128)
5242 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5243 .Padding(PaddingMode::NONE)));
5244
5245 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5246
5247 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005248 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005249 string message(i, 'a');
5250 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5251 }
5252}
5253
5254/*
5255 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5256 *
5257 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5258 */
5259TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5260 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5261 .Authorization(TAG_NO_AUTH_REQUIRED)
5262 .AesEncryptionKey(128)
5263 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5264 .Padding(PaddingMode::PKCS7)));
5265
5266 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5267
5268 string message = "a";
5269 string ciphertext = EncryptMessage(message, params);
5270 EXPECT_EQ(16U, ciphertext.size());
5271 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005272
Seth Moore7a55ae32021-06-23 14:28:11 -07005273 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5274 ++ciphertext[ciphertext.size() / 2];
5275
5276 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5277 string plaintext;
5278 ErrorCode error = Finish(message, &plaintext);
5279 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
5280 // This is the expected error, we can exit the test now.
5281 return;
5282 } else {
5283 // Very small chance we got valid decryption, so try again.
5284 ASSERT_EQ(error, ErrorCode::OK);
5285 }
5286 }
5287 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005288}
5289
5290vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5291 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005292 EXPECT_TRUE(iv);
5293 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005294}
5295
5296/*
5297 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5298 *
5299 * Verifies that AES CTR mode works.
5300 */
5301TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5302 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5303 .Authorization(TAG_NO_AUTH_REQUIRED)
5304 .AesEncryptionKey(128)
5305 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5306 .Padding(PaddingMode::NONE)));
5307
5308 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5309
5310 string message = "123";
5311 AuthorizationSet out_params;
5312 string ciphertext1 = EncryptMessage(message, params, &out_params);
5313 vector<uint8_t> iv1 = CopyIv(out_params);
5314 EXPECT_EQ(16U, iv1.size());
5315
5316 EXPECT_EQ(message.size(), ciphertext1.size());
5317
5318 out_params.Clear();
5319 string ciphertext2 = EncryptMessage(message, params, &out_params);
5320 vector<uint8_t> iv2 = CopyIv(out_params);
5321 EXPECT_EQ(16U, iv2.size());
5322
5323 // IVs should be random, so ciphertexts should differ.
5324 EXPECT_NE(ciphertext1, ciphertext2);
5325
5326 auto params_iv1 =
5327 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5328 auto params_iv2 =
5329 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5330
5331 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5332 EXPECT_EQ(message, plaintext);
5333 plaintext = DecryptMessage(ciphertext2, params_iv2);
5334 EXPECT_EQ(message, plaintext);
5335
5336 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5337 plaintext = DecryptMessage(ciphertext1, params_iv2);
5338 EXPECT_NE(message, plaintext);
5339 plaintext = DecryptMessage(ciphertext2, params_iv1);
5340 EXPECT_NE(message, plaintext);
5341}
5342
5343/*
5344 * EncryptionOperationsTest.AesIncremental
5345 *
5346 * Verifies that AES works, all modes, when provided data in various size increments.
5347 */
5348TEST_P(EncryptionOperationsTest, AesIncremental) {
5349 auto block_modes = {
5350 BlockMode::ECB,
5351 BlockMode::CBC,
5352 BlockMode::CTR,
5353 BlockMode::GCM,
5354 };
5355
5356 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5357 .Authorization(TAG_NO_AUTH_REQUIRED)
5358 .AesEncryptionKey(128)
5359 .BlockMode(block_modes)
5360 .Padding(PaddingMode::NONE)
5361 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5362
5363 for (int increment = 1; increment <= 240; ++increment) {
5364 for (auto block_mode : block_modes) {
5365 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07005366 auto params =
5367 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
5368 if (block_mode == BlockMode::GCM) {
5369 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
5370 }
Selene Huang31ab4042020-04-29 04:22:39 -07005371
5372 AuthorizationSet output_params;
5373 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
5374
5375 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005376 string to_send;
5377 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07005378 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005379 }
Shawn Willden92d79c02021-02-19 07:31:55 -07005380 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
5381 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07005382
5383 switch (block_mode) {
5384 case BlockMode::GCM:
5385 EXPECT_EQ(message.size() + 16, ciphertext.size());
5386 break;
5387 case BlockMode::CTR:
5388 EXPECT_EQ(message.size(), ciphertext.size());
5389 break;
5390 case BlockMode::CBC:
5391 case BlockMode::ECB:
5392 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
5393 break;
5394 }
5395
5396 auto iv = output_params.GetTagValue(TAG_NONCE);
5397 switch (block_mode) {
5398 case BlockMode::CBC:
5399 case BlockMode::GCM:
5400 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005401 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
5402 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
5403 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005404 break;
5405
5406 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005407 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07005408 break;
5409 }
5410
5411 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
5412 << "Decrypt begin() failed for block mode " << block_mode;
5413
5414 string plaintext;
5415 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07005416 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005417 }
5418 ErrorCode error = Finish(to_send, &plaintext);
5419 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
5420 << " and increment " << increment;
5421 if (error == ErrorCode::OK) {
5422 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
5423 << block_mode << " and increment " << increment;
5424 }
5425 }
5426 }
5427}
5428
5429struct AesCtrSp80038aTestVector {
5430 const char* key;
5431 const char* nonce;
5432 const char* plaintext;
5433 const char* ciphertext;
5434};
5435
5436// These test vectors are taken from
5437// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
5438static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
5439 // AES-128
5440 {
5441 "2b7e151628aed2a6abf7158809cf4f3c",
5442 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5443 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5444 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5445 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
5446 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
5447 },
5448 // AES-192
5449 {
5450 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
5451 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5452 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5453 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5454 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
5455 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
5456 },
5457 // AES-256
5458 {
5459 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
5460 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5461 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5462 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5463 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
5464 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
5465 },
5466};
5467
5468/*
5469 * EncryptionOperationsTest.AesCtrSp80038aTestVector
5470 *
5471 * Verifies AES CTR implementation against SP800-38A test vectors.
5472 */
5473TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
5474 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
5475 for (size_t i = 0; i < 3; i++) {
5476 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
5477 const string key = hex2str(test.key);
5478 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
5479 InvalidSizes.end())
5480 continue;
5481 const string nonce = hex2str(test.nonce);
5482 const string plaintext = hex2str(test.plaintext);
5483 const string ciphertext = hex2str(test.ciphertext);
5484 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
5485 }
5486}
5487
5488/*
5489 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
5490 *
5491 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
5492 */
5493TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
5494 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5495 .Authorization(TAG_NO_AUTH_REQUIRED)
5496 .AesEncryptionKey(128)
5497 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5498 .Padding(PaddingMode::PKCS7)));
5499 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5500 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5501}
5502
5503/*
5504 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
5505 *
5506 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5507 */
5508TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
5509 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5510 .Authorization(TAG_NO_AUTH_REQUIRED)
5511 .AesEncryptionKey(128)
5512 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5513 .Authorization(TAG_CALLER_NONCE)
5514 .Padding(PaddingMode::NONE)));
5515
5516 auto params = AuthorizationSetBuilder()
5517 .BlockMode(BlockMode::CTR)
5518 .Padding(PaddingMode::NONE)
5519 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
5520 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5521
5522 params = AuthorizationSetBuilder()
5523 .BlockMode(BlockMode::CTR)
5524 .Padding(PaddingMode::NONE)
5525 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
5526 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5527
5528 params = AuthorizationSetBuilder()
5529 .BlockMode(BlockMode::CTR)
5530 .Padding(PaddingMode::NONE)
5531 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
5532 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5533}
5534
5535/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005536 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07005537 *
5538 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5539 */
5540TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
5541 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5542 .Authorization(TAG_NO_AUTH_REQUIRED)
5543 .AesEncryptionKey(128)
5544 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5545 .Padding(PaddingMode::NONE)));
5546 // Two-block message.
5547 string message = "12345678901234567890123456789012";
5548 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5549 AuthorizationSet out_params;
5550 string ciphertext1 = EncryptMessage(message, params, &out_params);
5551 vector<uint8_t> iv1 = CopyIv(out_params);
5552 EXPECT_EQ(message.size(), ciphertext1.size());
5553
5554 out_params.Clear();
5555
5556 string ciphertext2 = EncryptMessage(message, params, &out_params);
5557 vector<uint8_t> iv2 = CopyIv(out_params);
5558 EXPECT_EQ(message.size(), ciphertext2.size());
5559
5560 // IVs should be random, so ciphertexts should differ.
5561 EXPECT_NE(ciphertext1, ciphertext2);
5562
5563 params.push_back(TAG_NONCE, iv1);
5564 string plaintext = DecryptMessage(ciphertext1, params);
5565 EXPECT_EQ(message, plaintext);
5566}
5567
5568/*
5569 * EncryptionOperationsTest.AesCallerNonce
5570 *
5571 * Verifies that AES caller-provided nonces work correctly.
5572 */
5573TEST_P(EncryptionOperationsTest, AesCallerNonce) {
5574 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5575 .Authorization(TAG_NO_AUTH_REQUIRED)
5576 .AesEncryptionKey(128)
5577 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5578 .Authorization(TAG_CALLER_NONCE)
5579 .Padding(PaddingMode::NONE)));
5580
5581 string message = "12345678901234567890123456789012";
5582
5583 // Don't specify nonce, should get a random one.
5584 AuthorizationSetBuilder params =
5585 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5586 AuthorizationSet out_params;
5587 string ciphertext = EncryptMessage(message, params, &out_params);
5588 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005589 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005590
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005591 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005592 string plaintext = DecryptMessage(ciphertext, params);
5593 EXPECT_EQ(message, plaintext);
5594
5595 // Now specify a nonce, should also work.
5596 params = AuthorizationSetBuilder()
5597 .BlockMode(BlockMode::CBC)
5598 .Padding(PaddingMode::NONE)
5599 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5600 out_params.Clear();
5601 ciphertext = EncryptMessage(message, params, &out_params);
5602
5603 // Decrypt with correct nonce.
5604 plaintext = DecryptMessage(ciphertext, params);
5605 EXPECT_EQ(message, plaintext);
5606
5607 // Try with wrong nonce.
5608 params = AuthorizationSetBuilder()
5609 .BlockMode(BlockMode::CBC)
5610 .Padding(PaddingMode::NONE)
5611 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
5612 plaintext = DecryptMessage(ciphertext, params);
5613 EXPECT_NE(message, plaintext);
5614}
5615
5616/*
5617 * EncryptionOperationsTest.AesCallerNonceProhibited
5618 *
5619 * Verifies that caller-provided nonces are not permitted when not specified in the key
5620 * authorizations.
5621 */
5622TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
5623 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5624 .Authorization(TAG_NO_AUTH_REQUIRED)
5625 .AesEncryptionKey(128)
5626 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5627 .Padding(PaddingMode::NONE)));
5628
5629 string message = "12345678901234567890123456789012";
5630
5631 // Don't specify nonce, should get a random one.
5632 AuthorizationSetBuilder params =
5633 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5634 AuthorizationSet out_params;
5635 string ciphertext = EncryptMessage(message, params, &out_params);
5636 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005637 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005638
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005639 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005640 string plaintext = DecryptMessage(ciphertext, params);
5641 EXPECT_EQ(message, plaintext);
5642
5643 // Now specify a nonce, should fail
5644 params = AuthorizationSetBuilder()
5645 .BlockMode(BlockMode::CBC)
5646 .Padding(PaddingMode::NONE)
5647 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5648 out_params.Clear();
5649 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5650}
5651
5652/*
5653 * EncryptionOperationsTest.AesGcmRoundTripSuccess
5654 *
5655 * Verifies that AES GCM mode works.
5656 */
5657TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
5658 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5659 .Authorization(TAG_NO_AUTH_REQUIRED)
5660 .AesEncryptionKey(128)
5661 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5662 .Padding(PaddingMode::NONE)
5663 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5664
5665 string aad = "foobar";
5666 string message = "123456789012345678901234567890123456";
5667
5668 auto begin_params = AuthorizationSetBuilder()
5669 .BlockMode(BlockMode::GCM)
5670 .Padding(PaddingMode::NONE)
5671 .Authorization(TAG_MAC_LENGTH, 128);
5672
Selene Huang31ab4042020-04-29 04:22:39 -07005673 // Encrypt
5674 AuthorizationSet begin_out_params;
5675 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5676 << "Begin encrypt";
5677 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005678 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5679 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005680 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5681
5682 // Grab nonce
5683 begin_params.push_back(begin_out_params);
5684
5685 // Decrypt.
5686 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07005687 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005688 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005689 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005690 EXPECT_EQ(message.length(), plaintext.length());
5691 EXPECT_EQ(message, plaintext);
5692}
5693
5694/*
5695 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
5696 *
5697 * Verifies that AES GCM mode works, even when there's a long delay
5698 * between operations.
5699 */
5700TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
5701 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5702 .Authorization(TAG_NO_AUTH_REQUIRED)
5703 .AesEncryptionKey(128)
5704 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5705 .Padding(PaddingMode::NONE)
5706 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5707
5708 string aad = "foobar";
5709 string message = "123456789012345678901234567890123456";
5710
5711 auto begin_params = AuthorizationSetBuilder()
5712 .BlockMode(BlockMode::GCM)
5713 .Padding(PaddingMode::NONE)
5714 .Authorization(TAG_MAC_LENGTH, 128);
5715
Selene Huang31ab4042020-04-29 04:22:39 -07005716 // Encrypt
5717 AuthorizationSet begin_out_params;
5718 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5719 << "Begin encrypt";
5720 string ciphertext;
5721 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005722 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005723 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005724 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005725
5726 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5727
5728 // Grab nonce
5729 begin_params.push_back(begin_out_params);
5730
5731 // Decrypt.
5732 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
5733 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005734 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005735 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005736 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005737 sleep(5);
5738 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
5739 EXPECT_EQ(message.length(), plaintext.length());
5740 EXPECT_EQ(message, plaintext);
5741}
5742
5743/*
5744 * EncryptionOperationsTest.AesGcmDifferentNonces
5745 *
5746 * Verifies that encrypting the same data with different nonces produces different outputs.
5747 */
5748TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
5749 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5750 .Authorization(TAG_NO_AUTH_REQUIRED)
5751 .AesEncryptionKey(128)
5752 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5753 .Padding(PaddingMode::NONE)
5754 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5755 .Authorization(TAG_CALLER_NONCE)));
5756
5757 string aad = "foobar";
5758 string message = "123456789012345678901234567890123456";
5759 string nonce1 = "000000000000";
5760 string nonce2 = "111111111111";
5761 string nonce3 = "222222222222";
5762
5763 string ciphertext1 =
5764 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
5765 string ciphertext2 =
5766 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
5767 string ciphertext3 =
5768 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
5769
5770 ASSERT_NE(ciphertext1, ciphertext2);
5771 ASSERT_NE(ciphertext1, ciphertext3);
5772 ASSERT_NE(ciphertext2, ciphertext3);
5773}
5774
5775/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005776 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
5777 *
5778 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
5779 */
5780TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
5781 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5782 .Authorization(TAG_NO_AUTH_REQUIRED)
5783 .AesEncryptionKey(128)
5784 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5785 .Padding(PaddingMode::NONE)
5786 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5787
5788 string aad = "foobar";
5789 string message = "123456789012345678901234567890123456";
5790
5791 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5792 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5793 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5794
5795 ASSERT_NE(ciphertext1, ciphertext2);
5796 ASSERT_NE(ciphertext1, ciphertext3);
5797 ASSERT_NE(ciphertext2, ciphertext3);
5798}
5799
5800/*
Selene Huang31ab4042020-04-29 04:22:39 -07005801 * EncryptionOperationsTest.AesGcmTooShortTag
5802 *
5803 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
5804 */
5805TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
5806 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5807 .Authorization(TAG_NO_AUTH_REQUIRED)
5808 .AesEncryptionKey(128)
5809 .BlockMode(BlockMode::GCM)
5810 .Padding(PaddingMode::NONE)
5811 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5812 string message = "123456789012345678901234567890123456";
5813 auto params = AuthorizationSetBuilder()
5814 .BlockMode(BlockMode::GCM)
5815 .Padding(PaddingMode::NONE)
5816 .Authorization(TAG_MAC_LENGTH, 96);
5817
5818 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
5819}
5820
5821/*
5822 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
5823 *
5824 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
5825 */
5826TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
5827 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5828 .Authorization(TAG_NO_AUTH_REQUIRED)
5829 .AesEncryptionKey(128)
5830 .BlockMode(BlockMode::GCM)
5831 .Padding(PaddingMode::NONE)
5832 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5833 string aad = "foobar";
5834 string message = "123456789012345678901234567890123456";
5835 auto params = AuthorizationSetBuilder()
5836 .BlockMode(BlockMode::GCM)
5837 .Padding(PaddingMode::NONE)
5838 .Authorization(TAG_MAC_LENGTH, 128);
5839
Selene Huang31ab4042020-04-29 04:22:39 -07005840 // Encrypt
5841 AuthorizationSet begin_out_params;
5842 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5843 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005844 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005845
5846 AuthorizationSet finish_out_params;
5847 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005848 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5849 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005850
5851 params = AuthorizationSetBuilder()
5852 .Authorizations(begin_out_params)
5853 .BlockMode(BlockMode::GCM)
5854 .Padding(PaddingMode::NONE)
5855 .Authorization(TAG_MAC_LENGTH, 96);
5856
5857 // Decrypt.
5858 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
5859}
5860
5861/*
5862 * EncryptionOperationsTest.AesGcmCorruptKey
5863 *
5864 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
5865 */
5866TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
5867 const uint8_t nonce_bytes[] = {
5868 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
5869 };
5870 string nonce = make_string(nonce_bytes);
5871 const uint8_t ciphertext_bytes[] = {
5872 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
5873 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
5874 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
5875 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5876 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5877 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5878 };
5879 string ciphertext = make_string(ciphertext_bytes);
5880
5881 auto params = AuthorizationSetBuilder()
5882 .BlockMode(BlockMode::GCM)
5883 .Padding(PaddingMode::NONE)
5884 .Authorization(TAG_MAC_LENGTH, 128)
5885 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5886
5887 auto import_params = AuthorizationSetBuilder()
5888 .Authorization(TAG_NO_AUTH_REQUIRED)
5889 .AesEncryptionKey(128)
5890 .BlockMode(BlockMode::GCM)
5891 .Padding(PaddingMode::NONE)
5892 .Authorization(TAG_CALLER_NONCE)
5893 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5894
5895 // Import correct key and decrypt
5896 const uint8_t key_bytes[] = {
5897 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5898 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5899 };
5900 string key = make_string(key_bytes);
5901 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5902 string plaintext = DecryptMessage(ciphertext, params);
5903 CheckedDeleteKey();
5904
5905 // Corrupt key and attempt to decrypt
5906 key[0] = 0;
5907 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5908 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5909 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5910 CheckedDeleteKey();
5911}
5912
5913/*
5914 * EncryptionOperationsTest.AesGcmAadNoData
5915 *
5916 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5917 * encrypt.
5918 */
5919TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5920 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5921 .Authorization(TAG_NO_AUTH_REQUIRED)
5922 .AesEncryptionKey(128)
5923 .BlockMode(BlockMode::GCM)
5924 .Padding(PaddingMode::NONE)
5925 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5926
5927 string aad = "1234567890123456";
5928 auto params = AuthorizationSetBuilder()
5929 .BlockMode(BlockMode::GCM)
5930 .Padding(PaddingMode::NONE)
5931 .Authorization(TAG_MAC_LENGTH, 128);
5932
Selene Huang31ab4042020-04-29 04:22:39 -07005933 // Encrypt
5934 AuthorizationSet begin_out_params;
5935 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5936 string ciphertext;
5937 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005938 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5939 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005940 EXPECT_TRUE(finish_out_params.empty());
5941
5942 // Grab nonce
5943 params.push_back(begin_out_params);
5944
5945 // Decrypt.
5946 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005947 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005948 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005949 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005950
5951 EXPECT_TRUE(finish_out_params.empty());
5952
5953 EXPECT_EQ("", plaintext);
5954}
5955
5956/*
5957 * EncryptionOperationsTest.AesGcmMultiPartAad
5958 *
5959 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5960 * chunks.
5961 */
5962TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5963 const size_t tag_bits = 128;
5964 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5965 .Authorization(TAG_NO_AUTH_REQUIRED)
5966 .AesEncryptionKey(128)
5967 .BlockMode(BlockMode::GCM)
5968 .Padding(PaddingMode::NONE)
5969 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5970
5971 string message = "123456789012345678901234567890123456";
5972 auto begin_params = AuthorizationSetBuilder()
5973 .BlockMode(BlockMode::GCM)
5974 .Padding(PaddingMode::NONE)
5975 .Authorization(TAG_MAC_LENGTH, tag_bits);
5976 AuthorizationSet begin_out_params;
5977
Selene Huang31ab4042020-04-29 04:22:39 -07005978 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5979
5980 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005981 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5982 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005983 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005984 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5985 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005986
Selene Huang31ab4042020-04-29 04:22:39 -07005987 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005988 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005989
5990 // Grab nonce.
5991 begin_params.push_back(begin_out_params);
5992
5993 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005994 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005995 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005996 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005997 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005998 EXPECT_EQ(message, plaintext);
5999}
6000
6001/*
6002 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6003 *
6004 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6005 */
6006TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6007 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6008 .Authorization(TAG_NO_AUTH_REQUIRED)
6009 .AesEncryptionKey(128)
6010 .BlockMode(BlockMode::GCM)
6011 .Padding(PaddingMode::NONE)
6012 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6013
6014 string message = "123456789012345678901234567890123456";
6015 auto begin_params = AuthorizationSetBuilder()
6016 .BlockMode(BlockMode::GCM)
6017 .Padding(PaddingMode::NONE)
6018 .Authorization(TAG_MAC_LENGTH, 128);
6019 AuthorizationSet begin_out_params;
6020
Selene Huang31ab4042020-04-29 04:22:39 -07006021 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
6022
Shawn Willden92d79c02021-02-19 07:31:55 -07006023 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006024 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006025 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6026 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006027
David Drysdaled2cc8c22021-04-15 13:29:45 +01006028 // The failure should have already cancelled the operation.
6029 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6030
Shawn Willden92d79c02021-02-19 07:31:55 -07006031 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006032}
6033
6034/*
6035 * EncryptionOperationsTest.AesGcmBadAad
6036 *
6037 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6038 */
6039TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6040 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6041 .Authorization(TAG_NO_AUTH_REQUIRED)
6042 .AesEncryptionKey(128)
6043 .BlockMode(BlockMode::GCM)
6044 .Padding(PaddingMode::NONE)
6045 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6046
6047 string message = "12345678901234567890123456789012";
6048 auto begin_params = AuthorizationSetBuilder()
6049 .BlockMode(BlockMode::GCM)
6050 .Padding(PaddingMode::NONE)
6051 .Authorization(TAG_MAC_LENGTH, 128);
6052
Selene Huang31ab4042020-04-29 04:22:39 -07006053 // Encrypt
6054 AuthorizationSet begin_out_params;
6055 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006056 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006057 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006058 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006059
6060 // Grab nonce
6061 begin_params.push_back(begin_out_params);
6062
Selene Huang31ab4042020-04-29 04:22:39 -07006063 // Decrypt.
6064 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006065 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006066 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006067 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006068}
6069
6070/*
6071 * EncryptionOperationsTest.AesGcmWrongNonce
6072 *
6073 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6074 */
6075TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6076 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6077 .Authorization(TAG_NO_AUTH_REQUIRED)
6078 .AesEncryptionKey(128)
6079 .BlockMode(BlockMode::GCM)
6080 .Padding(PaddingMode::NONE)
6081 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6082
6083 string message = "12345678901234567890123456789012";
6084 auto begin_params = AuthorizationSetBuilder()
6085 .BlockMode(BlockMode::GCM)
6086 .Padding(PaddingMode::NONE)
6087 .Authorization(TAG_MAC_LENGTH, 128);
6088
Selene Huang31ab4042020-04-29 04:22:39 -07006089 // Encrypt
6090 AuthorizationSet begin_out_params;
6091 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006092 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006093 string ciphertext;
6094 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006095 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006096
6097 // Wrong nonce
6098 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6099
6100 // Decrypt.
6101 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006102 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006103 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006104 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006105
6106 // With wrong nonce, should have gotten garbage plaintext (or none).
6107 EXPECT_NE(message, plaintext);
6108}
6109
6110/*
6111 * EncryptionOperationsTest.AesGcmCorruptTag
6112 *
6113 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6114 */
6115TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6116 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6117 .Authorization(TAG_NO_AUTH_REQUIRED)
6118 .AesEncryptionKey(128)
6119 .BlockMode(BlockMode::GCM)
6120 .Padding(PaddingMode::NONE)
6121 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6122
6123 string aad = "1234567890123456";
6124 string message = "123456789012345678901234567890123456";
6125
6126 auto params = AuthorizationSetBuilder()
6127 .BlockMode(BlockMode::GCM)
6128 .Padding(PaddingMode::NONE)
6129 .Authorization(TAG_MAC_LENGTH, 128);
6130
Selene Huang31ab4042020-04-29 04:22:39 -07006131 // Encrypt
6132 AuthorizationSet begin_out_params;
6133 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006134 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006135 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006136 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006137
6138 // Corrupt tag
6139 ++(*ciphertext.rbegin());
6140
6141 // Grab nonce
6142 params.push_back(begin_out_params);
6143
6144 // Decrypt.
6145 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006146 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006147 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006148 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006149}
6150
6151/*
6152 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
6153 *
6154 * Verifies that 3DES is basically functional.
6155 */
6156TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
6157 auto auths = AuthorizationSetBuilder()
6158 .TripleDesEncryptionKey(168)
6159 .BlockMode(BlockMode::ECB)
6160 .Authorization(TAG_NO_AUTH_REQUIRED)
6161 .Padding(PaddingMode::NONE);
6162
6163 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
6164 // Two-block message.
6165 string message = "1234567890123456";
6166 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6167 string ciphertext1 = EncryptMessage(message, inParams);
6168 EXPECT_EQ(message.size(), ciphertext1.size());
6169
6170 string ciphertext2 = EncryptMessage(string(message), inParams);
6171 EXPECT_EQ(message.size(), ciphertext2.size());
6172
6173 // ECB is deterministic.
6174 EXPECT_EQ(ciphertext1, ciphertext2);
6175
6176 string plaintext = DecryptMessage(ciphertext1, inParams);
6177 EXPECT_EQ(message, plaintext);
6178}
6179
6180/*
6181 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
6182 *
6183 * Verifies that CBC keys reject ECB usage.
6184 */
6185TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
6186 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6187 .TripleDesEncryptionKey(168)
6188 .BlockMode(BlockMode::CBC)
6189 .Authorization(TAG_NO_AUTH_REQUIRED)
6190 .Padding(PaddingMode::NONE)));
6191
6192 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6193 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
6194}
6195
6196/*
6197 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
6198 *
6199 * Tests ECB mode with PKCS#7 padding, various message sizes.
6200 */
6201TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
6202 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6203 .TripleDesEncryptionKey(168)
6204 .BlockMode(BlockMode::ECB)
6205 .Authorization(TAG_NO_AUTH_REQUIRED)
6206 .Padding(PaddingMode::PKCS7)));
6207
6208 for (size_t i = 0; i < 32; ++i) {
6209 string message(i, 'a');
6210 auto inParams =
6211 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6212 string ciphertext = EncryptMessage(message, inParams);
6213 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6214 string plaintext = DecryptMessage(ciphertext, inParams);
6215 EXPECT_EQ(message, plaintext);
6216 }
6217}
6218
6219/*
6220 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
6221 *
6222 * Verifies that keys configured for no padding reject PKCS7 padding
6223 */
6224TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
6225 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6226 .TripleDesEncryptionKey(168)
6227 .BlockMode(BlockMode::ECB)
6228 .Authorization(TAG_NO_AUTH_REQUIRED)
6229 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00006230 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6231 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07006232}
6233
6234/*
6235 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
6236 *
6237 * Verifies that corrupted padding is detected.
6238 */
6239TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
6240 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6241 .TripleDesEncryptionKey(168)
6242 .BlockMode(BlockMode::ECB)
6243 .Authorization(TAG_NO_AUTH_REQUIRED)
6244 .Padding(PaddingMode::PKCS7)));
6245
6246 string message = "a";
6247 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
6248 EXPECT_EQ(8U, ciphertext.size());
6249 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006250
6251 AuthorizationSetBuilder begin_params;
6252 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
6253 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07006254
6255 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
6256 ++ciphertext[ciphertext.size() / 2];
6257
6258 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
6259 string plaintext;
6260 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6261 ErrorCode error = Finish(&plaintext);
6262 if (error == ErrorCode::INVALID_ARGUMENT) {
6263 // This is the expected error, we can exit the test now.
6264 return;
6265 } else {
6266 // Very small chance we got valid decryption, so try again.
6267 ASSERT_EQ(error, ErrorCode::OK);
6268 }
6269 }
6270 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006271}
6272
6273struct TripleDesTestVector {
6274 const char* name;
6275 const KeyPurpose purpose;
6276 const BlockMode block_mode;
6277 const PaddingMode padding_mode;
6278 const char* key;
6279 const char* iv;
6280 const char* input;
6281 const char* output;
6282};
6283
6284// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
6285// of the NIST vectors are multiples of the block size.
6286static const TripleDesTestVector kTripleDesTestVectors[] = {
6287 {
6288 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6289 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
6290 "", // IV
6291 "329d86bdf1bc5af4", // input
6292 "d946c2756d78633f", // output
6293 },
6294 {
6295 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6296 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
6297 "", // IV
6298 "6b1540781b01ce1997adae102dbf3c5b", // input
6299 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
6300 },
6301 {
6302 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6303 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
6304 "", // IV
6305 "6daad94ce08acfe7", // input
6306 "660e7d32dcc90e79", // output
6307 },
6308 {
6309 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6310 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
6311 "", // IV
6312 "e9653a0a1f05d31b9acd12d73aa9879d", // input
6313 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
6314 },
6315 {
6316 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6317 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
6318 "43f791134c5647ba", // IV
6319 "dcc153cef81d6f24", // input
6320 "92538bd8af18d3ba", // output
6321 },
6322 {
6323 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6324 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6325 "c2e999cb6249023c", // IV
6326 "c689aee38a301bb316da75db36f110b5", // input
6327 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
6328 },
6329 {
6330 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
6331 PaddingMode::PKCS7,
6332 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6333 "c2e999cb6249023c", // IV
6334 "c689aee38a301bb316da75db36f110b500", // input
6335 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
6336 },
6337 {
6338 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
6339 PaddingMode::PKCS7,
6340 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6341 "c2e999cb6249023c", // IV
6342 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
6343 "c689aee38a301bb316da75db36f110b500", // output
6344 },
6345 {
6346 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6347 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
6348 "41746c7e442d3681", // IV
6349 "c53a7b0ec40600fe", // input
6350 "d4f00eb455de1034", // output
6351 },
6352 {
6353 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6354 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
6355 "3982bc02c3727d45", // IV
6356 "6006f10adef52991fcc777a1238bbb65", // input
6357 "edae09288e9e3bc05746d872b48e3b29", // output
6358 },
6359};
6360
6361/*
6362 * EncryptionOperationsTest.TripleDesTestVector
6363 *
6364 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
6365 */
6366TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
6367 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
6368 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
6369 SCOPED_TRACE(test->name);
6370 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
6371 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
6372 hex2str(test->output));
6373 }
6374}
6375
6376/*
6377 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
6378 *
6379 * Validates CBC mode functionality.
6380 */
6381TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
6382 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6383 .TripleDesEncryptionKey(168)
6384 .BlockMode(BlockMode::CBC)
6385 .Authorization(TAG_NO_AUTH_REQUIRED)
6386 .Padding(PaddingMode::NONE)));
6387
6388 ASSERT_GT(key_blob_.size(), 0U);
6389
Brian J Murray734c8412022-01-13 14:55:30 -08006390 // Four-block message.
6391 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07006392 vector<uint8_t> iv1;
6393 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
6394 EXPECT_EQ(message.size(), ciphertext1.size());
6395
6396 vector<uint8_t> iv2;
6397 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
6398 EXPECT_EQ(message.size(), ciphertext2.size());
6399
6400 // IVs should be random, so ciphertexts should differ.
6401 EXPECT_NE(iv1, iv2);
6402 EXPECT_NE(ciphertext1, ciphertext2);
6403
6404 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
6405 EXPECT_EQ(message, plaintext);
6406}
6407
6408/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006409 * EncryptionOperationsTest.TripleDesInvalidCallerIv
6410 *
6411 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
6412 */
6413TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
6414 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6415 .TripleDesEncryptionKey(168)
6416 .BlockMode(BlockMode::CBC)
6417 .Authorization(TAG_NO_AUTH_REQUIRED)
6418 .Authorization(TAG_CALLER_NONCE)
6419 .Padding(PaddingMode::NONE)));
6420 auto params = AuthorizationSetBuilder()
6421 .BlockMode(BlockMode::CBC)
6422 .Padding(PaddingMode::NONE)
6423 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
6424 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6425}
6426
6427/*
Selene Huang31ab4042020-04-29 04:22:39 -07006428 * EncryptionOperationsTest.TripleDesCallerIv
6429 *
6430 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
6431 */
6432TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
6433 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6434 .TripleDesEncryptionKey(168)
6435 .BlockMode(BlockMode::CBC)
6436 .Authorization(TAG_NO_AUTH_REQUIRED)
6437 .Authorization(TAG_CALLER_NONCE)
6438 .Padding(PaddingMode::NONE)));
6439 string message = "1234567890123456";
6440 vector<uint8_t> iv;
6441 // Don't specify IV, should get a random one.
6442 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6443 EXPECT_EQ(message.size(), ciphertext1.size());
6444 EXPECT_EQ(8U, iv.size());
6445
6446 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6447 EXPECT_EQ(message, plaintext);
6448
6449 // Now specify an IV, should also work.
6450 iv = AidlBuf("abcdefgh");
6451 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
6452
6453 // Decrypt with correct IV.
6454 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
6455 EXPECT_EQ(message, plaintext);
6456
6457 // Now try with wrong IV.
6458 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
6459 EXPECT_NE(message, plaintext);
6460}
6461
6462/*
6463 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
6464 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01006465 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07006466 */
6467TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
6468 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6469 .TripleDesEncryptionKey(168)
6470 .BlockMode(BlockMode::CBC)
6471 .Authorization(TAG_NO_AUTH_REQUIRED)
6472 .Padding(PaddingMode::NONE)));
6473
6474 string message = "12345678901234567890123456789012";
6475 vector<uint8_t> iv;
6476 // Don't specify nonce, should get a random one.
6477 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6478 EXPECT_EQ(message.size(), ciphertext1.size());
6479 EXPECT_EQ(8U, iv.size());
6480
6481 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6482 EXPECT_EQ(message, plaintext);
6483
6484 // Now specify a nonce, should fail.
6485 auto input_params = AuthorizationSetBuilder()
6486 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
6487 .BlockMode(BlockMode::CBC)
6488 .Padding(PaddingMode::NONE);
6489 AuthorizationSet output_params;
6490 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
6491 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6492}
6493
6494/*
6495 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
6496 *
6497 * Verifies that 3DES ECB-only keys do not allow CBC usage.
6498 */
6499TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
6500 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6501 .TripleDesEncryptionKey(168)
6502 .BlockMode(BlockMode::ECB)
6503 .Authorization(TAG_NO_AUTH_REQUIRED)
6504 .Padding(PaddingMode::NONE)));
6505 // Two-block message.
6506 string message = "1234567890123456";
6507 auto begin_params =
6508 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6509 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6510}
6511
6512/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006513 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07006514 *
6515 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
6516 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01006517TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
6518 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
6519 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6520 .TripleDesEncryptionKey(168)
6521 .BlockMode(blockMode)
6522 .Authorization(TAG_NO_AUTH_REQUIRED)
6523 .Padding(PaddingMode::NONE)));
6524 // Message is slightly shorter than two blocks.
6525 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07006526
David Drysdaled2cc8c22021-04-15 13:29:45 +01006527 auto begin_params =
6528 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
6529 AuthorizationSet output_params;
6530 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
6531 string ciphertext;
6532 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
6533
6534 CheckedDeleteKey();
6535 }
Selene Huang31ab4042020-04-29 04:22:39 -07006536}
6537
6538/*
6539 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
6540 *
6541 * Verifies that PKCS7 padding works correctly in CBC mode.
6542 */
6543TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
6544 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6545 .TripleDesEncryptionKey(168)
6546 .BlockMode(BlockMode::CBC)
6547 .Authorization(TAG_NO_AUTH_REQUIRED)
6548 .Padding(PaddingMode::PKCS7)));
6549
6550 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08006551 for (size_t i = 0; i <= 32; i++) {
6552 SCOPED_TRACE(testing::Message() << "i = " << i);
6553 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
6554 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07006555 vector<uint8_t> iv;
6556 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6557 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6558 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
6559 EXPECT_EQ(message, plaintext);
6560 }
6561}
6562
6563/*
6564 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
6565 *
6566 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
6567 */
6568TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
6569 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6570 .TripleDesEncryptionKey(168)
6571 .BlockMode(BlockMode::CBC)
6572 .Authorization(TAG_NO_AUTH_REQUIRED)
6573 .Padding(PaddingMode::NONE)));
6574
6575 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08006576 for (size_t i = 0; i <= 32; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07006577 auto begin_params =
6578 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
6579 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6580 }
6581}
6582
6583/*
6584 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
6585 *
6586 * Verifies that corrupted PKCS7 padding is rejected during decryption.
6587 */
6588TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
6589 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6590 .TripleDesEncryptionKey(168)
6591 .BlockMode(BlockMode::CBC)
6592 .Authorization(TAG_NO_AUTH_REQUIRED)
6593 .Padding(PaddingMode::PKCS7)));
6594
6595 string message = "a";
6596 vector<uint8_t> iv;
6597 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6598 EXPECT_EQ(8U, ciphertext.size());
6599 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006600
6601 auto begin_params = AuthorizationSetBuilder()
6602 .BlockMode(BlockMode::CBC)
6603 .Padding(PaddingMode::PKCS7)
6604 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07006605
6606 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08006607 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07006608 ++ciphertext[ciphertext.size() / 2];
6609 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
6610 string plaintext;
6611 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6612 ErrorCode error = Finish(&plaintext);
6613 if (error == ErrorCode::INVALID_ARGUMENT) {
6614 // This is the expected error, we can exit the test now.
6615 return;
6616 } else {
6617 // Very small chance we got valid decryption, so try again.
6618 ASSERT_EQ(error, ErrorCode::OK);
6619 }
6620 }
6621 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006622}
6623
6624/*
6625 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
6626 *
6627 * Verifies that 3DES CBC works with many different input sizes.
6628 */
6629TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
6630 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6631 .TripleDesEncryptionKey(168)
6632 .BlockMode(BlockMode::CBC)
6633 .Authorization(TAG_NO_AUTH_REQUIRED)
6634 .Padding(PaddingMode::NONE)));
6635
6636 int increment = 7;
6637 string message(240, 'a');
6638 AuthorizationSet input_params =
6639 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6640 AuthorizationSet output_params;
6641 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6642
6643 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07006644 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006645 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006646 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
6647 EXPECT_EQ(message.size(), ciphertext.size());
6648
6649 // Move TAG_NONCE into input_params
6650 input_params = output_params;
6651 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
6652 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
6653 output_params.Clear();
6654
6655 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
6656 string plaintext;
6657 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006658 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006659 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
6660 EXPECT_EQ(ciphertext.size(), plaintext.size());
6661 EXPECT_EQ(message, plaintext);
6662}
6663
6664INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
6665
6666typedef KeyMintAidlTestBase MaxOperationsTest;
6667
6668/*
6669 * MaxOperationsTest.TestLimitAes
6670 *
6671 * Verifies that the max uses per boot tag works correctly with AES keys.
6672 */
6673TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006674 if (SecLevel() == SecurityLevel::STRONGBOX) {
6675 GTEST_SKIP() << "Test not applicable to StrongBox device";
6676 }
Selene Huang31ab4042020-04-29 04:22:39 -07006677
6678 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6679 .Authorization(TAG_NO_AUTH_REQUIRED)
6680 .AesEncryptionKey(128)
6681 .EcbMode()
6682 .Padding(PaddingMode::NONE)
6683 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
6684
6685 string message = "1234567890123456";
6686
6687 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6688
6689 EncryptMessage(message, params);
6690 EncryptMessage(message, params);
6691 EncryptMessage(message, params);
6692
6693 // Fourth time should fail.
6694 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
6695}
6696
6697/*
Qi Wud22ec842020-11-26 13:27:53 +08006698 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07006699 *
6700 * Verifies that the max uses per boot tag works correctly with RSA keys.
6701 */
6702TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006703 if (SecLevel() == SecurityLevel::STRONGBOX) {
6704 GTEST_SKIP() << "Test not applicable to StrongBox device";
6705 }
Selene Huang31ab4042020-04-29 04:22:39 -07006706
6707 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6708 .Authorization(TAG_NO_AUTH_REQUIRED)
6709 .RsaSigningKey(1024, 65537)
6710 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006711 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
6712 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006713
6714 string message = "1234567890123456";
6715
6716 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6717
6718 SignMessage(message, params);
6719 SignMessage(message, params);
6720 SignMessage(message, params);
6721
6722 // Fourth time should fail.
6723 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
6724}
6725
6726INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
6727
Qi Wud22ec842020-11-26 13:27:53 +08006728typedef KeyMintAidlTestBase UsageCountLimitTest;
6729
6730/*
Qi Wubeefae42021-01-28 23:16:37 +08006731 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006732 *
Qi Wubeefae42021-01-28 23:16:37 +08006733 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006734 */
Qi Wubeefae42021-01-28 23:16:37 +08006735TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006736 if (SecLevel() == SecurityLevel::STRONGBOX) {
6737 GTEST_SKIP() << "Test not applicable to StrongBox device";
6738 }
Qi Wud22ec842020-11-26 13:27:53 +08006739
6740 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6741 .Authorization(TAG_NO_AUTH_REQUIRED)
6742 .AesEncryptionKey(128)
6743 .EcbMode()
6744 .Padding(PaddingMode::NONE)
6745 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
6746
6747 // Check the usage count limit tag appears in the authorizations.
6748 AuthorizationSet auths;
6749 for (auto& entry : key_characteristics_) {
6750 auths.push_back(AuthorizationSet(entry.authorizations));
6751 }
6752 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6753 << "key usage count limit " << 1U << " missing";
6754
6755 string message = "1234567890123456";
6756 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6757
Qi Wubeefae42021-01-28 23:16:37 +08006758 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6759 AuthorizationSet keystore_auths =
6760 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6761
Qi Wud22ec842020-11-26 13:27:53 +08006762 // First usage of AES key should work.
6763 EncryptMessage(message, params);
6764
Qi Wud22ec842020-11-26 13:27:53 +08006765 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6766 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6767 // must be invalidated from secure storage (such as RPMB partition).
6768 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6769 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006770 // Usage count limit tag is enforced by keystore, keymint does nothing.
6771 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08006772 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6773 }
6774}
6775
6776/*
Qi Wubeefae42021-01-28 23:16:37 +08006777 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006778 *
Qi Wubeefae42021-01-28 23:16:37 +08006779 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006780 */
Qi Wubeefae42021-01-28 23:16:37 +08006781TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006782 if (SecLevel() == SecurityLevel::STRONGBOX) {
6783 GTEST_SKIP() << "Test not applicable to StrongBox device";
6784 }
Qi Wubeefae42021-01-28 23:16:37 +08006785
6786 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6787 .Authorization(TAG_NO_AUTH_REQUIRED)
6788 .AesEncryptionKey(128)
6789 .EcbMode()
6790 .Padding(PaddingMode::NONE)
6791 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
6792
6793 // Check the usage count limit tag appears in the authorizations.
6794 AuthorizationSet auths;
6795 for (auto& entry : key_characteristics_) {
6796 auths.push_back(AuthorizationSet(entry.authorizations));
6797 }
6798 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6799 << "key usage count limit " << 3U << " missing";
6800
6801 string message = "1234567890123456";
6802 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6803
6804 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6805 AuthorizationSet keystore_auths =
6806 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6807
6808 EncryptMessage(message, params);
6809 EncryptMessage(message, params);
6810 EncryptMessage(message, params);
6811
6812 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6813 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6814 // must be invalidated from secure storage (such as RPMB partition).
6815 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6816 } else {
6817 // Usage count limit tag is enforced by keystore, keymint does nothing.
6818 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
6819 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6820 }
6821}
6822
6823/*
6824 * UsageCountLimitTest.TestSingleUseRsa
6825 *
6826 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
6827 */
6828TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006829 if (SecLevel() == SecurityLevel::STRONGBOX) {
6830 GTEST_SKIP() << "Test not applicable to StrongBox device";
6831 }
Qi Wud22ec842020-11-26 13:27:53 +08006832
6833 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6834 .Authorization(TAG_NO_AUTH_REQUIRED)
6835 .RsaSigningKey(1024, 65537)
6836 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006837 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6838 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08006839
6840 // Check the usage count limit tag appears in the authorizations.
6841 AuthorizationSet auths;
6842 for (auto& entry : key_characteristics_) {
6843 auths.push_back(AuthorizationSet(entry.authorizations));
6844 }
6845 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6846 << "key usage count limit " << 1U << " missing";
6847
6848 string message = "1234567890123456";
6849 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6850
Qi Wubeefae42021-01-28 23:16:37 +08006851 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6852 AuthorizationSet keystore_auths =
6853 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6854
Qi Wud22ec842020-11-26 13:27:53 +08006855 // First usage of RSA key should work.
6856 SignMessage(message, params);
6857
Qi Wud22ec842020-11-26 13:27:53 +08006858 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6859 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6860 // must be invalidated from secure storage (such as RPMB partition).
6861 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6862 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006863 // Usage count limit tag is enforced by keystore, keymint does nothing.
6864 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
6865 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6866 }
6867}
6868
6869/*
6870 * UsageCountLimitTest.TestLimitUseRsa
6871 *
6872 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
6873 */
6874TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006875 if (SecLevel() == SecurityLevel::STRONGBOX) {
6876 GTEST_SKIP() << "Test not applicable to StrongBox device";
6877 }
Qi Wubeefae42021-01-28 23:16:37 +08006878
6879 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6880 .Authorization(TAG_NO_AUTH_REQUIRED)
6881 .RsaSigningKey(1024, 65537)
6882 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006883 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
6884 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08006885
6886 // Check the usage count limit tag appears in the authorizations.
6887 AuthorizationSet auths;
6888 for (auto& entry : key_characteristics_) {
6889 auths.push_back(AuthorizationSet(entry.authorizations));
6890 }
6891 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6892 << "key usage count limit " << 3U << " missing";
6893
6894 string message = "1234567890123456";
6895 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6896
6897 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6898 AuthorizationSet keystore_auths =
6899 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6900
6901 SignMessage(message, params);
6902 SignMessage(message, params);
6903 SignMessage(message, params);
6904
6905 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6906 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6907 // must be invalidated from secure storage (such as RPMB partition).
6908 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6909 } else {
6910 // Usage count limit tag is enforced by keystore, keymint does nothing.
6911 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006912 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6913 }
6914}
6915
Qi Wu8e727f72021-02-11 02:49:33 +08006916/*
6917 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6918 *
6919 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6920 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6921 * in hardware.
6922 */
6923TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01006924 if (SecLevel() == SecurityLevel::STRONGBOX) {
6925 GTEST_SKIP() << "Test not applicable to StrongBox device";
6926 }
Qi Wu8e727f72021-02-11 02:49:33 +08006927
6928 auto error = GenerateKey(AuthorizationSetBuilder()
6929 .RsaSigningKey(2048, 65537)
6930 .Digest(Digest::NONE)
6931 .Padding(PaddingMode::NONE)
6932 .Authorization(TAG_NO_AUTH_REQUIRED)
6933 .Authorization(TAG_ROLLBACK_RESISTANCE)
6934 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006935 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6936 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08006937 }
David Drysdale513bf122021-10-06 11:53:13 +01006938
6939 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6940 ASSERT_EQ(ErrorCode::OK, error);
6941 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6942 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6943 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6944
6945 // The KeyMint should also enforce single use key in hardware when it supports rollback
6946 // resistance.
6947 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6948 .Authorization(TAG_NO_AUTH_REQUIRED)
6949 .RsaSigningKey(1024, 65537)
6950 .NoDigestOrPadding()
6951 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6952 .SetDefaultValidity()));
6953
6954 // Check the usage count limit tag appears in the hardware authorizations.
6955 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6956 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6957 << "key usage count limit " << 1U << " missing";
6958
6959 string message = "1234567890123456";
6960 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6961
6962 // First usage of RSA key should work.
6963 SignMessage(message, params);
6964
6965 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6966 // must be invalidated from secure storage (such as RPMB partition).
6967 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08006968}
6969
Qi Wud22ec842020-11-26 13:27:53 +08006970INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6971
David Drysdale7de9feb2021-03-05 14:56:19 +00006972typedef KeyMintAidlTestBase GetHardwareInfoTest;
6973
6974TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6975 // Retrieving hardware info should give the same result each time.
6976 KeyMintHardwareInfo info;
6977 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6978 KeyMintHardwareInfo info2;
6979 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6980 EXPECT_EQ(info, info2);
6981}
6982
6983INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6984
Selene Huang31ab4042020-04-29 04:22:39 -07006985typedef KeyMintAidlTestBase AddEntropyTest;
6986
6987/*
6988 * AddEntropyTest.AddEntropy
6989 *
6990 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6991 * is actually added.
6992 */
6993TEST_P(AddEntropyTest, AddEntropy) {
6994 string data = "foo";
6995 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6996}
6997
6998/*
6999 * AddEntropyTest.AddEmptyEntropy
7000 *
7001 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7002 */
7003TEST_P(AddEntropyTest, AddEmptyEntropy) {
7004 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7005}
7006
7007/*
7008 * AddEntropyTest.AddLargeEntropy
7009 *
7010 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7011 */
7012TEST_P(AddEntropyTest, AddLargeEntropy) {
7013 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7014}
7015
David Drysdalebb3d85e2021-04-13 11:15:51 +01007016/*
7017 * AddEntropyTest.AddTooLargeEntropy
7018 *
7019 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7020 */
7021TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7022 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7023 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7024}
7025
Selene Huang31ab4042020-04-29 04:22:39 -07007026INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7027
Selene Huang31ab4042020-04-29 04:22:39 -07007028typedef KeyMintAidlTestBase KeyDeletionTest;
7029
7030/**
7031 * KeyDeletionTest.DeleteKey
7032 *
7033 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7034 * valid key blob.
7035 */
7036TEST_P(KeyDeletionTest, DeleteKey) {
7037 auto error = GenerateKey(AuthorizationSetBuilder()
7038 .RsaSigningKey(2048, 65537)
7039 .Digest(Digest::NONE)
7040 .Padding(PaddingMode::NONE)
7041 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007042 .Authorization(TAG_ROLLBACK_RESISTANCE)
7043 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007044 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7045 GTEST_SKIP() << "Rollback resistance not supported";
7046 }
Selene Huang31ab4042020-04-29 04:22:39 -07007047
7048 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007049 ASSERT_EQ(ErrorCode::OK, error);
7050 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7051 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007052
David Drysdale513bf122021-10-06 11:53:13 +01007053 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007054
David Drysdale513bf122021-10-06 11:53:13 +01007055 string message = "12345678901234567890123456789012";
7056 AuthorizationSet begin_out_params;
7057 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7058 Begin(KeyPurpose::SIGN, key_blob_,
7059 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7060 &begin_out_params));
7061 AbortIfNeeded();
7062 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007063}
7064
7065/**
7066 * KeyDeletionTest.DeleteInvalidKey
7067 *
7068 * This test checks that the HAL excepts invalid key blobs..
7069 */
7070TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7071 // Generate key just to check if rollback protection is implemented
7072 auto error = GenerateKey(AuthorizationSetBuilder()
7073 .RsaSigningKey(2048, 65537)
7074 .Digest(Digest::NONE)
7075 .Padding(PaddingMode::NONE)
7076 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007077 .Authorization(TAG_ROLLBACK_RESISTANCE)
7078 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007079 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7080 GTEST_SKIP() << "Rollback resistance not supported";
7081 }
Selene Huang31ab4042020-04-29 04:22:39 -07007082
7083 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007084 ASSERT_EQ(ErrorCode::OK, error);
7085 AuthorizationSet enforced(SecLevelAuthorizations());
7086 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007087
David Drysdale513bf122021-10-06 11:53:13 +01007088 // Delete the key we don't care about the result at this point.
7089 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007090
David Drysdale513bf122021-10-06 11:53:13 +01007091 // Now create an invalid key blob and delete it.
7092 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007093
David Drysdale513bf122021-10-06 11:53:13 +01007094 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007095}
7096
7097/**
7098 * KeyDeletionTest.DeleteAllKeys
7099 *
7100 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7101 *
7102 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7103 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7104 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7105 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7106 * credentials stored in Keystore/Keymint.
7107 */
7108TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007109 if (!arm_deleteAllKeys) {
7110 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7111 return;
7112 }
Selene Huang31ab4042020-04-29 04:22:39 -07007113 auto error = GenerateKey(AuthorizationSetBuilder()
7114 .RsaSigningKey(2048, 65537)
7115 .Digest(Digest::NONE)
7116 .Padding(PaddingMode::NONE)
7117 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007118 .Authorization(TAG_ROLLBACK_RESISTANCE)
7119 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007120 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7121 GTEST_SKIP() << "Rollback resistance not supported";
7122 }
Selene Huang31ab4042020-04-29 04:22:39 -07007123
7124 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007125 ASSERT_EQ(ErrorCode::OK, error);
7126 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7127 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007128
David Drysdale513bf122021-10-06 11:53:13 +01007129 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007130
David Drysdale513bf122021-10-06 11:53:13 +01007131 string message = "12345678901234567890123456789012";
7132 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07007133
David Drysdale513bf122021-10-06 11:53:13 +01007134 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7135 Begin(KeyPurpose::SIGN, key_blob_,
7136 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7137 &begin_out_params));
7138 AbortIfNeeded();
7139 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007140}
7141
7142INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
7143
David Drysdaled2cc8c22021-04-15 13:29:45 +01007144typedef KeyMintAidlTestBase KeyUpgradeTest;
7145
7146/**
7147 * KeyUpgradeTest.UpgradeInvalidKey
7148 *
7149 * This test checks that the HAL excepts invalid key blobs..
7150 */
7151TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
7152 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
7153
7154 std::vector<uint8_t> new_blob;
7155 Status result = keymint_->upgradeKey(key_blob,
7156 AuthorizationSetBuilder()
7157 .Authorization(TAG_APPLICATION_ID, "clientid")
7158 .Authorization(TAG_APPLICATION_DATA, "appdata")
7159 .vector_data(),
7160 &new_blob);
7161 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
7162}
7163
7164INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
7165
Selene Huang31ab4042020-04-29 04:22:39 -07007166using UpgradeKeyTest = KeyMintAidlTestBase;
7167
7168/*
7169 * UpgradeKeyTest.UpgradeKey
7170 *
7171 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
7172 */
7173TEST_P(UpgradeKeyTest, UpgradeKey) {
7174 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7175 .AesEncryptionKey(128)
7176 .Padding(PaddingMode::NONE)
7177 .Authorization(TAG_NO_AUTH_REQUIRED)));
7178
7179 auto result = UpgradeKey(key_blob_);
7180
7181 // Key doesn't need upgrading. Should get okay, but no new key blob.
7182 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
7183}
7184
7185INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
7186
7187using ClearOperationsTest = KeyMintAidlTestBase;
7188
7189/*
7190 * ClearSlotsTest.TooManyOperations
7191 *
7192 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
7193 * operations are started without being finished or aborted. Also verifies
7194 * that aborting the operations clears the operations.
7195 *
7196 */
7197TEST_P(ClearOperationsTest, TooManyOperations) {
7198 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7199 .Authorization(TAG_NO_AUTH_REQUIRED)
7200 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08007201 .Padding(PaddingMode::NONE)
7202 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007203
7204 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
7205 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08007206 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07007207 AuthorizationSet out_params;
7208 ErrorCode result;
7209 size_t i;
7210
7211 for (i = 0; i < max_operations; i++) {
7212 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
7213 if (ErrorCode::OK != result) {
7214 break;
7215 }
7216 }
7217 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
7218 // Try again just in case there's a weird overflow bug
7219 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
7220 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
7221 for (size_t j = 0; j < i; j++) {
7222 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
7223 << "Aboort failed for i = " << j << std::endl;
7224 }
7225 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
7226 AbortIfNeeded();
7227}
7228
7229INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
7230
7231typedef KeyMintAidlTestBase TransportLimitTest;
7232
7233/*
David Drysdale7de9feb2021-03-05 14:56:19 +00007234 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07007235 *
7236 * Verifies that passing input data to finish succeeds as expected.
7237 */
7238TEST_P(TransportLimitTest, LargeFinishInput) {
7239 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7240 .Authorization(TAG_NO_AUTH_REQUIRED)
7241 .AesEncryptionKey(128)
7242 .BlockMode(BlockMode::ECB)
7243 .Padding(PaddingMode::NONE)));
7244
7245 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
7246 auto cipher_params =
7247 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7248
7249 AuthorizationSet out_params;
7250 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
7251
7252 string plain_message = std::string(1 << msg_size, 'x');
7253 string encrypted_message;
7254 auto rc = Finish(plain_message, &encrypted_message);
7255
7256 EXPECT_EQ(ErrorCode::OK, rc);
7257 EXPECT_EQ(plain_message.size(), encrypted_message.size())
7258 << "Encrypt finish returned OK, but did not consume all of the given input";
7259 cipher_params.push_back(out_params);
7260
7261 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
7262
7263 string decrypted_message;
7264 rc = Finish(encrypted_message, &decrypted_message);
7265 EXPECT_EQ(ErrorCode::OK, rc);
7266 EXPECT_EQ(plain_message.size(), decrypted_message.size())
7267 << "Decrypt finish returned OK, did not consume all of the given input";
7268 }
7269}
7270
7271INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
7272
Seth Moored79a0ec2021-12-13 20:03:33 +00007273static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05007274 switch (curve) {
7275 case EcCurve::P_224:
7276 return NID_secp224r1;
7277 case EcCurve::P_256:
7278 return NID_X9_62_prime256v1;
7279 case EcCurve::P_384:
7280 return NID_secp384r1;
7281 case EcCurve::P_521:
7282 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00007283 case EcCurve::CURVE_25519:
7284 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05007285 }
7286}
7287
David Drysdale42fe1892021-10-14 14:43:46 +01007288class KeyAgreementTest : public KeyMintAidlTestBase {
7289 protected:
7290 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
7291 std::vector<uint8_t>* localPublicKey) {
7292 // Generate EC key locally (with access to private key material)
7293 if (localCurve == EcCurve::CURVE_25519) {
7294 uint8_t privKeyData[32];
7295 uint8_t pubKeyData[32];
7296 X25519_keypair(pubKeyData, privKeyData);
7297 *localPublicKey = vector<uint8_t>(pubKeyData, pubKeyData + 32);
7298 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
7299 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
7300 } else {
7301 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
7302 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
7303 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
7304 ASSERT_NE(group, nullptr);
7305 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
7306 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
7307 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
7308 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
7309
7310 // Get encoded form of the public part of the locally generated key...
7311 unsigned char* p = nullptr;
7312 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
7313 ASSERT_GT(localPublicKeySize, 0);
7314 *localPublicKey =
7315 vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
7316 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
7317 OPENSSL_free(p);
7318 }
7319 }
7320
7321 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
7322 vector<uint8_t> challenge = {0x41, 0x42};
7323 ErrorCode result =
7324 GenerateKey(AuthorizationSetBuilder()
7325 .Authorization(TAG_NO_AUTH_REQUIRED)
7326 .Authorization(TAG_EC_CURVE, curve)
7327 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7328 .Authorization(TAG_ALGORITHM, Algorithm::EC)
7329 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
7330 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
7331 .SetDefaultValidity());
7332 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
7333 ASSERT_GT(cert_chain_.size(), 0);
7334 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7335 ASSERT_NE(kmKeyCert, nullptr);
7336 // Check that keyAgreement (bit 4) is set in KeyUsage
7337 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
7338 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
7339 ASSERT_NE(*kmPubKey, nullptr);
7340 if (dump_Attestations) {
7341 for (size_t n = 0; n < cert_chain_.size(); n++) {
7342 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
7343 }
7344 }
7345 }
7346
7347 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
7348 const std::vector<uint8_t>& localPublicKey) {
7349 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7350 string ZabFromKeyMintStr;
7351 ASSERT_EQ(ErrorCode::OK,
7352 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
7353 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
7354 vector<uint8_t> ZabFromTest;
7355
7356 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
7357 size_t kmPubKeySize = 32;
7358 uint8_t kmPubKeyData[32];
7359 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7360 ASSERT_EQ(kmPubKeySize, 32);
7361
7362 uint8_t localPrivKeyData[32];
7363 size_t localPrivKeySize = 32;
7364 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
7365 &localPrivKeySize));
7366 ASSERT_EQ(localPrivKeySize, 32);
7367
7368 uint8_t sharedKey[32];
7369 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
7370 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
7371 } else {
7372 // Perform local ECDH between the two keys so we can check if we get the same Zab..
7373 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
7374 ASSERT_NE(ctx, nullptr);
7375 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
7376 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
7377 size_t ZabFromTestLen = 0;
7378 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
7379 ZabFromTest.resize(ZabFromTestLen);
7380 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
7381 }
7382 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
7383 }
7384};
7385
David Zeuthene0c40892021-01-08 12:54:11 -05007386/*
7387 * KeyAgreementTest.Ecdh
7388 *
David Drysdale42fe1892021-10-14 14:43:46 +01007389 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05007390 */
7391TEST_P(KeyAgreementTest, Ecdh) {
7392 // Because it's possible to use this API with keys on different curves, we
7393 // check all N^2 combinations where N is the number of supported
7394 // curves.
7395 //
7396 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
7397 // lot more curves we can be smart about things and just pick |otherCurve| so
7398 // it's not |curve| and that way we end up with only 2*N runs
7399 //
7400 for (auto curve : ValidCurves()) {
7401 for (auto localCurve : ValidCurves()) {
7402 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007403 EVP_PKEY_Ptr localPrivKey;
7404 vector<uint8_t> localPublicKey;
7405 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007406
7407 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007408 EVP_PKEY_Ptr kmPubKey;
7409 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007410
7411 // Now that we have the two keys, we ask KeyMint to perform ECDH...
7412 if (curve != localCurve) {
7413 // If the keys are using different curves KeyMint should fail with
7414 // ErrorCode:INVALID_ARGUMENT. Check that.
7415 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7416 string ZabFromKeyMintStr;
7417 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01007418 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05007419 &ZabFromKeyMintStr));
7420
7421 } else {
7422 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01007423 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007424 }
7425
7426 CheckedDeleteKey();
7427 }
7428 }
7429}
7430
David Drysdale42fe1892021-10-14 14:43:46 +01007431/*
7432 * KeyAgreementTest.EcdhCurve25519
7433 *
7434 * Verifies that ECDH works for curve25519. This is also covered by the general
7435 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
7436 * KeyMint 1.0.
7437 */
7438TEST_P(KeyAgreementTest, EcdhCurve25519) {
7439 if (!Curve25519Supported()) {
7440 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7441 }
7442
7443 // Generate EC key in KeyMint (only access to public key material)
7444 EcCurve curve = EcCurve::CURVE_25519;
7445 EVP_PKEY_Ptr kmPubKey = nullptr;
7446 GenerateKeyMintEcKey(curve, &kmPubKey);
7447
7448 // Generate EC key on same curve locally (with access to private key material).
7449 EVP_PKEY_Ptr privKey;
7450 vector<uint8_t> encodedPublicKey;
7451 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7452
7453 // Agree on a key between local and KeyMint and check it.
7454 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7455
7456 CheckedDeleteKey();
7457}
7458
7459/*
7460 * KeyAgreementTest.EcdhCurve25519Imported
7461 *
7462 * Verifies that ECDH works for an imported curve25519 key.
7463 */
7464TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
7465 if (!Curve25519Supported()) {
7466 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7467 }
7468
7469 // Import x25519 key into KeyMint.
7470 EcCurve curve = EcCurve::CURVE_25519;
7471 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
7472 .Authorization(TAG_NO_AUTH_REQUIRED)
7473 .EcdsaKey(EcCurve::CURVE_25519)
7474 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7475 .SetDefaultValidity(),
7476 KeyFormat::PKCS8, x25519_pkcs8_key));
7477 ASSERT_GT(cert_chain_.size(), 0);
7478 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7479 ASSERT_NE(kmKeyCert, nullptr);
7480 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
7481 ASSERT_NE(kmPubKey.get(), nullptr);
7482
7483 // Expect the import to emit corresponding public key data.
7484 size_t kmPubKeySize = 32;
7485 uint8_t kmPubKeyData[32];
7486 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7487 ASSERT_EQ(kmPubKeySize, 32);
7488 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
7489 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
7490
7491 // Generate EC key on same curve locally (with access to private key material).
7492 EVP_PKEY_Ptr privKey;
7493 vector<uint8_t> encodedPublicKey;
7494 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7495
7496 // Agree on a key between local and KeyMint and check it.
7497 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7498
7499 CheckedDeleteKey();
7500}
7501
7502/*
7503 * KeyAgreementTest.EcdhCurve25519InvalidSize
7504 *
7505 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
7506 */
7507TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
7508 if (!Curve25519Supported()) {
7509 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7510 }
7511
7512 // Generate EC key in KeyMint (only access to public key material)
7513 EcCurve curve = EcCurve::CURVE_25519;
7514 EVP_PKEY_Ptr kmPubKey = nullptr;
7515 GenerateKeyMintEcKey(curve, &kmPubKey);
7516
7517 // Generate EC key on same curve locally (with access to private key material).
7518 EVP_PKEY_Ptr privKey;
7519 vector<uint8_t> encodedPublicKey;
7520 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7521
7522 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7523 string ZabFromKeyMintStr;
7524 // Send in an incomplete public key.
7525 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
7526 &ZabFromKeyMintStr));
7527
7528 CheckedDeleteKey();
7529}
7530
7531/*
7532 * KeyAgreementTest.EcdhCurve25519Mismatch
7533 *
7534 * Verifies that ECDH fails between curve25519 and other curves.
7535 */
7536TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
7537 if (!Curve25519Supported()) {
7538 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7539 }
7540
7541 // Generate EC key in KeyMint (only access to public key material)
7542 EcCurve curve = EcCurve::CURVE_25519;
7543 EVP_PKEY_Ptr kmPubKey = nullptr;
7544 GenerateKeyMintEcKey(curve, &kmPubKey);
7545
7546 for (auto localCurve : ValidCurves()) {
7547 if (localCurve == curve) {
7548 continue;
7549 }
7550 // Generate EC key on a different curve locally (with access to private key material).
7551 EVP_PKEY_Ptr privKey;
7552 vector<uint8_t> encodedPublicKey;
7553 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
7554
7555 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7556 string ZabFromKeyMintStr;
7557 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
7558 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
7559 &ZabFromKeyMintStr));
7560 }
7561
7562 CheckedDeleteKey();
7563}
7564
David Zeuthene0c40892021-01-08 12:54:11 -05007565INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
7566
David Drysdaled2cc8c22021-04-15 13:29:45 +01007567using DestroyAttestationIdsTest = KeyMintAidlTestBase;
7568
7569// This is a problematic test, as it can render the device under test permanently unusable.
7570// Re-enable and run at your own risk.
7571TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
7572 auto result = DestroyAttestationIds();
7573 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
7574}
7575
7576INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
7577
Shawn Willdend659c7c2021-02-19 14:51:51 -07007578using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007579
David Drysdaledb0dcf52021-05-18 11:43:31 +01007580/*
7581 * EarlyBootKeyTest.CreateEarlyBootKeys
7582 *
7583 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
7584 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007585TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01007586 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007587 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7588 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7589
David Drysdaleadfe6112021-05-27 12:00:53 +01007590 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
7591 ASSERT_GT(keyData.blob.size(), 0U);
7592 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7593 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7594 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007595 CheckedDeleteKey(&aesKeyData.blob);
7596 CheckedDeleteKey(&hmacKeyData.blob);
7597 CheckedDeleteKey(&rsaKeyData.blob);
7598 CheckedDeleteKey(&ecdsaKeyData.blob);
7599}
7600
David Drysdaledb0dcf52021-05-18 11:43:31 +01007601/*
David Drysdaleadfe6112021-05-27 12:00:53 +01007602 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
7603 *
7604 * Verifies that creating an early boot key with attestation succeeds.
7605 */
7606TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
7607 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
7608 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
7609 builder->AttestationChallenge("challenge");
7610 builder->AttestationApplicationId("app_id");
7611 });
7612
7613 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
7614 ASSERT_GT(keyData.blob.size(), 0U);
7615 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7616 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7617 }
7618 CheckedDeleteKey(&aesKeyData.blob);
7619 CheckedDeleteKey(&hmacKeyData.blob);
7620 CheckedDeleteKey(&rsaKeyData.blob);
7621 CheckedDeleteKey(&ecdsaKeyData.blob);
7622}
7623
7624/*
7625 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01007626 *
7627 * Verifies that using early boot keys at a later stage fails.
7628 */
7629TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
7630 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7631 .Authorization(TAG_NO_AUTH_REQUIRED)
7632 .Authorization(TAG_EARLY_BOOT_ONLY)
7633 .HmacKey(128)
7634 .Digest(Digest::SHA_2_256)
7635 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
7636 AuthorizationSet output_params;
7637 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
7638 AuthorizationSetBuilder()
7639 .Digest(Digest::SHA_2_256)
7640 .Authorization(TAG_MAC_LENGTH, 256),
7641 &output_params));
7642}
7643
7644/*
7645 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
7646 *
7647 * Verifies that importing early boot keys fails.
7648 */
7649TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
7650 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
7651 .Authorization(TAG_NO_AUTH_REQUIRED)
7652 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01007653 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01007654 .Digest(Digest::SHA_2_256)
7655 .SetDefaultValidity(),
7656 KeyFormat::PKCS8, ec_256_key));
7657}
7658
David Drysdaled2cc8c22021-04-15 13:29:45 +01007659// 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 +00007660// boot stage, which no proper Android device is by the time we can run VTS. To use this,
7661// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
7662// early boot, so you'll have to reboot between runs.
7663TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
7664 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7665 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7666 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
7667 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7668 EXPECT_TRUE(
7669 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7670 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7671 EXPECT_TRUE(
7672 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7673
7674 // Should be able to use keys, since early boot has not ended
7675 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7676 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
7677 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
7678 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
7679
7680 // End early boot
7681 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
7682 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
7683
7684 // Should not be able to use already-created keys.
7685 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
7686 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
7687 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
7688 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
7689
7690 CheckedDeleteKey(&aesKeyData.blob);
7691 CheckedDeleteKey(&hmacKeyData.blob);
7692 CheckedDeleteKey(&rsaKeyData.blob);
7693 CheckedDeleteKey(&ecdsaKeyData.blob);
7694
7695 // Should not be able to create new keys
7696 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
7697 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
7698
7699 CheckedDeleteKey(&aesKeyData.blob);
7700 CheckedDeleteKey(&hmacKeyData.blob);
7701 CheckedDeleteKey(&rsaKeyData.blob);
7702 CheckedDeleteKey(&ecdsaKeyData.blob);
7703}
Shawn Willdend659c7c2021-02-19 14:51:51 -07007704
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007705INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
7706
Shawn Willdend659c7c2021-02-19 14:51:51 -07007707using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007708
7709// This may be a problematic test. It can't be run repeatedly without unlocking the device in
7710// between runs... and on most test devices there are no enrolled credentials so it can't be
7711// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
7712// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
7713// a manual test process, which includes unlocking between runs, which is why it's included here.
7714// Well, that and the fact that it's the only test we can do without also making calls into the
7715// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
7716// implications might be, so that may or may not be a solution.
7717TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
7718 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7719 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
7720
7721 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7722 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
7723 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
7724 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
7725
7726 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01007727 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007728 ASSERT_EQ(ErrorCode::OK, rc);
7729 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
7730 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
7731 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
7732 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
7733
7734 CheckedDeleteKey(&aesKeyData.blob);
7735 CheckedDeleteKey(&hmacKeyData.blob);
7736 CheckedDeleteKey(&rsaKeyData.blob);
7737 CheckedDeleteKey(&ecdsaKeyData.blob);
7738}
Shawn Willdend659c7c2021-02-19 14:51:51 -07007739
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007740INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
7741
Janis Danisevskis24c04702020-12-16 18:28:39 -08007742} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07007743
7744int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07007745 std::cout << "Testing ";
7746 auto halInstances =
7747 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
7748 std::cout << "HAL instances:\n";
7749 for (auto& entry : halInstances) {
7750 std::cout << " " << entry << '\n';
7751 }
7752
Selene Huang31ab4042020-04-29 04:22:39 -07007753 ::testing::InitGoogleTest(&argc, argv);
7754 for (int i = 1; i < argc; ++i) {
7755 if (argv[i][0] == '-') {
7756 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07007757 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
7758 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07007759 }
7760 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07007761 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
7762 dump_Attestations = true;
7763 } else {
7764 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07007765 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00007766 if (std::string(argv[i]) == "--skip_boot_pl_check") {
7767 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
7768 // be run in emulated environments that don't have the normal bootloader
7769 // interactions.
7770 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
7771 }
Selene Huang31ab4042020-04-29 04:22:39 -07007772 }
7773 }
Shawn Willden08a7e432020-12-11 13:05:27 +00007774 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07007775}