blob: 767de2bdee82571f1c102331be4188cde190cedf [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
David Drysdale37af4b32021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Drysdale42fe1892021-10-14 14:43:46 +010025#include <openssl/curve25519.h>
David Zeuthene0c40892021-01-08 12:54:11 -050026#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070027#include <openssl/evp.h>
28#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050029#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070030
31#include <cutils/properties.h>
32
David Drysdale4dc01072021-04-01 12:17:35 +010033#include <android/binder_manager.h>
34
35#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080036#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070037
Shawn Willden08a7e432020-12-11 13:05:27 +000038#include <keymint_support/key_param_output.h>
39#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070040
41#include "KeyMintAidlTestBase.h"
42
Janis Danisevskis24c04702020-12-16 18:28:39 -080043using aidl::android::hardware::security::keymint::AuthorizationSet;
44using aidl::android::hardware::security::keymint::KeyCharacteristics;
45using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070046
Selene Huang31ab4042020-04-29 04:22:39 -070047namespace std {
48
Janis Danisevskis24c04702020-12-16 18:28:39 -080049using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070050
51template <>
52struct std::equal_to<KeyCharacteristics> {
53 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070054 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070055
Shawn Willden7f424372021-01-10 18:06:50 -070056 // this isn't very efficient. Oh, well.
57 AuthorizationSet a_auths(a.authorizations);
58 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070059
Shawn Willden7f424372021-01-10 18:06:50 -070060 a_auths.Sort();
61 b_auths.Sort();
62
63 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070064 }
65};
66
67} // namespace std
68
Janis Danisevskis24c04702020-12-16 18:28:39 -080069namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000070
Selene Huang31ab4042020-04-29 04:22:39 -070071namespace {
72
David Drysdalefeab5d92022-01-06 15:46:23 +000073// Maximum supported Ed25519 message size.
74const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
75
David Drysdaledbbbe2e2021-12-02 07:44:23 +000076// Whether to check that BOOT_PATCHLEVEL is populated.
77bool check_boot_pl = true;
78
Seth Moore7a55ae32021-06-23 14:28:11 -070079// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000080// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070081// is a small (roughly 1/256) chance that corrupting ciphertext still results
82// in valid PKCS7 padding.
83constexpr size_t kMaxPaddingCorruptionRetries = 8;
84
Selene Huang31ab4042020-04-29 04:22:39 -070085template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000086bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
87 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070088 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080089 if (auto p = authorizationValue(ttag, param)) {
90 return *p == expected_value;
91 }
92 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070093 });
94 return (it != set.end());
95}
96
97template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000098bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070099 auto it = std::find_if(set.begin(), set.end(),
100 [&](const KeyParameter& param) { return param.tag == tag; });
101 return (it != set.end());
102}
103
104constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
108 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
110 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
111 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
114 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
115 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
117 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
120
121string hex2str(string a) {
122 string b;
123 size_t num = a.size() / 2;
124 b.resize(num);
125 for (size_t i = 0; i < num; i++) {
126 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
127 }
128 return b;
129}
130
David Drysdaled2cc8c22021-04-15 13:29:45 +0100131string rsa_key = hex2str(
132 // RFC 5208 s5
133 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
134 "020100" // INTEGER length 1 value 0x00 (version)
135 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
136 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
137 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
138 "0500" // NULL (parameters)
139 // } end SEQUENCE (AlgorithmIdentifier)
140 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
141 // RFC 8017 A.1.2
142 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
143 "020100" // INTEGER length 1 value 0x00 (version)
144 "028181" // INTEGER length 0x81 value (modulus) ...
145 "00c6095409047d8634812d5a218176e4"
146 "5c41d60a75b13901f234226cffe77652"
147 "1c5a77b9e389417b71c0b6a44d13afe4"
148 "e4a2805d46c9da2935adb1ff0c1f24ea"
149 "06e62b20d776430a4d435157233c6f91"
150 "6783c30e310fcbd89b85c2d567711697"
151 "85ac12bca244abda72bfb19fc44d27c8"
152 "1e1d92de284f4061edfd99280745ea6d"
153 "25"
154 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
155 "028180" // INTEGER length 0x80 (privateExponent) value...
156 "1be0f04d9cae3718691f035338308e91"
157 "564b55899ffb5084d2460e6630257e05"
158 "b3ceab02972dfabcd6ce5f6ee2589eb6"
159 "7911ed0fac16e43a444b8c861e544a05"
160 "93365772f8baf6b22fc9e3c5f1024b06"
161 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
162 "ace7240290bef16c0b3f7f3cdd64ce3a"
163 "b5912cf6e32f39ab188358afcccd8081"
164 "0241" // INTEGER length 0x41 (prime1)
165 "00e4b49ef50f765d3b24dde01aceaaf1"
166 "30f2c76670a91a61ae08af497b4a82be"
167 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
168 "8c92bfab137fba2285227b83c342ff7c"
169 "55"
170 "0241" // INTEGER length 0x41 (prime2)
171 "00ddabb5839c4c7f6bf3d4183231f005"
172 "b31aa58affdda5c79e4cce217f6bc930"
173 "dbe563d480706c24e9ebfcab28a6cdef"
174 "d324b77e1bf7251b709092c24ff501fd"
175 "91"
176 "0240" // INTEGER length 0x40 (exponent1)
177 "23d4340eda3445d8cd26c14411da6fdc"
178 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
179 "842c1d280405bc2f6c1bea214a1d742a"
180 "b996b35b63a82a5e470fa88dbf823cdd"
181 "0240" // INTEGER length 0x40 (exponent2)
182 "1b7b57449ad30d1518249a5f56bb9829"
183 "4d4b6ac12ffc86940497a5a5837a6cf9"
184 "46262b494526d328c11e1126380fde04"
185 "c24f916dec250892db09a6d77cdba351"
186 "0240" // INTEGER length 0x40 (coefficient)
187 "7762cd8f4d050da56bd591adb515d24d"
188 "7ccd32cca0d05f866d583514bd7324d5"
189 "f33645e8ed8b4a1cb3cc4a1d67987399"
190 "f2a09f5b3fb68c88d5e5d90ac33492d6"
191 // } end SEQUENCE (PrivateKey)
192 // } end SEQUENCE (PrivateKeyInfo)
193);
Selene Huang31ab4042020-04-29 04:22:39 -0700194
Selene Huange5727e62021-04-13 22:41:20 -0700195/*
196 * DER-encoded PKCS#8 format RSA key. Generated using:
197 *
198 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
199 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100200string rsa_2048_key = hex2str(
201 // RFC 5208 s5
202 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
203 "020100" // INTEGER length 1 value 0x00 (version)
204 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
205 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
206 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
207 "0500" // NULL (parameters)
208 // } end SEQUENCE (AlgorithmIdentifier)
209 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
210 // RFC 8017 A.1.2
211 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
212 "020100" // INTEGER length 1 value 0x00 (version)
213 "02820101" // INTEGER length 0x101 value (modulus) ...
214 "00BEBC342B56D443B1299F9A6A7056E8"
215 "0A897E318476A5A18029E63B2ED739A6"
216 "1791D339F58DC763D9D14911F2EDEC38"
217 "3DEE11F6319B44510E7A3ECD9B79B973"
218 "82E49500ACF8117DC89CAF0E621F7775"
219 "6554A2FD4664BFE7AB8B59AB48340DBF"
220 "A27B93B5A81F6ECDEB02D0759307128D"
221 "F3E3BAD4055C8B840216DFAA5700670E"
222 "6C5126F0962FCB70FF308F25049164CC"
223 "F76CC2DA66A7DD9A81A714C2809D6918"
224 "6133D29D84568E892B6FFBF3199BDB14"
225 "383EE224407F190358F111A949552ABA"
226 "6714227D1BD7F6B20DD0CB88F9467B71"
227 "9339F33BFF35B3870B3F62204E4286B0"
228 "948EA348B524544B5F9838F29EE643B0"
229 "79EEF8A713B220D7806924CDF7295070"
230 "C5"
231 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
232 "02820100" // INTEGER length 0x100 (privateExponent) value...
233 "69F377F35F2F584EF075353CCD1CA997"
234 "38DB3DBC7C7FF35F9366CE176DFD1B13"
235 "5AB10030344ABF5FBECF1D4659FDEF1C"
236 "0FC430834BE1BE3911951377BB3D563A"
237 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
238 "2686C7B4B3C09A7B8354133E6F93F790"
239 "D59EAEB92E84C9A4339302CCE28FDF04"
240 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
241 "6AB706645BF074A4E4090D06FB163124"
242 "365FD5EE7A20D350E9958CC30D91326E"
243 "1B292E9EF5DB408EC42DAF737D201497"
244 "04D0A678A0FB5B5446863B099228A352"
245 "D604BA8091A164D01D5AB05397C71EAD"
246 "20BE2A08FC528FE442817809C787FEE4"
247 "AB97F97B9130D022153EDC6EB6CBE7B0"
248 "F8E3473F2E901209B5DB10F93604DB01"
249 "028181" // INTEGER length 0x81 (prime1)
250 "00E83C0998214941EA4F9293F1B77E2E"
251 "99E6CF305FAF358238E126124FEAF2EB"
252 "9724B2EA7B78E6032343821A80E55D1D"
253 "88FB12D220C3F41A56142FEC85796D19"
254 "17F1E8C774F142B67D3D6E7B7E6B4383"
255 "E94DB5929089DBB346D5BDAB40CC2D96"
256 "EE0409475E175C63BF78CFD744136740"
257 "838127EA723FF3FE7FA368C1311B4A4E"
258 "05"
259 "028181" // INTEGER length 0x81 (prime2)
260 "00D240FCC0F5D7715CDE21CB2DC86EA1"
261 "46132EA3B06F61FF2AF54BF38473F59D"
262 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
263 "B1B58C39F95E4798CCBB43E83D0119AC"
264 "F532F359CA743C85199F0286610E2009"
265 "97D7312917179AC9B67558773212EC96"
266 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
267 "94D94E066A0900B7B70E82A44FB30053"
268 "C1"
269 "028181" // INTEGER length 0x81 (exponent1)
270 "00AD15DA1CBD6A492B66851BA8C316D3"
271 "8AB700E2CFDDD926A658003513C54BAA"
272 "152B30021D667D20078F500F8AD3E7F3"
273 "945D74A891ED1A28EAD0FEEAEC8C14A8"
274 "E834CF46A13D1378C99D18940823CFDD"
275 "27EC5810D59339E0C34198AC638E09C8"
276 "7CBB1B634A9864AE9F4D5EB2D53514F6"
277 "7B4CAEC048C8AB849A02E397618F3271"
278 "35"
279 "028180" // INTEGER length 0x80 (exponent2)
280 "1FA2C1A5331880A92D8F3E281C617108"
281 "BF38244F16E352E69ED417C7153F9EC3"
282 "18F211839C643DCF8B4DD67CE2AC312E"
283 "95178D5D952F06B1BF779F4916924B70"
284 "F582A23F11304E02A5E7565AE22A35E7"
285 "4FECC8B6FDC93F92A1A37703E4CF0E63"
286 "783BD02EB716A7ECBBFA606B10B74D01"
287 "579522E7EF84D91FC522292108D902C1"
288 "028180" // INTEGER length 0x80 (coefficient)
289 "796FE3825F9DCC85DF22D58690065D93"
290 "898ACD65C087BEA8DA3A63BF4549B795"
291 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
292 "0D74F40DED8E1102C52152A31B6165F8"
293 "3A6722AECFCC35A493D7634664B888A0"
294 "8D3EB034F12EA28BFEE346E205D33482"
295 "7F778B16ED40872BD29FCB36536B6E93"
296 "FFB06778696B4A9D81BB0A9423E63DE5"
297 // } end SEQUENCE (PrivateKey)
298 // } end SEQUENCE (PrivateKeyInfo)
299);
Selene Huange5727e62021-04-13 22:41:20 -0700300
David Drysdaled2cc8c22021-04-15 13:29:45 +0100301string ec_256_key = hex2str(
302 // RFC 5208 s5
303 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
304 "020100" // INTEGER length 1 value 0 (version)
305 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
306 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
307 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
308 "0608" // OBJECT IDENTIFIER length 8 (param)
309 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
310 // } end SEQUENCE (AlgorithmIdentifier)
311 "046d" // OCTET STRING length 0x6d (privateKey) holding...
312 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
313 "020101" // INTEGER length 1 value 1 (version)
314 "0420" // OCTET STRING length 0x20 (privateKey)
315 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
316 "941eed09366bc03299986481f3a4d859"
317 "a144" // TAG [1] len 0x44 (publicKey) {
318 "03420004bf85d7720d07c25461683bc6"
319 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
320 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
321 "bcc41c6eb00083cf3376d11fd44949e0"
322 "b2183bfe"
323 // } end SEQUENCE (ECPrivateKey)
324 // } end SEQUENCE (PrivateKeyInfo)
325);
Selene Huang31ab4042020-04-29 04:22:39 -0700326
David Drysdaled2cc8c22021-04-15 13:29:45 +0100327string ec_521_key = hex2str(
328 // RFC 5208 s5
329 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
330 "020100" // INTEGER length 1 value 0 (version)
331 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
332 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
333 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
334 "0605" // OBJECT IDENTIFIER length 5 (param)
335 "2B81040023" // 1.3.132.0.35 (secp521r1)
336 // } end SEQUENCE (AlgorithmIdentifier)
337 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
338 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
339 "020101" // INTEGER length 1 value 1 (version)
340 "0442" // OCTET STRING length 0x42 (privateKey)
341 "0011458C586DB5DAA92AFAB03F4FE46A"
342 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
343 "9D18D7D08B5BCFA0E53C75B064AD51C4"
344 "49BAE0258D54B94B1E885DED08ED4FB2"
345 "5CE9"
346 "A18189" // TAG [1] len 0x89 (publicKey) {
347 "03818600040149EC11C6DF0FA122C6A9"
348 "AFD9754A4FA9513A627CA329E349535A"
349 "5629875A8ADFBE27DCB932C051986377"
350 "108D054C28C6F39B6F2C9AF81802F9F3"
351 "26B842FF2E5F3C00AB7635CFB36157FC"
352 "0882D574A10D839C1A0C049DC5E0D775"
353 "E2EE50671A208431BB45E78E70BEFE93"
354 "0DB34818EE4D5C26259F5C6B8E28A652"
355 "950F9F88D7B4B2C9D9"
356 // } end SEQUENCE (ECPrivateKey)
357 // } end SEQUENCE (PrivateKeyInfo)
358);
Selene Huang31ab4042020-04-29 04:22:39 -0700359
David Drysdaled2cc8c22021-04-15 13:29:45 +0100360string ec_256_key_rfc5915 = hex2str(
361 // RFC 5208 s5
362 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
363 "020100" // INTEGER length 1 value 0 (version)
364 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
365 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
366 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
367 "0608" // OBJECT IDENTIFIER length 8 (param)
368 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
369 // } end SEQUENCE (AlgorithmIdentifier)
370 "0479" // OCTET STRING length 0x79 (privateKey) holding...
371 // RFC 5915 s3
372 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
373 "020101" // INTEGER length 1 value 1 (version)
374 "0420" // OCTET STRING length 0x42 (privateKey)
375 "782370a8c8ce5537baadd04dcff079c8"
376 "158cfa9c67b818b38e8d21c9fa750c1d"
377 "a00a" // TAG [0] length 0xa (parameters)
378 "0608" // OBJECT IDENTIFIER length 8
379 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
380 // } end TAG [0]
381 "a144" // TAG [1] length 0x44 (publicKey) {
382 "0342" // BIT STRING length 0x42
383 "00" // no pad bits
384 "04e2cc561ee701da0ad0ef0d176bb0c9"
385 "19d42e79c393fdc1bd6c4010d85cf2cf"
386 "8e68c905464666f98dad4f01573ba810"
387 "78b3428570a439ba3229fbc026c55068"
388 "2f"
389 // } end SEQUENCE (ECPrivateKey)
390 // } end SEQUENCE (PrivateKeyInfo)
391);
Selene Huang31ab4042020-04-29 04:22:39 -0700392
David Drysdaled2cc8c22021-04-15 13:29:45 +0100393string ec_256_key_sec1 = hex2str(
394 // RFC 5208 s5
395 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
396 "020100" // INTEGER length 1 value 0 (version)
397 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
398 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
399 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
400 "0608" // OBJECT IDENTIFIER length 8 (param)
401 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
402 // } end SEQUENCE (AlgorithmIdentifier)
403 "046d" // OCTET STRING length 0x6d (privateKey) holding...
404 // SEC1-v2 C.4
405 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
406 "020101" // INTEGER length 1 value 0x01 (version)
407 "0420" // OCTET STRING length 0x20 (privateKey)
408 "782370a8c8ce5537baadd04dcff079c8"
409 "158cfa9c67b818b38e8d21c9fa750c1d"
410 "a144" // TAG [1] length 0x44 (publicKey) {
411 "0342" // BIT STRING length 0x42
412 "00" // no pad bits
413 "04e2cc561ee701da0ad0ef0d176bb0c9"
414 "19d42e79c393fdc1bd6c4010d85cf2cf"
415 "8e68c905464666f98dad4f01573ba810"
416 "78b3428570a439ba3229fbc026c55068"
417 "2f"
418 // } end TAG [1] (publicKey)
419 // } end SEQUENCE (PrivateKeyInfo)
420);
Selene Huang31ab4042020-04-29 04:22:39 -0700421
David Drysdale42fe1892021-10-14 14:43:46 +0100422/**
423 * Ed25519 key pair generated as follows:
424 * ```
425 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
426 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
427 * Generating a ED25519 private key writing new private key to
428 * 'ed25519_priv.key'
429 * -----
430 * % cat ed25519_priv.key
431 * -----BEGIN PRIVATE KEY-----
432 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
433 * -----END PRIVATE KEY-----
434 * % der2ascii -pem -i ed25519_priv.key
435 * SEQUENCE {
436 * INTEGER { 0 }
437 * SEQUENCE {
438 * # ed25519
439 * OBJECT_IDENTIFIER { 1.3.101.112 }
440 * }
441 * OCTET_STRING {
442 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
443 * }
444 * }
445 * % cat ed25519.pem
446 * -----BEGIN CERTIFICATE-----
447 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
448 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
449 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
450 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
451 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
452 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
453 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
454 * -----END CERTIFICATE-----
455 * % openssl x509 -in ed25519.pem -text -noout
456 * Certificate:
457 * Data:
458 * Version: 3 (0x2)
459 * Serial Number:
460 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
461 * Signature Algorithm: ED25519
462 * Issuer: CN = fake.ed25519.com
463 * Validity
464 * Not Before: Oct 20 08:27:42 2021 GMT
465 * Not After : Sep 20 08:27:42 2023 GMT
466 * Subject: CN = fake.ed25519.com
467 * Subject Public Key Info:
468 * Public Key Algorithm: ED25519
469 * ED25519 Public-Key:
470 * pub:
471 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
472 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
473 * 56:91
474 * X509v3 extensions:
475 * X509v3 Subject Key Identifier:
476 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
477 * X509v3 Authority Key Identifier:
478 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
479 *
480 * X509v3 Basic Constraints: critical
481 * CA:TRUE
482 * Signature Algorithm: ED25519
483 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
484 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
485 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
486 * e7:07:32:60:32:8d:bb:eb:f6:0f
487 * ```
488 */
489string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
490string ed25519_pkcs8_key = hex2str(
491 // RFC 5208 s5
492 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
493 "0201" // INTEGER length 1 (Version)
494 "00" // version 0
495 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
496 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
497 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
498 // } end SEQUENCE (AlgorithmIdentifier)
499 "0422" // OCTET STRING length 0x22 (PrivateKey)
500 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
501 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
502 // } end SEQUENCE (PrivateKeyInfo)
503);
504string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
505
506/**
507 * X25519 key pair generated as follows:
508 * ```
509 * % openssl genpkey -algorithm X25519 > x25519_priv.key
510 * % cat x25519_priv.key
511 * -----BEGIN PRIVATE KEY-----
512 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
513 * -----END PRIVATE KEY-----
514 * % der2ascii -pem -i x25519_priv.key
515 * SEQUENCE {
516 * INTEGER { 0 }
517 * SEQUENCE {
518 * # x25519
519 * OBJECT_IDENTIFIER { 1.3.101.110 }
520 * }
521 * OCTET_STRING {
522 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
523 * }
524 * }
525 * ```
526 */
527
528string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
529string x25519_pkcs8_key = hex2str(
530 // RFC 5208 s5
531 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
532 "0201" // INTEGER length 1 (Version)
533 "00" // version 0
534 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
535 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
536 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
537 "0422" // OCTET STRING length 0x22 (PrivateKey)
538 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
539 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
540string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
541
Selene Huang31ab4042020-04-29 04:22:39 -0700542struct RSA_Delete {
543 void operator()(RSA* p) { RSA_free(p); }
544};
545
Selene Huang31ab4042020-04-29 04:22:39 -0700546std::string make_string(const uint8_t* data, size_t length) {
547 return std::string(reinterpret_cast<const char*>(data), length);
548}
549
550template <size_t N>
551std::string make_string(const uint8_t (&a)[N]) {
552 return make_string(a, N);
553}
554
555class AidlBuf : public vector<uint8_t> {
556 typedef vector<uint8_t> super;
557
558 public:
559 AidlBuf() {}
560 AidlBuf(const super& other) : super(other) {}
561 AidlBuf(super&& other) : super(std::move(other)) {}
562 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
563
564 AidlBuf& operator=(const super& other) {
565 super::operator=(other);
566 return *this;
567 }
568
569 AidlBuf& operator=(super&& other) {
570 super::operator=(std::move(other));
571 return *this;
572 }
573
574 AidlBuf& operator=(const string& other) {
575 resize(other.size());
576 for (size_t i = 0; i < other.size(); ++i) {
577 (*this)[i] = static_cast<uint8_t>(other[i]);
578 }
579 return *this;
580 }
581
582 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
583};
584
David Drysdale4dc01072021-04-01 12:17:35 +0100585string device_suffix(const string& name) {
586 size_t pos = name.find('/');
587 if (pos == string::npos) {
588 return name;
589 }
590 return name.substr(pos + 1);
591}
592
593bool matching_rp_instance(const string& km_name,
594 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
595 string km_suffix = device_suffix(km_name);
596
597 vector<string> rp_names =
598 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
599 for (const string& rp_name : rp_names) {
600 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
601 // KeyMint instance, assume they match.
602 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
603 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
604 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
605 return true;
606 }
607 }
608 return false;
609}
610
Selene Huang31ab4042020-04-29 04:22:39 -0700611} // namespace
612
613class NewKeyGenerationTest : public KeyMintAidlTestBase {
614 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700615 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000616 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700617 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700618
Selene Huang31ab4042020-04-29 04:22:39 -0700619 // Check that some unexpected tags/values are NOT present.
620 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
621 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000622 }
623
624 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
625 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
626 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
627 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
628
629 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000630 }
631
632 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
633 // TODO(swillden): Distinguish which params should be in which auth list.
634 AuthorizationSet auths;
635 for (auto& entry : keyCharacteristics) {
636 auths.push_back(AuthorizationSet(entry.authorizations));
637 }
638 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
639
640 // Verify that App data, ROT and auth timeout are NOT included.
641 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
642 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700643 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
644
David Drysdaled2cc8c22021-04-15 13:29:45 +0100645 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
646 // never adds it.
647 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
648
David Drysdale7de9feb2021-03-05 14:56:19 +0000649 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700650 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000651 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700652 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700653 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000654 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700655 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000656
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000657 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100658 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
659 EXPECT_TRUE(vendor_pl);
660 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000661
662 // Should include boot patchlevel (but there are some test scenarios where this is not
663 // possible).
664 if (check_boot_pl) {
665 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
666 EXPECT_TRUE(boot_pl);
667 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100668
David Drysdale7de9feb2021-03-05 14:56:19 +0000669 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700670 }
671};
672
673/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000674 * NewKeyGenerationTest.Aes
675 *
676 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
677 * have correct characteristics.
678 */
679TEST_P(NewKeyGenerationTest, Aes) {
680 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
681 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
682 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
683 SCOPED_TRACE(testing::Message()
684 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
685 vector<uint8_t> key_blob;
686 vector<KeyCharacteristics> key_characteristics;
687 auto builder = AuthorizationSetBuilder()
688 .AesEncryptionKey(key_size)
689 .BlockMode(block_mode)
690 .Padding(padding_mode)
691 .SetDefaultValidity();
692 if (block_mode == BlockMode::GCM) {
693 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
694 }
695 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
696
697 EXPECT_GT(key_blob.size(), 0U);
698 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100699 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000700
701 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
702
703 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
704 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
705 << "Key size " << key_size << "missing";
706
707 CheckedDeleteKey(&key_blob);
708 }
709 }
710 }
711}
712
713/*
714 * NewKeyGenerationTest.AesInvalidSize
715 *
716 * Verifies that specifying an invalid key size for AES key generation returns
717 * UNSUPPORTED_KEY_SIZE.
718 */
719TEST_P(NewKeyGenerationTest, AesInvalidSize) {
720 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
721 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
722 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
723 SCOPED_TRACE(testing::Message()
724 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
725 vector<uint8_t> key_blob;
726 vector<KeyCharacteristics> key_characteristics;
727 auto builder = AuthorizationSetBuilder()
728 .AesEncryptionKey(key_size)
729 .BlockMode(block_mode)
730 .Padding(padding_mode)
731 .SetDefaultValidity();
732 if (block_mode == BlockMode::GCM) {
733 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
734 }
735 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
736 GenerateKey(builder, &key_blob, &key_characteristics));
737 }
738 }
739 }
740
741 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
742 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
743 vector<uint8_t> key_blob;
744 vector<KeyCharacteristics> key_characteristics;
745 // No key size specified
746 auto builder = AuthorizationSetBuilder()
747 .Authorization(TAG_ALGORITHM, Algorithm::AES)
748 .BlockMode(block_mode)
749 .Padding(padding_mode)
750 .SetDefaultValidity();
751 if (block_mode == BlockMode::GCM) {
752 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
753 }
754 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
755 GenerateKey(builder, &key_blob, &key_characteristics));
756 }
757 }
758}
759
760/*
761 * NewKeyGenerationTest.AesInvalidPadding
762 *
763 * Verifies that specifying an invalid padding on AES keys gives a failure
764 * somewhere along the way.
765 */
766TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
767 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
768 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
769 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
770 SCOPED_TRACE(testing::Message()
771 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000772 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800773 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000774 .AesEncryptionKey(key_size)
775 .BlockMode(block_mode)
776 .Padding(padding_mode)
777 .SetDefaultValidity();
778 if (block_mode == BlockMode::GCM) {
779 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
780 }
781
Tommy Chiu3950b452021-05-03 22:01:46 +0800782 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000783 if (result == ErrorCode::OK) {
784 // Key creation was OK but has generated a key that cannot be used.
785 auto params =
786 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800787 if (block_mode == BlockMode::GCM) {
788 params.Authorization(TAG_MAC_LENGTH, 128);
789 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000790 auto result = Begin(KeyPurpose::ENCRYPT, params);
791 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100792 result == ErrorCode::INVALID_KEY_BLOB)
793 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000794 } else {
795 // The KeyMint implementation detected that the generated key
796 // is unusable.
797 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
798 }
799 }
800 }
801 }
802}
803
804/*
805 * NewKeyGenerationTest.AesGcmMissingMinMac
806 *
807 * Verifies that specifying an invalid key size for AES key generation returns
808 * UNSUPPORTED_KEY_SIZE.
809 */
810TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
811 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
812 BlockMode block_mode = BlockMode::GCM;
813 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
814 SCOPED_TRACE(testing::Message()
815 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
816 vector<uint8_t> key_blob;
817 vector<KeyCharacteristics> key_characteristics;
818 // No MIN_MAC_LENGTH provided.
819 auto builder = AuthorizationSetBuilder()
820 .AesEncryptionKey(key_size)
821 .BlockMode(block_mode)
822 .Padding(padding_mode)
823 .SetDefaultValidity();
824 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
825 GenerateKey(builder, &key_blob, &key_characteristics));
826 }
827 }
828}
829
830/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100831 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
832 *
833 * Verifies that specifying an invalid min MAC size for AES key generation returns
834 * UNSUPPORTED_MIN_MAC_LENGTH.
835 */
836TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
837 for (size_t min_mac_len : {88, 136}) {
838 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
839 BlockMode block_mode = BlockMode::GCM;
840 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
841 SCOPED_TRACE(testing::Message()
842 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
843 vector<uint8_t> key_blob;
844 vector<KeyCharacteristics> key_characteristics;
845 auto builder = AuthorizationSetBuilder()
846 .AesEncryptionKey(key_size)
847 .BlockMode(block_mode)
848 .Padding(padding_mode)
849 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
850 .SetDefaultValidity();
851 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
852 GenerateKey(builder, &key_blob, &key_characteristics));
853 }
854 }
855 }
856}
857
858/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000859 * NewKeyGenerationTest.TripleDes
860 *
861 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
862 * have correct characteristics.
863 */
864TEST_P(NewKeyGenerationTest, TripleDes) {
865 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
866 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
867 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
868 SCOPED_TRACE(testing::Message()
869 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
870 vector<uint8_t> key_blob;
871 vector<KeyCharacteristics> key_characteristics;
872 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
873 .TripleDesEncryptionKey(key_size)
874 .BlockMode(block_mode)
875 .Padding(padding_mode)
876 .Authorization(TAG_NO_AUTH_REQUIRED)
877 .SetDefaultValidity(),
878 &key_blob, &key_characteristics));
879
880 EXPECT_GT(key_blob.size(), 0U);
881 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100882 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000883
884 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
885
886 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
887 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
888 << "Key size " << key_size << "missing";
889
890 CheckedDeleteKey(&key_blob);
891 }
892 }
893 }
894}
895
896/*
897 * NewKeyGenerationTest.TripleDesWithAttestation
898 *
899 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
900 * have correct characteristics.
901 *
902 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
903 * put in a certificate) but which isn't an error.
904 */
905TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
906 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
907 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
908 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
909 SCOPED_TRACE(testing::Message()
910 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
911
912 auto challenge = "hello";
913 auto app_id = "foo";
914
915 vector<uint8_t> key_blob;
916 vector<KeyCharacteristics> key_characteristics;
917 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
918 .TripleDesEncryptionKey(key_size)
919 .BlockMode(block_mode)
920 .Padding(padding_mode)
921 .Authorization(TAG_NO_AUTH_REQUIRED)
922 .AttestationChallenge(challenge)
923 .AttestationApplicationId(app_id)
924 .SetDefaultValidity(),
925 &key_blob, &key_characteristics));
926
927 EXPECT_GT(key_blob.size(), 0U);
928 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100929 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000930
931 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
932
933 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
934 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
935 << "Key size " << key_size << "missing";
936
937 CheckedDeleteKey(&key_blob);
938 }
939 }
940 }
941}
942
943/*
944 * NewKeyGenerationTest.TripleDesInvalidSize
945 *
946 * Verifies that specifying an invalid key size for 3-DES key generation returns
947 * UNSUPPORTED_KEY_SIZE.
948 */
949TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
950 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
951 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
952 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
953 SCOPED_TRACE(testing::Message()
954 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
955 vector<uint8_t> key_blob;
956 vector<KeyCharacteristics> key_characteristics;
957 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
958 GenerateKey(AuthorizationSetBuilder()
959 .TripleDesEncryptionKey(key_size)
960 .BlockMode(block_mode)
961 .Padding(padding_mode)
962 .Authorization(TAG_NO_AUTH_REQUIRED)
963 .SetDefaultValidity(),
964 &key_blob, &key_characteristics));
965 }
966 }
967 }
968
969 // Omitting the key size fails.
970 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
971 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
972 SCOPED_TRACE(testing::Message()
973 << "3DES-default-" << block_mode << "-" << padding_mode);
974 vector<uint8_t> key_blob;
975 vector<KeyCharacteristics> key_characteristics;
976 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
977 GenerateKey(AuthorizationSetBuilder()
978 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
979 .BlockMode(block_mode)
980 .Padding(padding_mode)
981 .Authorization(TAG_NO_AUTH_REQUIRED)
982 .SetDefaultValidity(),
983 &key_blob, &key_characteristics));
984 }
985 }
986}
987
988/*
Selene Huang31ab4042020-04-29 04:22:39 -0700989 * NewKeyGenerationTest.Rsa
990 *
991 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
992 * have correct characteristics.
993 */
994TEST_P(NewKeyGenerationTest, Rsa) {
995 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
996 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700997 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700998 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
999 .RsaSigningKey(key_size, 65537)
1000 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001001 .Padding(PaddingMode::NONE)
1002 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001003 &key_blob, &key_characteristics));
1004
1005 ASSERT_GT(key_blob.size(), 0U);
1006 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001007 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001008
Shawn Willden7f424372021-01-10 18:06:50 -07001009 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001010
1011 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1012 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1013 << "Key size " << key_size << "missing";
1014 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1015
1016 CheckedDeleteKey(&key_blob);
1017 }
1018}
1019
1020/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001021 * NewKeyGenerationTest.RsaWithMissingValidity
1022 *
1023 * Verifies that keymint returns an error while generating asymmetric key
1024 * without providing NOT_BEFORE and NOT_AFTER parameters.
1025 */
1026TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
1027 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1028 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1029 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1030
1031 vector<uint8_t> key_blob;
1032 vector<KeyCharacteristics> key_characteristics;
1033 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1034 GenerateKey(AuthorizationSetBuilder()
1035 .RsaSigningKey(2048, 65537)
1036 .Digest(Digest::NONE)
1037 .Padding(PaddingMode::NONE)
1038 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1039 kUndefinedExpirationDateTime),
1040 &key_blob, &key_characteristics));
1041
1042 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1043 GenerateKey(AuthorizationSetBuilder()
1044 .RsaSigningKey(2048, 65537)
1045 .Digest(Digest::NONE)
1046 .Padding(PaddingMode::NONE)
1047 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1048 &key_blob, &key_characteristics));
1049}
1050
1051/*
Qi Wud22ec842020-11-26 13:27:53 +08001052 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001053 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001054 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1055 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001056 */
1057TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001058 auto challenge = "hello";
1059 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001060
Selene Huang6e46f142021-04-20 19:20:11 -07001061 auto subject = "cert subj 2";
1062 vector<uint8_t> subject_der(make_name_from_str(subject));
1063
1064 uint64_t serial_int = 66;
1065 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1066
Selene Huang4f64c222021-04-13 19:54:36 -07001067 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001068 vector<uint8_t> key_blob;
1069 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman05642492022-02-05 07:10:56 +00001070 auto result = GenerateKey(AuthorizationSetBuilder()
1071 .RsaSigningKey(key_size, 65537)
1072 .Digest(Digest::NONE)
1073 .Padding(PaddingMode::NONE)
1074 .AttestationChallenge(challenge)
1075 .AttestationApplicationId(app_id)
1076 .Authorization(TAG_NO_AUTH_REQUIRED)
1077 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1078 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1079 .SetDefaultValidity(),
1080 &key_blob, &key_characteristics);
1081 // Strongbox may not support factory provisioned attestation key.
1082 if (SecLevel() == SecurityLevel::STRONGBOX) {
1083 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1084 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001085
1086 ASSERT_GT(key_blob.size(), 0U);
1087 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001088 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001089
1090 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1091
1092 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1093 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1094 << "Key size " << key_size << "missing";
1095 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1096
Selene Huang6e46f142021-04-20 19:20:11 -07001097 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001098 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001099 ASSERT_GT(cert_chain_.size(), 0);
1100
1101 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1102 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001103 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001104 sw_enforced, hw_enforced, SecLevel(),
1105 cert_chain_[0].encodedCertificate));
1106
1107 CheckedDeleteKey(&key_blob);
1108 }
1109}
1110
1111/*
David Drysdale4dc01072021-04-01 12:17:35 +01001112 * NewKeyGenerationTest.RsaWithRpkAttestation
1113 *
1114 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
1115 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale0fce69d2021-04-13 17:22:13 +01001116 *
1117 * This test is disabled because the KeyMint specification does not require that implementations
1118 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
1119 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +01001120 */
David Drysdale0fce69d2021-04-13 17:22:13 +01001121TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +01001122 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
1123 // instance.
1124 std::shared_ptr<IRemotelyProvisionedComponent> rp;
1125 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
1126 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
1127
1128 // Generate a P-256 keypair to use as an attestation key.
1129 MacedPublicKey macedPubKey;
1130 std::vector<uint8_t> privateKeyBlob;
1131 auto status =
1132 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1133 ASSERT_TRUE(status.isOk());
1134 vector<uint8_t> coseKeyData;
1135 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1136
1137 AttestationKey attestation_key;
1138 attestation_key.keyBlob = std::move(privateKeyBlob);
1139 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1140
1141 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1142 auto challenge = "hello";
1143 auto app_id = "foo";
1144
1145 vector<uint8_t> key_blob;
1146 vector<KeyCharacteristics> key_characteristics;
1147 ASSERT_EQ(ErrorCode::OK,
1148 GenerateKey(AuthorizationSetBuilder()
1149 .RsaSigningKey(key_size, 65537)
1150 .Digest(Digest::NONE)
1151 .Padding(PaddingMode::NONE)
1152 .AttestationChallenge(challenge)
1153 .AttestationApplicationId(app_id)
1154 .Authorization(TAG_NO_AUTH_REQUIRED)
1155 .SetDefaultValidity(),
1156 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1157
1158 ASSERT_GT(key_blob.size(), 0U);
1159 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001160 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001161
1162 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1163
1164 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1165 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1166 << "Key size " << key_size << "missing";
1167 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1168
1169 // Attestation by itself is not valid (last entry is not self-signed).
1170 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1171
1172 // The signature over the attested key should correspond to the P256 public key.
1173 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1174 ASSERT_TRUE(key_cert.get());
1175 EVP_PKEY_Ptr signing_pubkey;
1176 p256_pub_key(coseKeyData, &signing_pubkey);
1177 ASSERT_TRUE(signing_pubkey.get());
1178
1179 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1180 << "Verification of attested certificate failed "
1181 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1182
1183 CheckedDeleteKey(&key_blob);
1184 }
1185}
1186
1187/*
Selene Huang4f64c222021-04-13 19:54:36 -07001188 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1189 *
1190 * Verifies that keymint attestation for RSA encryption keys with challenge and
1191 * app id is also successful.
1192 */
1193TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1194 auto key_size = 2048;
1195 auto challenge = "hello";
1196 auto app_id = "foo";
1197
Selene Huang6e46f142021-04-20 19:20:11 -07001198 auto subject = "subj 2";
1199 vector<uint8_t> subject_der(make_name_from_str(subject));
1200
1201 uint64_t serial_int = 111166;
1202 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1203
Selene Huang4f64c222021-04-13 19:54:36 -07001204 vector<uint8_t> key_blob;
1205 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman05642492022-02-05 07:10:56 +00001206 auto result = GenerateKey(AuthorizationSetBuilder()
1207 .RsaEncryptionKey(key_size, 65537)
1208 .Padding(PaddingMode::NONE)
1209 .AttestationChallenge(challenge)
1210 .AttestationApplicationId(app_id)
1211 .Authorization(TAG_NO_AUTH_REQUIRED)
1212 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1213 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1214 .SetDefaultValidity(),
1215 &key_blob, &key_characteristics);
1216 // Strongbox may not support factory provisioned attestation key.
1217 if (SecLevel() == SecurityLevel::STRONGBOX) {
1218 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1219 }
1220 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001221
1222 ASSERT_GT(key_blob.size(), 0U);
1223 AuthorizationSet auths;
1224 for (auto& entry : key_characteristics) {
1225 auths.push_back(AuthorizationSet(entry.authorizations));
1226 }
1227
1228 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1229 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1230
1231 // Verify that App data and ROT are NOT included.
1232 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1233 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1234
1235 // Check that some unexpected tags/values are NOT present.
1236 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1237 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1238
1239 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1240
1241 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1242 ASSERT_TRUE(os_ver);
1243 EXPECT_EQ(*os_ver, os_version());
1244
1245 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1246
1247 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1248 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1249 << "Key size " << key_size << "missing";
1250 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1251
Selene Huang6e46f142021-04-20 19:20:11 -07001252 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001253 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1254 ASSERT_GT(cert_chain_.size(), 0);
1255
1256 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1257 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001258 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001259 sw_enforced, hw_enforced, SecLevel(),
1260 cert_chain_[0].encodedCertificate));
1261
1262 CheckedDeleteKey(&key_blob);
1263}
1264
1265/*
1266 * NewKeyGenerationTest.RsaWithSelfSign
1267 *
1268 * Verifies that attesting to RSA key generation is successful, and returns
1269 * self signed certificate if no challenge is provided. And signing etc
1270 * works as expected.
1271 */
1272TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001273 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1274 vector<uint8_t> subject_der(make_name_from_str(subject));
1275
1276 uint64_t serial_int = 0;
1277 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1278
Selene Huang4f64c222021-04-13 19:54:36 -07001279 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1280 vector<uint8_t> key_blob;
1281 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001282 ASSERT_EQ(ErrorCode::OK,
1283 GenerateKey(AuthorizationSetBuilder()
1284 .RsaSigningKey(key_size, 65537)
1285 .Digest(Digest::NONE)
1286 .Padding(PaddingMode::NONE)
1287 .Authorization(TAG_NO_AUTH_REQUIRED)
1288 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1289 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1290 .SetDefaultValidity(),
1291 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001292
1293 ASSERT_GT(key_blob.size(), 0U);
1294 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001295 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001296
1297 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1298
1299 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1300 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1301 << "Key size " << key_size << "missing";
1302 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1303
Selene Huang6e46f142021-04-20 19:20:11 -07001304 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001305 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1306 ASSERT_EQ(cert_chain_.size(), 1);
1307
1308 CheckedDeleteKey(&key_blob);
1309 }
1310}
1311
1312/*
1313 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1314 *
1315 * Verifies that attesting to RSA checks for missing app ID.
1316 */
1317TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1318 auto challenge = "hello";
1319 vector<uint8_t> key_blob;
1320 vector<KeyCharacteristics> key_characteristics;
1321
subrahmanyaman05642492022-02-05 07:10:56 +00001322 auto result = GenerateKey(AuthorizationSetBuilder()
1323 .RsaSigningKey(2048, 65537)
1324 .Digest(Digest::NONE)
1325 .Padding(PaddingMode::NONE)
1326 .AttestationChallenge(challenge)
1327 .Authorization(TAG_NO_AUTH_REQUIRED)
1328 .SetDefaultValidity(),
1329 &key_blob, &key_characteristics);
1330 // Strongbox may not support factory provisioned attestation key.
1331 if (SecLevel() == SecurityLevel::STRONGBOX) {
1332 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1333 }
1334 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001335}
1336
1337/*
1338 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1339 *
1340 * Verifies that attesting to RSA ignores app id if challenge is missing.
1341 */
1342TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1343 auto key_size = 2048;
1344 auto app_id = "foo";
1345
Selene Huang6e46f142021-04-20 19:20:11 -07001346 auto subject = "cert subj 2";
1347 vector<uint8_t> subject_der(make_name_from_str(subject));
1348
1349 uint64_t serial_int = 1;
1350 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1351
Selene Huang4f64c222021-04-13 19:54:36 -07001352 vector<uint8_t> key_blob;
1353 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001354 ASSERT_EQ(ErrorCode::OK,
1355 GenerateKey(AuthorizationSetBuilder()
1356 .RsaSigningKey(key_size, 65537)
1357 .Digest(Digest::NONE)
1358 .Padding(PaddingMode::NONE)
1359 .AttestationApplicationId(app_id)
1360 .Authorization(TAG_NO_AUTH_REQUIRED)
1361 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1362 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1363 .SetDefaultValidity(),
1364 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001365
1366 ASSERT_GT(key_blob.size(), 0U);
1367 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001368 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001369
1370 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1371
1372 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1373 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1374 << "Key size " << key_size << "missing";
1375 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1376
Selene Huang6e46f142021-04-20 19:20:11 -07001377 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001378 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1379 ASSERT_EQ(cert_chain_.size(), 1);
1380
1381 CheckedDeleteKey(&key_blob);
1382}
1383
1384/*
Qi Wud22ec842020-11-26 13:27:53 +08001385 * NewKeyGenerationTest.LimitedUsageRsa
1386 *
1387 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1388 * resulting keys have correct characteristics.
1389 */
1390TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1391 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1392 vector<uint8_t> key_blob;
1393 vector<KeyCharacteristics> key_characteristics;
1394 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1395 .RsaSigningKey(key_size, 65537)
1396 .Digest(Digest::NONE)
1397 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001398 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1399 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001400 &key_blob, &key_characteristics));
1401
1402 ASSERT_GT(key_blob.size(), 0U);
1403 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001404 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001405
1406 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1407
1408 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1409 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1410 << "Key size " << key_size << "missing";
1411 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1412
1413 // Check the usage count limit tag appears in the authorizations.
1414 AuthorizationSet auths;
1415 for (auto& entry : key_characteristics) {
1416 auths.push_back(AuthorizationSet(entry.authorizations));
1417 }
1418 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1419 << "key usage count limit " << 1U << " missing";
1420
1421 CheckedDeleteKey(&key_blob);
1422 }
1423}
1424
1425/*
Qi Wubeefae42021-01-28 23:16:37 +08001426 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1427 *
1428 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1429 * resulting keys have correct characteristics and attestation.
1430 */
1431TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001432 auto challenge = "hello";
1433 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001434
Selene Huang6e46f142021-04-20 19:20:11 -07001435 auto subject = "cert subj 2";
1436 vector<uint8_t> subject_der(make_name_from_str(subject));
1437
1438 uint64_t serial_int = 66;
1439 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1440
Selene Huang4f64c222021-04-13 19:54:36 -07001441 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001442 vector<uint8_t> key_blob;
1443 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman05642492022-02-05 07:10:56 +00001444 auto result = GenerateKey(AuthorizationSetBuilder()
1445 .RsaSigningKey(key_size, 65537)
1446 .Digest(Digest::NONE)
1447 .Padding(PaddingMode::NONE)
1448 .AttestationChallenge(challenge)
1449 .AttestationApplicationId(app_id)
1450 .Authorization(TAG_NO_AUTH_REQUIRED)
1451 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1452 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1453 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1454 .SetDefaultValidity(),
1455 &key_blob, &key_characteristics);
1456 // Strongbox may not support factory provisioned attestation key.
1457 if (SecLevel() == SecurityLevel::STRONGBOX) {
1458 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1459 }
1460 ASSERT_EQ(ErrorCode::OK, result);
Qi Wubeefae42021-01-28 23:16:37 +08001461
1462 ASSERT_GT(key_blob.size(), 0U);
1463 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001464 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001465
1466 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1467
1468 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1469 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1470 << "Key size " << key_size << "missing";
1471 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1472
1473 // Check the usage count limit tag appears in the authorizations.
1474 AuthorizationSet auths;
1475 for (auto& entry : key_characteristics) {
1476 auths.push_back(AuthorizationSet(entry.authorizations));
1477 }
1478 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1479 << "key usage count limit " << 1U << " missing";
1480
1481 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001482 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001483 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001484 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001485
1486 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1487 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001488 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001489 sw_enforced, hw_enforced, SecLevel(),
1490 cert_chain_[0].encodedCertificate));
1491
1492 CheckedDeleteKey(&key_blob);
1493 }
1494}
1495
1496/*
Selene Huang31ab4042020-04-29 04:22:39 -07001497 * NewKeyGenerationTest.NoInvalidRsaSizes
1498 *
1499 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1500 */
1501TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1502 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1503 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001504 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001505 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1506 GenerateKey(AuthorizationSetBuilder()
1507 .RsaSigningKey(key_size, 65537)
1508 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001509 .Padding(PaddingMode::NONE)
1510 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001511 &key_blob, &key_characteristics));
1512 }
1513}
1514
1515/*
1516 * NewKeyGenerationTest.RsaNoDefaultSize
1517 *
1518 * Verifies that failing to specify a key size for RSA key generation returns
1519 * UNSUPPORTED_KEY_SIZE.
1520 */
1521TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1522 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1523 GenerateKey(AuthorizationSetBuilder()
1524 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1525 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001526 .SigningKey()
1527 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001528}
1529
1530/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001531 * NewKeyGenerationTest.RsaMissingParams
1532 *
1533 * Verifies that omitting optional tags works.
1534 */
1535TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1536 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1537 ASSERT_EQ(ErrorCode::OK,
1538 GenerateKey(
1539 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1540 CheckedDeleteKey();
1541 }
1542}
1543
1544/*
Selene Huang31ab4042020-04-29 04:22:39 -07001545 * NewKeyGenerationTest.Ecdsa
1546 *
David Drysdale42fe1892021-10-14 14:43:46 +01001547 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001548 * have correct characteristics.
1549 */
1550TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001551 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001552 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001553 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001554 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001555 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001556 .Digest(Digest::NONE)
1557 .SetDefaultValidity(),
1558 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001559 ASSERT_GT(key_blob.size(), 0U);
1560 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001561 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001562
Shawn Willden7f424372021-01-10 18:06:50 -07001563 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001564
1565 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001566 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001567
1568 CheckedDeleteKey(&key_blob);
1569 }
1570}
1571
1572/*
David Drysdale42fe1892021-10-14 14:43:46 +01001573 * NewKeyGenerationTest.EcdsaCurve25519
1574 *
1575 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1576 * has correct characteristics.
1577 */
1578TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1579 if (!Curve25519Supported()) {
1580 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1581 }
1582
1583 EcCurve curve = EcCurve::CURVE_25519;
1584 vector<uint8_t> key_blob;
1585 vector<KeyCharacteristics> key_characteristics;
1586 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1587 .EcdsaSigningKey(curve)
1588 .Digest(Digest::NONE)
1589 .SetDefaultValidity(),
1590 &key_blob, &key_characteristics);
1591 ASSERT_EQ(result, ErrorCode::OK);
1592 ASSERT_GT(key_blob.size(), 0U);
1593
1594 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1595 ASSERT_GT(cert_chain_.size(), 0);
1596
1597 CheckBaseParams(key_characteristics);
1598 CheckCharacteristics(key_blob, key_characteristics);
1599
1600 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1601
1602 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1603 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1604
1605 CheckedDeleteKey(&key_blob);
1606}
1607
1608/*
1609 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1610 *
1611 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1612 * SIGN and AGREE_KEY.
1613 */
1614TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1615 if (!Curve25519Supported()) {
1616 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1617 }
1618
1619 EcCurve curve = EcCurve::CURVE_25519;
1620 vector<uint8_t> key_blob;
1621 vector<KeyCharacteristics> key_characteristics;
1622 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1623 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1624 .EcdsaSigningKey(curve)
1625 .Digest(Digest::NONE)
1626 .SetDefaultValidity(),
1627 &key_blob, &key_characteristics);
1628 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1629}
1630
1631/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001632 * NewKeyGenerationTest.EcdsaWithMissingValidity
1633 *
1634 * Verifies that keymint returns an error while generating asymmetric key
1635 * without providing NOT_BEFORE and NOT_AFTER parameters.
1636 */
1637TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
1638 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1639 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1640 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1641
1642 vector<uint8_t> key_blob;
1643 vector<KeyCharacteristics> key_characteristics;
1644 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1645 GenerateKey(AuthorizationSetBuilder()
1646 .EcdsaSigningKey(EcCurve::P_256)
1647 .Digest(Digest::NONE)
1648 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1649 kUndefinedExpirationDateTime),
1650 &key_blob, &key_characteristics));
1651
1652 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1653 GenerateKey(AuthorizationSetBuilder()
1654 .EcdsaSigningKey(EcCurve::P_256)
1655 .Digest(Digest::NONE)
1656 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1657 &key_blob, &key_characteristics));
1658}
1659
1660/*
Selene Huang4f64c222021-04-13 19:54:36 -07001661 * NewKeyGenerationTest.EcdsaAttestation
1662 *
1663 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1664 * an attestation will be generated.
1665 */
1666TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1667 auto challenge = "hello";
1668 auto app_id = "foo";
1669
Selene Huang6e46f142021-04-20 19:20:11 -07001670 auto subject = "cert subj 2";
1671 vector<uint8_t> subject_der(make_name_from_str(subject));
1672
1673 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1674 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1675
David Drysdaledf09e542021-06-08 15:46:11 +01001676 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001677 vector<uint8_t> key_blob;
1678 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman05642492022-02-05 07:10:56 +00001679 auto result = GenerateKey(AuthorizationSetBuilder()
1680 .Authorization(TAG_NO_AUTH_REQUIRED)
1681 .EcdsaSigningKey(curve)
1682 .Digest(Digest::NONE)
1683 .AttestationChallenge(challenge)
1684 .AttestationApplicationId(app_id)
1685 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1686 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1687 .SetDefaultValidity(),
1688 &key_blob, &key_characteristics);
1689 // Strongbox may not support factory provisioned attestation key.
1690 if (SecLevel() == SecurityLevel::STRONGBOX) {
1691 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1692 }
1693 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001694 ASSERT_GT(key_blob.size(), 0U);
1695 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001696 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001697
1698 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1699
1700 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001701 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001702
1703 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1704 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001705 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001706
1707 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1708 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001709 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001710 sw_enforced, hw_enforced, SecLevel(),
1711 cert_chain_[0].encodedCertificate));
1712
1713 CheckedDeleteKey(&key_blob);
1714 }
1715}
1716
1717/*
David Drysdale42fe1892021-10-14 14:43:46 +01001718 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1719 *
1720 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1721 * an attestation will be generated.
1722 */
1723TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1724 if (!Curve25519Supported()) {
1725 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1726 }
1727
1728 EcCurve curve = EcCurve::CURVE_25519;
1729 auto challenge = "hello";
1730 auto app_id = "foo";
1731
1732 auto subject = "cert subj 2";
1733 vector<uint8_t> subject_der(make_name_from_str(subject));
1734
1735 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1736 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1737
1738 vector<uint8_t> key_blob;
1739 vector<KeyCharacteristics> key_characteristics;
1740 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1741 .Authorization(TAG_NO_AUTH_REQUIRED)
1742 .EcdsaSigningKey(curve)
1743 .Digest(Digest::NONE)
1744 .AttestationChallenge(challenge)
1745 .AttestationApplicationId(app_id)
1746 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1747 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1748 .SetDefaultValidity(),
1749 &key_blob, &key_characteristics);
1750 ASSERT_EQ(ErrorCode::OK, result);
1751 ASSERT_GT(key_blob.size(), 0U);
1752 CheckBaseParams(key_characteristics);
1753 CheckCharacteristics(key_blob, key_characteristics);
1754
1755 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1756
1757 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1758 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1759
1760 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1761 ASSERT_GT(cert_chain_.size(), 0);
1762 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1763
1764 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1765 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1766 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1767 sw_enforced, hw_enforced, SecLevel(),
1768 cert_chain_[0].encodedCertificate));
1769
1770 CheckedDeleteKey(&key_blob);
1771}
1772
1773/*
David Drysdale37af4b32021-05-14 16:46:59 +01001774 * NewKeyGenerationTest.EcdsaAttestationTags
1775 *
1776 * Verifies that creation of an attested ECDSA key includes various tags in the
1777 * attestation extension.
1778 */
1779TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1780 auto challenge = "hello";
1781 auto app_id = "foo";
1782 auto subject = "cert subj 2";
1783 vector<uint8_t> subject_der(make_name_from_str(subject));
1784 uint64_t serial_int = 0x1010;
1785 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1786 const AuthorizationSetBuilder base_builder =
1787 AuthorizationSetBuilder()
1788 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001789 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001790 .Digest(Digest::NONE)
1791 .AttestationChallenge(challenge)
1792 .AttestationApplicationId(app_id)
1793 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1794 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1795 .SetDefaultValidity();
1796
1797 // Various tags that map to fields in the attestation extension ASN.1 schema.
1798 auto extra_tags = AuthorizationSetBuilder()
1799 .Authorization(TAG_ROLLBACK_RESISTANCE)
1800 .Authorization(TAG_EARLY_BOOT_ONLY)
1801 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1802 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1803 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1804 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1805 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1806 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1807 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1808 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1809 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1810 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001811
David Drysdale37af4b32021-05-14 16:46:59 +01001812 for (const KeyParameter& tag : extra_tags) {
1813 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1814 vector<uint8_t> key_blob;
1815 vector<KeyCharacteristics> key_characteristics;
1816 AuthorizationSetBuilder builder = base_builder;
1817 builder.push_back(tag);
1818 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1819 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1820 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1821 continue;
1822 }
Seth Mooreb393b082021-07-12 14:18:28 -07001823 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1824 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001825 continue;
1826 }
subrahmanyaman05642492022-02-05 07:10:56 +00001827 // Strongbox may not support factory provisioned attestation key.
1828 if (SecLevel() == SecurityLevel::STRONGBOX) {
1829 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1830 }
David Drysdale37af4b32021-05-14 16:46:59 +01001831 ASSERT_EQ(result, ErrorCode::OK);
1832 ASSERT_GT(key_blob.size(), 0U);
1833
1834 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1835 ASSERT_GT(cert_chain_.size(), 0);
1836 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1837
1838 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1839 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001840 // Some tags are optional, so don't require them to be in the enforcements.
1841 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001842 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1843 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1844 }
1845
1846 // Verifying the attestation record will check for the specific tag because
1847 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001848 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1849 hw_enforced, SecLevel(),
1850 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01001851
1852 CheckedDeleteKey(&key_blob);
1853 }
1854
David Drysdalec53b7d92021-10-11 12:35:58 +01001855 // Collection of invalid attestation ID tags.
1856 auto invalid_tags =
1857 AuthorizationSetBuilder()
1858 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1859 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1860 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1861 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1862 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
1863 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
1864 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
1865 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01001866 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01001867 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01001868 vector<uint8_t> key_blob;
1869 vector<KeyCharacteristics> key_characteristics;
1870 AuthorizationSetBuilder builder =
1871 AuthorizationSetBuilder()
1872 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001873 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001874 .Digest(Digest::NONE)
1875 .AttestationChallenge(challenge)
1876 .AttestationApplicationId(app_id)
1877 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1878 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1879 .SetDefaultValidity();
1880 builder.push_back(tag);
1881 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1882 GenerateKey(builder, &key_blob, &key_characteristics));
1883 }
1884}
1885
1886/*
David Drysdalec53b7d92021-10-11 12:35:58 +01001887 * NewKeyGenerationTest.EcdsaAttestationIdTags
1888 *
1889 * Verifies that creation of an attested ECDSA key includes various ID tags in the
1890 * attestation extension.
1891 */
1892TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
1893 auto challenge = "hello";
1894 auto app_id = "foo";
1895 auto subject = "cert subj 2";
1896 vector<uint8_t> subject_der(make_name_from_str(subject));
1897 uint64_t serial_int = 0x1010;
1898 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1899 const AuthorizationSetBuilder base_builder =
1900 AuthorizationSetBuilder()
1901 .Authorization(TAG_NO_AUTH_REQUIRED)
1902 .EcdsaSigningKey(EcCurve::P_256)
1903 .Digest(Digest::NONE)
1904 .AttestationChallenge(challenge)
1905 .AttestationApplicationId(app_id)
1906 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1907 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1908 .SetDefaultValidity();
1909
1910 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
1911 auto extra_tags = AuthorizationSetBuilder();
1912 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
1913 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
1914 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
1915 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
1916 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
1917 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
1918
1919 for (const KeyParameter& tag : extra_tags) {
1920 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1921 vector<uint8_t> key_blob;
1922 vector<KeyCharacteristics> key_characteristics;
1923 AuthorizationSetBuilder builder = base_builder;
1924 builder.push_back(tag);
1925 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001926 // Strongbox may not support factory provisioned attestation key.
1927 if (SecLevel() == SecurityLevel::STRONGBOX) {
1928 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1929 }
David Drysdalec53b7d92021-10-11 12:35:58 +01001930 if (result == ErrorCode::CANNOT_ATTEST_IDS) {
1931 // Device ID attestation is optional; KeyMint may not support it at all.
1932 continue;
1933 }
1934 ASSERT_EQ(result, ErrorCode::OK);
1935 ASSERT_GT(key_blob.size(), 0U);
1936
1937 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1938 ASSERT_GT(cert_chain_.size(), 0);
1939 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1940
1941 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1942 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1943
1944 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
1945 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
1946 // attestation extension should contain them, so make sure the extra tag is added.
1947 hw_enforced.push_back(tag);
1948
1949 // Verifying the attestation record will check for the specific tag because
1950 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001951 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1952 hw_enforced, SecLevel(),
1953 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01001954
1955 CheckedDeleteKey(&key_blob);
1956 }
1957}
1958
1959/*
David Drysdale565ccc72021-10-11 12:49:50 +01001960 * NewKeyGenerationTest.EcdsaAttestationUniqueId
1961 *
1962 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
1963 */
1964TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
1965 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00001966 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01001967 auto challenge = "hello";
1968 auto subject = "cert subj 2";
1969 vector<uint8_t> subject_der(make_name_from_str(subject));
1970 uint64_t serial_int = 0x1010;
1971 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00001972 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01001973 AuthorizationSetBuilder()
1974 .Authorization(TAG_NO_AUTH_REQUIRED)
1975 .Authorization(TAG_INCLUDE_UNIQUE_ID)
1976 .EcdsaSigningKey(EcCurve::P_256)
1977 .Digest(Digest::NONE)
1978 .AttestationChallenge(challenge)
1979 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1980 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1981 .AttestationApplicationId(app_id)
1982 .Authorization(TAG_CREATION_DATETIME, datetime)
1983 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00001984 if (reset) {
1985 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
1986 }
David Drysdale565ccc72021-10-11 12:49:50 +01001987
1988 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
1989 ASSERT_GT(key_blob_.size(), 0U);
1990
1991 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1992 ASSERT_GT(cert_chain_.size(), 0);
1993 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1994
1995 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
1996 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
1997
1998 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001999 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2000 hw_enforced, SecLevel(),
2001 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002002 EXPECT_GT(unique_id->size(), 0);
2003 CheckedDeleteKey();
2004 };
2005
2006 // Generate unique ID
2007 auto app_id = "foo";
2008 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2009 vector<uint8_t> unique_id;
2010 get_unique_id(app_id, cert_date, &unique_id);
2011
2012 // Generating a new key with the same parameters should give the same unique ID.
2013 vector<uint8_t> unique_id2;
2014 get_unique_id(app_id, cert_date, &unique_id2);
2015 EXPECT_EQ(unique_id, unique_id2);
2016
2017 // Generating a new key with a slightly different date should give the same unique ID.
2018 uint64_t rounded_date = cert_date / 2592000000LLU;
2019 uint64_t min_date = rounded_date * 2592000000LLU;
2020 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2021
2022 vector<uint8_t> unique_id3;
2023 get_unique_id(app_id, min_date, &unique_id3);
2024 EXPECT_EQ(unique_id, unique_id3);
2025
2026 vector<uint8_t> unique_id4;
2027 get_unique_id(app_id, max_date, &unique_id4);
2028 EXPECT_EQ(unique_id, unique_id4);
2029
2030 // A different attestation application ID should yield a different unique ID.
2031 auto app_id2 = "different_foo";
2032 vector<uint8_t> unique_id5;
2033 get_unique_id(app_id2, cert_date, &unique_id5);
2034 EXPECT_NE(unique_id, unique_id5);
2035
2036 // A radically different date should yield a different unique ID.
2037 vector<uint8_t> unique_id6;
2038 get_unique_id(app_id, 1611621648000, &unique_id6);
2039 EXPECT_NE(unique_id, unique_id6);
2040
2041 vector<uint8_t> unique_id7;
2042 get_unique_id(app_id, max_date + 1, &unique_id7);
2043 EXPECT_NE(unique_id, unique_id7);
2044
2045 vector<uint8_t> unique_id8;
2046 get_unique_id(app_id, min_date - 1, &unique_id8);
2047 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002048
2049 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2050 vector<uint8_t> unique_id9;
2051 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2052 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002053}
2054
2055/*
David Drysdale37af4b32021-05-14 16:46:59 +01002056 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2057 *
2058 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2059 */
2060TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2061 auto challenge = "hello";
2062 auto attest_app_id = "foo";
2063 auto subject = "cert subj 2";
2064 vector<uint8_t> subject_der(make_name_from_str(subject));
2065 uint64_t serial_int = 0x1010;
2066 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2067
2068 // Earlier versions of the attestation extension schema included a slot:
2069 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2070 // This should never have been included, and should never be filled in.
2071 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2072 // to confirm that this field never makes it into the attestation extension.
2073 vector<uint8_t> key_blob;
2074 vector<KeyCharacteristics> key_characteristics;
2075 auto result = GenerateKey(AuthorizationSetBuilder()
2076 .Authorization(TAG_NO_AUTH_REQUIRED)
2077 .EcdsaSigningKey(EcCurve::P_256)
2078 .Digest(Digest::NONE)
2079 .AttestationChallenge(challenge)
2080 .AttestationApplicationId(attest_app_id)
2081 .Authorization(TAG_APPLICATION_ID, "client_id")
2082 .Authorization(TAG_APPLICATION_DATA, "appdata")
2083 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2084 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2085 .SetDefaultValidity(),
2086 &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002087 // Strongbox may not support factory provisioned attestation key.
2088 if (SecLevel() == SecurityLevel::STRONGBOX) {
2089 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2090 }
David Drysdale37af4b32021-05-14 16:46:59 +01002091 ASSERT_EQ(result, ErrorCode::OK);
2092 ASSERT_GT(key_blob.size(), 0U);
2093
2094 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2095 ASSERT_GT(cert_chain_.size(), 0);
2096 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2097
2098 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2099 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002100 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2101 hw_enforced, SecLevel(),
2102 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002103
2104 // Check that the app id is not in the cert.
2105 string app_id = "clientid";
2106 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2107 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2108 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2109 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2110 cert_chain_[0].encodedCertificate.end());
2111
2112 CheckedDeleteKey(&key_blob);
2113}
2114
2115/*
Selene Huang4f64c222021-04-13 19:54:36 -07002116 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2117 *
2118 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2119 * the key will generate a self signed attestation.
2120 */
2121TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002122 auto subject = "cert subj 2";
2123 vector<uint8_t> subject_der(make_name_from_str(subject));
2124
2125 uint64_t serial_int = 0x123456FFF1234;
2126 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2127
David Drysdaledf09e542021-06-08 15:46:11 +01002128 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002129 vector<uint8_t> key_blob;
2130 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002131 ASSERT_EQ(ErrorCode::OK,
2132 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002133 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002134 .Digest(Digest::NONE)
2135 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2136 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2137 .SetDefaultValidity(),
2138 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002139 ASSERT_GT(key_blob.size(), 0U);
2140 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002141 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002142
2143 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2144
2145 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002146 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002147
2148 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07002149 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002150 ASSERT_EQ(cert_chain_.size(), 1);
2151
2152 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2153 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2154
2155 CheckedDeleteKey(&key_blob);
2156 }
2157}
2158
2159/*
2160 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2161 *
2162 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2163 * app id must also be provided or else it will fail.
2164 */
2165TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2166 auto challenge = "hello";
2167 vector<uint8_t> key_blob;
2168 vector<KeyCharacteristics> key_characteristics;
2169
subrahmanyaman05642492022-02-05 07:10:56 +00002170 auto result = GenerateKey(AuthorizationSetBuilder()
2171 .EcdsaSigningKey(EcCurve::P_256)
2172 .Digest(Digest::NONE)
2173 .AttestationChallenge(challenge)
2174 .SetDefaultValidity(),
2175 &key_blob, &key_characteristics);
2176 // Strongbox may not support factory provisioned attestation key.
2177 if (SecLevel() == SecurityLevel::STRONGBOX) {
2178 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2179 }
2180 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002181}
2182
2183/*
2184 * NewKeyGenerationTest.EcdsaIgnoreAppId
2185 *
2186 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2187 * any appid will be ignored, and keymint will generate a self sign certificate.
2188 */
2189TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2190 auto app_id = "foo";
2191
David Drysdaledf09e542021-06-08 15:46:11 +01002192 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002193 vector<uint8_t> key_blob;
2194 vector<KeyCharacteristics> key_characteristics;
2195 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002196 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002197 .Digest(Digest::NONE)
2198 .AttestationApplicationId(app_id)
2199 .SetDefaultValidity(),
2200 &key_blob, &key_characteristics));
2201
2202 ASSERT_GT(key_blob.size(), 0U);
2203 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002204 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002205
2206 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2207
2208 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002209 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002210
2211 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2212 ASSERT_EQ(cert_chain_.size(), 1);
2213
2214 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2215 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2216
2217 CheckedDeleteKey(&key_blob);
2218 }
2219}
2220
2221/*
2222 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2223 *
2224 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2225 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2226 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2227 * to specify how many following bytes will be used to encode the length.
2228 */
2229TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2230 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002231 std::vector<uint32_t> app_id_lengths{143, 258};
2232
2233 for (uint32_t length : app_id_lengths) {
2234 const string app_id(length, 'a');
2235 vector<uint8_t> key_blob;
2236 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman05642492022-02-05 07:10:56 +00002237 auto result = GenerateKey(AuthorizationSetBuilder()
2238 .Authorization(TAG_NO_AUTH_REQUIRED)
2239 .EcdsaSigningKey(EcCurve::P_256)
2240 .Digest(Digest::NONE)
2241 .AttestationChallenge(challenge)
2242 .AttestationApplicationId(app_id)
2243 .SetDefaultValidity(),
2244 &key_blob, &key_characteristics);
2245 // Strongbox may not support factory provisioned attestation key.
2246 if (SecLevel() == SecurityLevel::STRONGBOX) {
2247 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2248 }
2249 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002250 ASSERT_GT(key_blob.size(), 0U);
2251 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002252 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002253
2254 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2255
2256 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002257 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002258
2259 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2260 ASSERT_GT(cert_chain_.size(), 0);
2261
2262 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2263 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002264 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002265 sw_enforced, hw_enforced, SecLevel(),
2266 cert_chain_[0].encodedCertificate));
2267
2268 CheckedDeleteKey(&key_blob);
2269 }
2270}
2271
2272/*
Qi Wud22ec842020-11-26 13:27:53 +08002273 * NewKeyGenerationTest.LimitedUsageEcdsa
2274 *
2275 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2276 * resulting keys have correct characteristics.
2277 */
2278TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002279 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08002280 vector<uint8_t> key_blob;
2281 vector<KeyCharacteristics> key_characteristics;
2282 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002283 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002284 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002285 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2286 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002287 &key_blob, &key_characteristics));
2288
2289 ASSERT_GT(key_blob.size(), 0U);
2290 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002291 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002292
2293 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2294
2295 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002296 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002297
2298 // Check the usage count limit tag appears in the authorizations.
2299 AuthorizationSet auths;
2300 for (auto& entry : key_characteristics) {
2301 auths.push_back(AuthorizationSet(entry.authorizations));
2302 }
2303 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2304 << "key usage count limit " << 1U << " missing";
2305
2306 CheckedDeleteKey(&key_blob);
2307 }
2308}
2309
2310/*
Selene Huang31ab4042020-04-29 04:22:39 -07002311 * NewKeyGenerationTest.EcdsaDefaultSize
2312 *
David Drysdaledf09e542021-06-08 15:46:11 +01002313 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002314 * UNSUPPORTED_KEY_SIZE.
2315 */
2316TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2317 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2318 GenerateKey(AuthorizationSetBuilder()
2319 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2320 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002321 .Digest(Digest::NONE)
2322 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002323}
2324
2325/*
David Drysdale42fe1892021-10-14 14:43:46 +01002326 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002327 *
David Drysdale42fe1892021-10-14 14:43:46 +01002328 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002329 * UNSUPPORTED_KEY_SIZE.
2330 */
David Drysdale42fe1892021-10-14 14:43:46 +01002331TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002332 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07002333 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002334 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002335 auto result = GenerateKey(AuthorizationSetBuilder()
2336 .EcdsaSigningKey(curve)
2337 .Digest(Digest::NONE)
2338 .SetDefaultValidity(),
2339 &key_blob, &key_characteristics);
2340 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2341 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002342 }
2343
David Drysdaledf09e542021-06-08 15:46:11 +01002344 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2345 GenerateKey(AuthorizationSetBuilder()
2346 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2347 .Authorization(TAG_KEY_SIZE, 190)
2348 .SigningKey()
2349 .Digest(Digest::NONE)
2350 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002351}
2352
2353/*
2354 * NewKeyGenerationTest.EcdsaMismatchKeySize
2355 *
2356 * Verifies that specifying mismatched key size and curve for EC key generation returns
2357 * INVALID_ARGUMENT.
2358 */
2359TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002360 if (SecLevel() == SecurityLevel::STRONGBOX) {
2361 GTEST_SKIP() << "Test not applicable to StrongBox device";
2362 }
Selene Huang31ab4042020-04-29 04:22:39 -07002363
David Drysdaledf09e542021-06-08 15:46:11 +01002364 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002365 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002366 .Authorization(TAG_KEY_SIZE, 224)
2367 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002368 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002369 .Digest(Digest::NONE)
2370 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002371 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002372}
2373
2374/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002375 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002376 *
2377 * Verifies that keymint does not support any curve designated as unsupported.
2378 */
2379TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2380 Digest digest;
2381 if (SecLevel() == SecurityLevel::STRONGBOX) {
2382 digest = Digest::SHA_2_256;
2383 } else {
2384 digest = Digest::SHA_2_512;
2385 }
2386 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08002387 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2388 .EcdsaSigningKey(curve)
2389 .Digest(digest)
2390 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002391 << "Failed to generate key on curve: " << curve;
2392 CheckedDeleteKey();
2393 }
2394}
2395
2396/*
2397 * NewKeyGenerationTest.Hmac
2398 *
2399 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2400 * characteristics.
2401 */
2402TEST_P(NewKeyGenerationTest, Hmac) {
2403 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2404 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002405 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002406 constexpr size_t key_size = 128;
2407 ASSERT_EQ(ErrorCode::OK,
2408 GenerateKey(
2409 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2410 TAG_MIN_MAC_LENGTH, 128),
2411 &key_blob, &key_characteristics));
2412
2413 ASSERT_GT(key_blob.size(), 0U);
2414 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002415 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002416
Shawn Willden7f424372021-01-10 18:06:50 -07002417 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2418 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2419 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2420 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002421
2422 CheckedDeleteKey(&key_blob);
2423 }
2424}
2425
2426/*
Selene Huang4f64c222021-04-13 19:54:36 -07002427 * NewKeyGenerationTest.HmacNoAttestation
2428 *
2429 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2430 * and app id are provided.
2431 */
2432TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2433 auto challenge = "hello";
2434 auto app_id = "foo";
2435
2436 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2437 vector<uint8_t> key_blob;
2438 vector<KeyCharacteristics> key_characteristics;
2439 constexpr size_t key_size = 128;
2440 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2441 .HmacKey(key_size)
2442 .Digest(digest)
2443 .AttestationChallenge(challenge)
2444 .AttestationApplicationId(app_id)
2445 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2446 &key_blob, &key_characteristics));
2447
2448 ASSERT_GT(key_blob.size(), 0U);
2449 ASSERT_EQ(cert_chain_.size(), 0);
2450 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002451 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002452
2453 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2454 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2455 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2456 << "Key size " << key_size << "missing";
2457
2458 CheckedDeleteKey(&key_blob);
2459 }
2460}
2461
2462/*
Qi Wud22ec842020-11-26 13:27:53 +08002463 * NewKeyGenerationTest.LimitedUsageHmac
2464 *
2465 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2466 * resulting keys have correct characteristics.
2467 */
2468TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2469 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2470 vector<uint8_t> key_blob;
2471 vector<KeyCharacteristics> key_characteristics;
2472 constexpr size_t key_size = 128;
2473 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2474 .HmacKey(key_size)
2475 .Digest(digest)
2476 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2477 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2478 &key_blob, &key_characteristics));
2479
2480 ASSERT_GT(key_blob.size(), 0U);
2481 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002482 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002483
2484 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2485 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2486 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2487 << "Key size " << key_size << "missing";
2488
2489 // Check the usage count limit tag appears in the authorizations.
2490 AuthorizationSet auths;
2491 for (auto& entry : key_characteristics) {
2492 auths.push_back(AuthorizationSet(entry.authorizations));
2493 }
2494 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2495 << "key usage count limit " << 1U << " missing";
2496
2497 CheckedDeleteKey(&key_blob);
2498 }
2499}
2500
2501/*
Selene Huang31ab4042020-04-29 04:22:39 -07002502 * NewKeyGenerationTest.HmacCheckKeySizes
2503 *
2504 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2505 */
2506TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2507 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2508 if (key_size < 64 || key_size % 8 != 0) {
2509 // To keep this test from being very slow, we only test a random fraction of
2510 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2511 // them, we expect to run ~40 of them in each run.
2512 if (key_size % 8 == 0 || random() % 10 == 0) {
2513 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2514 GenerateKey(AuthorizationSetBuilder()
2515 .HmacKey(key_size)
2516 .Digest(Digest::SHA_2_256)
2517 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2518 << "HMAC key size " << key_size << " invalid";
2519 }
2520 } else {
2521 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2522 .HmacKey(key_size)
2523 .Digest(Digest::SHA_2_256)
2524 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2525 << "Failed to generate HMAC key of size " << key_size;
2526 CheckedDeleteKey();
2527 }
2528 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002529 if (SecLevel() == SecurityLevel::STRONGBOX) {
2530 // STRONGBOX devices must not support keys larger than 512 bits.
2531 size_t key_size = 520;
2532 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2533 GenerateKey(AuthorizationSetBuilder()
2534 .HmacKey(key_size)
2535 .Digest(Digest::SHA_2_256)
2536 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2537 << "HMAC key size " << key_size << " unexpectedly valid";
2538 }
Selene Huang31ab4042020-04-29 04:22:39 -07002539}
2540
2541/*
2542 * NewKeyGenerationTest.HmacCheckMinMacLengths
2543 *
2544 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2545 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2546 * specific MAC length that failed, so reproducing a failed run will be easy.
2547 */
2548TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2549 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2550 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2551 // To keep this test from being very long, we only test a random fraction of
2552 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2553 // we expect to run ~17 of them in each run.
2554 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2555 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2556 GenerateKey(AuthorizationSetBuilder()
2557 .HmacKey(128)
2558 .Digest(Digest::SHA_2_256)
2559 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2560 << "HMAC min mac length " << min_mac_length << " invalid.";
2561 }
2562 } else {
2563 EXPECT_EQ(ErrorCode::OK,
2564 GenerateKey(AuthorizationSetBuilder()
2565 .HmacKey(128)
2566 .Digest(Digest::SHA_2_256)
2567 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2568 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2569 CheckedDeleteKey();
2570 }
2571 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002572
2573 // Minimum MAC length must be no more than 512 bits.
2574 size_t min_mac_length = 520;
2575 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2576 GenerateKey(AuthorizationSetBuilder()
2577 .HmacKey(128)
2578 .Digest(Digest::SHA_2_256)
2579 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2580 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002581}
2582
2583/*
2584 * NewKeyGenerationTest.HmacMultipleDigests
2585 *
2586 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2587 */
2588TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002589 if (SecLevel() == SecurityLevel::STRONGBOX) {
2590 GTEST_SKIP() << "Test not applicable to StrongBox device";
2591 }
Selene Huang31ab4042020-04-29 04:22:39 -07002592
2593 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2594 GenerateKey(AuthorizationSetBuilder()
2595 .HmacKey(128)
2596 .Digest(Digest::SHA1)
2597 .Digest(Digest::SHA_2_256)
2598 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2599}
2600
2601/*
2602 * NewKeyGenerationTest.HmacDigestNone
2603 *
2604 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2605 */
2606TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2607 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2608 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2609 128)));
2610
2611 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2612 GenerateKey(AuthorizationSetBuilder()
2613 .HmacKey(128)
2614 .Digest(Digest::NONE)
2615 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2616}
2617
Selene Huang4f64c222021-04-13 19:54:36 -07002618/*
2619 * NewKeyGenerationTest.AesNoAttestation
2620 *
2621 * Verifies that attestation parameters to AES keys are ignored and generateKey
2622 * will succeed.
2623 */
2624TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2625 auto challenge = "hello";
2626 auto app_id = "foo";
2627
2628 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2629 .Authorization(TAG_NO_AUTH_REQUIRED)
2630 .AesEncryptionKey(128)
2631 .EcbMode()
2632 .Padding(PaddingMode::PKCS7)
2633 .AttestationChallenge(challenge)
2634 .AttestationApplicationId(app_id)));
2635
2636 ASSERT_EQ(cert_chain_.size(), 0);
2637}
2638
2639/*
2640 * NewKeyGenerationTest.TripleDesNoAttestation
2641 *
2642 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2643 * will be successful. No attestation should be generated.
2644 */
2645TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2646 auto challenge = "hello";
2647 auto app_id = "foo";
2648
2649 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2650 .TripleDesEncryptionKey(168)
2651 .BlockMode(BlockMode::ECB)
2652 .Authorization(TAG_NO_AUTH_REQUIRED)
2653 .Padding(PaddingMode::NONE)
2654 .AttestationChallenge(challenge)
2655 .AttestationApplicationId(app_id)));
2656 ASSERT_EQ(cert_chain_.size(), 0);
2657}
2658
Selene Huang31ab4042020-04-29 04:22:39 -07002659INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2660
2661typedef KeyMintAidlTestBase SigningOperationsTest;
2662
2663/*
2664 * SigningOperationsTest.RsaSuccess
2665 *
2666 * Verifies that raw RSA signature operations succeed.
2667 */
2668TEST_P(SigningOperationsTest, RsaSuccess) {
2669 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2670 .RsaSigningKey(2048, 65537)
2671 .Digest(Digest::NONE)
2672 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002673 .Authorization(TAG_NO_AUTH_REQUIRED)
2674 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002675 string message = "12345678901234567890123456789012";
2676 string signature = SignMessage(
2677 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002678 LocalVerifyMessage(message, signature,
2679 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2680}
2681
2682/*
2683 * SigningOperationsTest.RsaAllPaddingsAndDigests
2684 *
2685 * Verifies RSA signature/verification for all padding modes and digests.
2686 */
2687TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2688 auto authorizations = AuthorizationSetBuilder()
2689 .Authorization(TAG_NO_AUTH_REQUIRED)
2690 .RsaSigningKey(2048, 65537)
2691 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2692 .Padding(PaddingMode::NONE)
2693 .Padding(PaddingMode::RSA_PSS)
2694 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2695 .SetDefaultValidity();
2696
2697 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2698
2699 string message(128, 'a');
2700 string corrupt_message(message);
2701 ++corrupt_message[corrupt_message.size() / 2];
2702
2703 for (auto padding :
2704 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2705 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2706 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2707 // Digesting only makes sense with padding.
2708 continue;
2709 }
2710
2711 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2712 // PSS requires digesting.
2713 continue;
2714 }
2715
2716 string signature =
2717 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2718 LocalVerifyMessage(message, signature,
2719 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2720 }
2721 }
Selene Huang31ab4042020-04-29 04:22:39 -07002722}
2723
2724/*
2725 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2726 *
Shawn Willden7f424372021-01-10 18:06:50 -07002727 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002728 */
2729TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2730 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2731 .Authorization(TAG_NO_AUTH_REQUIRED)
2732 .RsaSigningKey(2048, 65537)
2733 .Digest(Digest::NONE)
2734 .Padding(PaddingMode::NONE)
2735 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002736 .Authorization(TAG_APPLICATION_DATA, "appdata")
2737 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002738
2739 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2740
Selene Huang31ab4042020-04-29 04:22:39 -07002741 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2742 Begin(KeyPurpose::SIGN,
2743 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2744 AbortIfNeeded();
2745 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2746 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2747 .Digest(Digest::NONE)
2748 .Padding(PaddingMode::NONE)
2749 .Authorization(TAG_APPLICATION_ID, "clientid")));
2750 AbortIfNeeded();
2751 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2752 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2753 .Digest(Digest::NONE)
2754 .Padding(PaddingMode::NONE)
2755 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2756 AbortIfNeeded();
2757 EXPECT_EQ(ErrorCode::OK,
2758 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2759 .Digest(Digest::NONE)
2760 .Padding(PaddingMode::NONE)
2761 .Authorization(TAG_APPLICATION_DATA, "appdata")
2762 .Authorization(TAG_APPLICATION_ID, "clientid")));
2763 AbortIfNeeded();
2764}
2765
2766/*
2767 * SigningOperationsTest.RsaPssSha256Success
2768 *
2769 * Verifies that RSA-PSS signature operations succeed.
2770 */
2771TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2772 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2773 .RsaSigningKey(2048, 65537)
2774 .Digest(Digest::SHA_2_256)
2775 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002776 .Authorization(TAG_NO_AUTH_REQUIRED)
2777 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002778 // Use large message, which won't work without digesting.
2779 string message(1024, 'a');
2780 string signature = SignMessage(
2781 message,
2782 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2783}
2784
2785/*
2786 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2787 *
2788 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2789 * supports only unpadded operations.
2790 */
2791TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2792 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2793 .RsaSigningKey(2048, 65537)
2794 .Digest(Digest::NONE)
2795 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002796 .Padding(PaddingMode::NONE)
2797 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002798 string message = "12345678901234567890123456789012";
2799 string signature;
2800
2801 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2802 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2803 .Digest(Digest::NONE)
2804 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2805}
2806
2807/*
2808 * SigningOperationsTest.NoUserConfirmation
2809 *
2810 * Verifies that keymint rejects signing operations for keys with
2811 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2812 * presented.
2813 */
2814TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002815 if (SecLevel() == SecurityLevel::STRONGBOX) {
2816 GTEST_SKIP() << "Test not applicable to StrongBox device";
2817 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002818 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2819 .RsaSigningKey(1024, 65537)
2820 .Digest(Digest::NONE)
2821 .Padding(PaddingMode::NONE)
2822 .Authorization(TAG_NO_AUTH_REQUIRED)
2823 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2824 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002825
2826 const string message = "12345678901234567890123456789012";
2827 EXPECT_EQ(ErrorCode::OK,
2828 Begin(KeyPurpose::SIGN,
2829 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2830 string signature;
2831 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2832}
2833
2834/*
2835 * SigningOperationsTest.RsaPkcs1Sha256Success
2836 *
2837 * Verifies that digested RSA-PKCS1 signature operations succeed.
2838 */
2839TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2840 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2841 .RsaSigningKey(2048, 65537)
2842 .Digest(Digest::SHA_2_256)
2843 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002844 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2845 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002846 string message(1024, 'a');
2847 string signature = SignMessage(message, AuthorizationSetBuilder()
2848 .Digest(Digest::SHA_2_256)
2849 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2850}
2851
2852/*
2853 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2854 *
2855 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2856 */
2857TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2858 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2859 .RsaSigningKey(2048, 65537)
2860 .Digest(Digest::NONE)
2861 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002862 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2863 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002864 string message(53, 'a');
2865 string signature = SignMessage(message, AuthorizationSetBuilder()
2866 .Digest(Digest::NONE)
2867 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2868}
2869
2870/*
2871 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2872 *
2873 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2874 * given a too-long message.
2875 */
2876TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2877 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2878 .RsaSigningKey(2048, 65537)
2879 .Digest(Digest::NONE)
2880 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002881 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2882 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002883 string message(257, 'a');
2884
2885 EXPECT_EQ(ErrorCode::OK,
2886 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2887 .Digest(Digest::NONE)
2888 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2889 string signature;
2890 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2891}
2892
2893/*
2894 * SigningOperationsTest.RsaPssSha512TooSmallKey
2895 *
2896 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2897 * used with a key that is too small for the message.
2898 *
2899 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2900 * keymint specification requires that salt_size == digest_size, so the message will be
2901 * digest_size * 2 +
2902 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2903 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2904 * for a 1024-bit key.
2905 */
2906TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01002907 if (SecLevel() == SecurityLevel::STRONGBOX) {
2908 GTEST_SKIP() << "Test not applicable to StrongBox device";
2909 }
Selene Huang31ab4042020-04-29 04:22:39 -07002910 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2911 .RsaSigningKey(1024, 65537)
2912 .Digest(Digest::SHA_2_512)
2913 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002914 .Padding(PaddingMode::RSA_PSS)
2915 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002916 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2917 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2918 .Digest(Digest::SHA_2_512)
2919 .Padding(PaddingMode::RSA_PSS)));
2920}
2921
2922/*
2923 * SigningOperationsTest.RsaNoPaddingTooLong
2924 *
2925 * Verifies that raw RSA signature operations fail with the correct error code when
2926 * given a too-long message.
2927 */
2928TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2929 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2930 .RsaSigningKey(2048, 65537)
2931 .Digest(Digest::NONE)
2932 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002933 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2934 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002935 // One byte too long
2936 string message(2048 / 8 + 1, 'a');
2937 ASSERT_EQ(ErrorCode::OK,
2938 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2939 .Digest(Digest::NONE)
2940 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2941 string result;
2942 ErrorCode finish_error_code = Finish(message, &result);
2943 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2944 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2945
2946 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2947 message = string(128 * 1024, 'a');
2948 ASSERT_EQ(ErrorCode::OK,
2949 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2950 .Digest(Digest::NONE)
2951 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2952 finish_error_code = Finish(message, &result);
2953 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2954 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2955}
2956
2957/*
2958 * SigningOperationsTest.RsaAbort
2959 *
2960 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2961 * test, but the behavior should be algorithm and purpose-independent.
2962 */
2963TEST_P(SigningOperationsTest, RsaAbort) {
2964 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2965 .RsaSigningKey(2048, 65537)
2966 .Digest(Digest::NONE)
2967 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002968 .Padding(PaddingMode::NONE)
2969 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002970
2971 ASSERT_EQ(ErrorCode::OK,
2972 Begin(KeyPurpose::SIGN,
2973 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2974 EXPECT_EQ(ErrorCode::OK, Abort());
2975
2976 // Another abort should fail
2977 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2978
2979 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002980 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002981}
2982
2983/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002984 * SigningOperationsTest.RsaNonUniqueParams
2985 *
2986 * Verifies that an operation with multiple padding modes is rejected.
2987 */
2988TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2989 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2990 .RsaSigningKey(2048, 65537)
2991 .Digest(Digest::NONE)
2992 .Digest(Digest::SHA1)
2993 .Authorization(TAG_NO_AUTH_REQUIRED)
2994 .Padding(PaddingMode::NONE)
2995 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2996 .SetDefaultValidity()));
2997
2998 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2999 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3000 .Digest(Digest::NONE)
3001 .Padding(PaddingMode::NONE)
3002 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3003
Tommy Chiuc93c4392021-05-11 18:36:50 +08003004 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3005 .Digest(Digest::NONE)
3006 .Digest(Digest::SHA1)
3007 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3008 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003009
3010 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3011 Begin(KeyPurpose::SIGN,
3012 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3013}
3014
3015/*
Selene Huang31ab4042020-04-29 04:22:39 -07003016 * SigningOperationsTest.RsaUnsupportedPadding
3017 *
3018 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3019 * with a padding mode inappropriate for RSA.
3020 */
3021TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3022 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3023 .RsaSigningKey(2048, 65537)
3024 .Authorization(TAG_NO_AUTH_REQUIRED)
3025 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003026 .Padding(PaddingMode::PKCS7)
3027 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003028 ASSERT_EQ(
3029 ErrorCode::UNSUPPORTED_PADDING_MODE,
3030 Begin(KeyPurpose::SIGN,
3031 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003032 CheckedDeleteKey();
3033
3034 ASSERT_EQ(ErrorCode::OK,
3035 GenerateKey(
3036 AuthorizationSetBuilder()
3037 .RsaSigningKey(2048, 65537)
3038 .Authorization(TAG_NO_AUTH_REQUIRED)
3039 .Digest(Digest::SHA_2_256 /* supported digest */)
3040 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3041 .SetDefaultValidity()));
3042 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3043 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3044 .Digest(Digest::SHA_2_256)
3045 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003046}
3047
3048/*
3049 * SigningOperationsTest.RsaPssNoDigest
3050 *
3051 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3052 */
3053TEST_P(SigningOperationsTest, RsaNoDigest) {
3054 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3055 .RsaSigningKey(2048, 65537)
3056 .Authorization(TAG_NO_AUTH_REQUIRED)
3057 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003058 .Padding(PaddingMode::RSA_PSS)
3059 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003060 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3061 Begin(KeyPurpose::SIGN,
3062 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3063
3064 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3065 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3066}
3067
3068/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003069 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003070 *
3071 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3072 * supported in some cases (as validated in other tests), but a mode must be specified.
3073 */
3074TEST_P(SigningOperationsTest, RsaNoPadding) {
3075 // Padding must be specified
3076 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3077 .RsaKey(2048, 65537)
3078 .Authorization(TAG_NO_AUTH_REQUIRED)
3079 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003080 .Digest(Digest::NONE)
3081 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003082 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3083 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3084}
3085
3086/*
3087 * SigningOperationsTest.RsaShortMessage
3088 *
3089 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3090 */
3091TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3092 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3093 .Authorization(TAG_NO_AUTH_REQUIRED)
3094 .RsaSigningKey(2048, 65537)
3095 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003096 .Padding(PaddingMode::NONE)
3097 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003098
3099 // Barely shorter
3100 string message(2048 / 8 - 1, 'a');
3101 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3102
3103 // Much shorter
3104 message = "a";
3105 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3106}
3107
3108/*
3109 * SigningOperationsTest.RsaSignWithEncryptionKey
3110 *
3111 * Verifies that RSA encryption keys cannot be used to sign.
3112 */
3113TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3114 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3115 .Authorization(TAG_NO_AUTH_REQUIRED)
3116 .RsaEncryptionKey(2048, 65537)
3117 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003118 .Padding(PaddingMode::NONE)
3119 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003120 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3121 Begin(KeyPurpose::SIGN,
3122 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3123}
3124
3125/*
3126 * SigningOperationsTest.RsaSignTooLargeMessage
3127 *
3128 * Verifies that attempting a raw signature of a message which is the same length as the key,
3129 * but numerically larger than the public modulus, fails with the correct error.
3130 */
3131TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3132 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3133 .Authorization(TAG_NO_AUTH_REQUIRED)
3134 .RsaSigningKey(2048, 65537)
3135 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003136 .Padding(PaddingMode::NONE)
3137 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003138
3139 // Largest possible message will always be larger than the public modulus.
3140 string message(2048 / 8, static_cast<char>(0xff));
3141 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3142 .Authorization(TAG_NO_AUTH_REQUIRED)
3143 .Digest(Digest::NONE)
3144 .Padding(PaddingMode::NONE)));
3145 string signature;
3146 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3147}
3148
3149/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003150 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3151 *
David Drysdale42fe1892021-10-14 14:43:46 +01003152 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003153 */
3154TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003155
3156 string message = "1234567890";
3157 string corrupt_message = "2234567890";
3158 for (auto curve : ValidCurves()) {
3159 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003160 // Ed25519 only allows Digest::NONE.
3161 auto digests = (curve == EcCurve::CURVE_25519)
3162 ? std::vector<Digest>(1, Digest::NONE)
3163 : ValidDigests(true /* withNone */, false /* withMD5 */);
3164
David Drysdaledf8f52e2021-05-06 08:10:58 +01003165 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3166 .Authorization(TAG_NO_AUTH_REQUIRED)
3167 .EcdsaSigningKey(curve)
3168 .Digest(digests)
3169 .SetDefaultValidity());
3170 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3171 if (error != ErrorCode::OK) {
3172 continue;
3173 }
3174
3175 for (auto digest : digests) {
3176 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3177 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3178 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3179 }
3180
3181 auto rc = DeleteKey();
3182 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3183 }
3184}
3185
3186/*
Selene Huang31ab4042020-04-29 04:22:39 -07003187 * SigningOperationsTest.EcdsaAllCurves
3188 *
David Drysdale42fe1892021-10-14 14:43:46 +01003189 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003190 */
3191TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3192 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003193 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3194 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003195 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3196 .Authorization(TAG_NO_AUTH_REQUIRED)
3197 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003198 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003199 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003200 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3201 if (error != ErrorCode::OK) continue;
3202
3203 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003204 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003205 CheckedDeleteKey();
3206 }
3207}
3208
3209/*
David Drysdale42fe1892021-10-14 14:43:46 +01003210 * SigningOperationsTest.EcdsaCurve25519
3211 *
3212 * Verifies that ECDSA operations succeed with curve25519.
3213 */
3214TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3215 if (!Curve25519Supported()) {
3216 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3217 }
3218
3219 EcCurve curve = EcCurve::CURVE_25519;
3220 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3221 .Authorization(TAG_NO_AUTH_REQUIRED)
3222 .EcdsaSigningKey(curve)
3223 .Digest(Digest::NONE)
3224 .SetDefaultValidity());
3225 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3226
3227 string message(1024, 'a');
3228 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3229 CheckedDeleteKey();
3230}
3231
3232/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003233 * SigningOperationsTest.EcdsaCurve25519MaxSize
3234 *
3235 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3236 */
3237TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3238 if (!Curve25519Supported()) {
3239 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3240 }
3241
3242 EcCurve curve = EcCurve::CURVE_25519;
3243 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3244 .Authorization(TAG_NO_AUTH_REQUIRED)
3245 .EcdsaSigningKey(curve)
3246 .Digest(Digest::NONE)
3247 .SetDefaultValidity());
3248 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3249
3250 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3251
3252 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3253 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3254 string message(msg_size, 'a');
3255
3256 // Attempt to sign via Begin+Finish.
3257 AuthorizationSet out_params;
3258 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3259 EXPECT_TRUE(out_params.empty());
3260 string signature;
3261 auto result = Finish(message, &signature);
3262 EXPECT_EQ(result, ErrorCode::OK);
3263 LocalVerifyMessage(message, signature, params);
3264
3265 // Attempt to sign via Begin+Update+Finish
3266 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3267 EXPECT_TRUE(out_params.empty());
3268 string output;
3269 result = Update(message, &output);
3270 EXPECT_EQ(result, ErrorCode::OK);
3271 EXPECT_EQ(output.size(), 0);
3272 string signature2;
3273 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3274 LocalVerifyMessage(message, signature2, params);
3275 }
3276
3277 CheckedDeleteKey();
3278}
3279
3280/*
3281 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3282 *
3283 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3284 */
3285TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3286 if (!Curve25519Supported()) {
3287 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3288 }
3289
3290 EcCurve curve = EcCurve::CURVE_25519;
3291 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3292 .Authorization(TAG_NO_AUTH_REQUIRED)
3293 .EcdsaSigningKey(curve)
3294 .Digest(Digest::NONE)
3295 .SetDefaultValidity());
3296 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3297
3298 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3299
3300 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3301 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3302 string message(msg_size, 'a');
3303
3304 // Attempt to sign via Begin+Finish.
3305 AuthorizationSet out_params;
3306 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3307 EXPECT_TRUE(out_params.empty());
3308 string signature;
3309 auto result = Finish(message, &signature);
3310 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3311
3312 // Attempt to sign via Begin+Update (but never get to Finish)
3313 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3314 EXPECT_TRUE(out_params.empty());
3315 string output;
3316 result = Update(message, &output);
3317 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3318 }
3319
3320 CheckedDeleteKey();
3321}
3322
3323/*
Selene Huang31ab4042020-04-29 04:22:39 -07003324 * SigningOperationsTest.EcdsaNoDigestHugeData
3325 *
3326 * Verifies that ECDSA operations support very large messages, even without digesting. This
3327 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3328 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3329 * the framework.
3330 */
3331TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3332 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3333 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003334 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003335 .Digest(Digest::NONE)
3336 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003337 string message(1 * 1024, 'a');
3338 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3339}
3340
3341/*
3342 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3343 *
3344 * Verifies that using an EC key requires the correct app ID/data.
3345 */
3346TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3347 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3348 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003349 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003350 .Digest(Digest::NONE)
3351 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003352 .Authorization(TAG_APPLICATION_DATA, "appdata")
3353 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003354
3355 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3356
Selene Huang31ab4042020-04-29 04:22:39 -07003357 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3358 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3359 AbortIfNeeded();
3360 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3361 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3362 .Digest(Digest::NONE)
3363 .Authorization(TAG_APPLICATION_ID, "clientid")));
3364 AbortIfNeeded();
3365 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3366 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3367 .Digest(Digest::NONE)
3368 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3369 AbortIfNeeded();
3370 EXPECT_EQ(ErrorCode::OK,
3371 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3372 .Digest(Digest::NONE)
3373 .Authorization(TAG_APPLICATION_DATA, "appdata")
3374 .Authorization(TAG_APPLICATION_ID, "clientid")));
3375 AbortIfNeeded();
3376}
3377
3378/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003379 * SigningOperationsTest.EcdsaIncompatibleDigest
3380 *
3381 * Verifies that using an EC key requires compatible digest.
3382 */
3383TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3384 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3385 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003386 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003387 .Digest(Digest::NONE)
3388 .Digest(Digest::SHA1)
3389 .SetDefaultValidity()));
3390 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3391 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3392 AbortIfNeeded();
3393}
3394
3395/*
Selene Huang31ab4042020-04-29 04:22:39 -07003396 * SigningOperationsTest.AesEcbSign
3397 *
3398 * Verifies that attempts to use AES keys to sign fail in the correct way.
3399 */
3400TEST_P(SigningOperationsTest, AesEcbSign) {
3401 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3402 .Authorization(TAG_NO_AUTH_REQUIRED)
3403 .SigningKey()
3404 .AesEncryptionKey(128)
3405 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3406
3407 AuthorizationSet out_params;
3408 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3409 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3410 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3411 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3412}
3413
3414/*
3415 * SigningOperationsTest.HmacAllDigests
3416 *
3417 * Verifies that HMAC works with all digests.
3418 */
3419TEST_P(SigningOperationsTest, HmacAllDigests) {
3420 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
3421 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3422 .Authorization(TAG_NO_AUTH_REQUIRED)
3423 .HmacKey(128)
3424 .Digest(digest)
3425 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3426 << "Failed to create HMAC key with digest " << digest;
3427 string message = "12345678901234567890123456789012";
3428 string signature = MacMessage(message, digest, 160);
3429 EXPECT_EQ(160U / 8U, signature.size())
3430 << "Failed to sign with HMAC key with digest " << digest;
3431 CheckedDeleteKey();
3432 }
3433}
3434
3435/*
3436 * SigningOperationsTest.HmacSha256TooLargeMacLength
3437 *
3438 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3439 * digest size.
3440 */
3441TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3442 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3443 .Authorization(TAG_NO_AUTH_REQUIRED)
3444 .HmacKey(128)
3445 .Digest(Digest::SHA_2_256)
3446 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3447 AuthorizationSet output_params;
3448 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3449 AuthorizationSetBuilder()
3450 .Digest(Digest::SHA_2_256)
3451 .Authorization(TAG_MAC_LENGTH, 264),
3452 &output_params));
3453}
3454
3455/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003456 * SigningOperationsTest.HmacSha256InvalidMacLength
3457 *
3458 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3459 * not a multiple of 8.
3460 */
3461TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3462 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3463 .Authorization(TAG_NO_AUTH_REQUIRED)
3464 .HmacKey(128)
3465 .Digest(Digest::SHA_2_256)
3466 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3467 AuthorizationSet output_params;
3468 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3469 AuthorizationSetBuilder()
3470 .Digest(Digest::SHA_2_256)
3471 .Authorization(TAG_MAC_LENGTH, 161),
3472 &output_params));
3473}
3474
3475/*
Selene Huang31ab4042020-04-29 04:22:39 -07003476 * SigningOperationsTest.HmacSha256TooSmallMacLength
3477 *
3478 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3479 * specified minimum MAC length.
3480 */
3481TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3482 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3483 .Authorization(TAG_NO_AUTH_REQUIRED)
3484 .HmacKey(128)
3485 .Digest(Digest::SHA_2_256)
3486 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3487 AuthorizationSet output_params;
3488 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3489 AuthorizationSetBuilder()
3490 .Digest(Digest::SHA_2_256)
3491 .Authorization(TAG_MAC_LENGTH, 120),
3492 &output_params));
3493}
3494
3495/*
3496 * SigningOperationsTest.HmacRfc4231TestCase3
3497 *
3498 * Validates against the test vectors from RFC 4231 test case 3.
3499 */
3500TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3501 string key(20, 0xaa);
3502 string message(50, 0xdd);
3503 uint8_t sha_224_expected[] = {
3504 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3505 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3506 };
3507 uint8_t sha_256_expected[] = {
3508 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3509 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3510 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3511 };
3512 uint8_t sha_384_expected[] = {
3513 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3514 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3515 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3516 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3517 };
3518 uint8_t sha_512_expected[] = {
3519 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3520 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3521 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3522 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3523 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3524 };
3525
3526 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3527 if (SecLevel() != SecurityLevel::STRONGBOX) {
3528 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3529 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3530 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3531 }
3532}
3533
3534/*
3535 * SigningOperationsTest.HmacRfc4231TestCase5
3536 *
3537 * Validates against the test vectors from RFC 4231 test case 5.
3538 */
3539TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3540 string key(20, 0x0c);
3541 string message = "Test With Truncation";
3542
3543 uint8_t sha_224_expected[] = {
3544 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3545 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3546 };
3547 uint8_t sha_256_expected[] = {
3548 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3549 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3550 };
3551 uint8_t sha_384_expected[] = {
3552 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3553 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3554 };
3555 uint8_t sha_512_expected[] = {
3556 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3557 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3558 };
3559
3560 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3561 if (SecLevel() != SecurityLevel::STRONGBOX) {
3562 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3563 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3564 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3565 }
3566}
3567
3568INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3569
3570typedef KeyMintAidlTestBase VerificationOperationsTest;
3571
3572/*
Selene Huang31ab4042020-04-29 04:22:39 -07003573 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3574 *
3575 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3576 */
3577TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3578 string key_material = "HelloThisIsAKey";
3579
3580 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003581 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003582 EXPECT_EQ(ErrorCode::OK,
3583 ImportKey(AuthorizationSetBuilder()
3584 .Authorization(TAG_NO_AUTH_REQUIRED)
3585 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3586 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3587 .Digest(Digest::SHA_2_256)
3588 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3589 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3590 EXPECT_EQ(ErrorCode::OK,
3591 ImportKey(AuthorizationSetBuilder()
3592 .Authorization(TAG_NO_AUTH_REQUIRED)
3593 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3594 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3595 .Digest(Digest::SHA_2_256)
3596 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3597 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3598
3599 string message = "This is a message.";
3600 string signature = SignMessage(
3601 signing_key, message,
3602 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3603
3604 // Signing key should not work.
3605 AuthorizationSet out_params;
3606 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3607 Begin(KeyPurpose::VERIFY, signing_key,
3608 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3609
3610 // Verification key should work.
3611 VerifyMessage(verification_key, message, signature,
3612 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3613
3614 CheckedDeleteKey(&signing_key);
3615 CheckedDeleteKey(&verification_key);
3616}
3617
Prashant Patildec9fdc2021-12-08 15:25:47 +00003618/*
3619 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3620 *
3621 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3622 */
3623TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3624 string key_material = "HelloThisIsAKey";
3625
3626 vector<uint8_t> signing_key, verification_key;
3627 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3628 EXPECT_EQ(ErrorCode::OK,
3629 ImportKey(AuthorizationSetBuilder()
3630 .Authorization(TAG_NO_AUTH_REQUIRED)
3631 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3632 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3633 .Digest(Digest::SHA_2_256)
3634 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3635 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3636 EXPECT_EQ(ErrorCode::OK,
3637 ImportKey(AuthorizationSetBuilder()
3638 .Authorization(TAG_NO_AUTH_REQUIRED)
3639 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3640 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3641 .Digest(Digest::SHA_2_256)
3642 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3643 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3644
3645 string message = "This is a message.";
3646 string signature = SignMessage(
3647 signing_key, message,
3648 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3649
3650 AuthorizationSet begin_out_params;
3651 ASSERT_EQ(ErrorCode::OK,
3652 Begin(KeyPurpose::VERIFY, verification_key,
3653 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3654
3655 string corruptMessage = "This is b message."; // Corrupted message
3656 string output;
3657 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3658
3659 ASSERT_EQ(ErrorCode::OK,
3660 Begin(KeyPurpose::VERIFY, verification_key,
3661 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3662
3663 signature[0] += 1; // Corrupt a signature
3664 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3665
3666 CheckedDeleteKey(&signing_key);
3667 CheckedDeleteKey(&verification_key);
3668}
3669
Selene Huang31ab4042020-04-29 04:22:39 -07003670INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3671
3672typedef KeyMintAidlTestBase ExportKeyTest;
3673
3674/*
3675 * ExportKeyTest.RsaUnsupportedKeyFormat
3676 *
3677 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3678 */
3679// TODO(seleneh) add ExportKey to GenerateKey
3680// check result
3681
3682class ImportKeyTest : public KeyMintAidlTestBase {
3683 public:
3684 template <TagType tag_type, Tag tag, typename ValueT>
3685 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3686 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003687 for (auto& entry : key_characteristics_) {
3688 if (entry.securityLevel == SecLevel()) {
3689 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3690 << "Tag " << tag << " with value " << expected
3691 << " not found at security level" << entry.securityLevel;
3692 } else {
3693 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3694 << "Tag " << tag << " found at security level " << entry.securityLevel;
3695 }
Selene Huang31ab4042020-04-29 04:22:39 -07003696 }
3697 }
3698
3699 void CheckOrigin() {
3700 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003701 // Origin isn't a crypto param, but it always lives with them.
3702 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003703 }
3704};
3705
3706/*
3707 * ImportKeyTest.RsaSuccess
3708 *
3709 * Verifies that importing and using an RSA key pair works correctly.
3710 */
3711TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003712 uint32_t key_size;
3713 string key;
3714
3715 if (SecLevel() == SecurityLevel::STRONGBOX) {
3716 key_size = 2048;
3717 key = rsa_2048_key;
3718 } else {
3719 key_size = 1024;
3720 key = rsa_key;
3721 }
3722
Selene Huang31ab4042020-04-29 04:22:39 -07003723 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3724 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003725 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003726 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003727 .Padding(PaddingMode::RSA_PSS)
3728 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003729 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003730
3731 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003732 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003733 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3734 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3735 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3736 CheckOrigin();
3737
3738 string message(1024 / 8, 'a');
3739 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3740 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003741 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003742}
3743
3744/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003745 * ImportKeyTest.RsaSuccessWithoutParams
3746 *
3747 * Verifies that importing and using an RSA key pair without specifying parameters
3748 * works correctly.
3749 */
3750TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3751 uint32_t key_size;
3752 string key;
3753
3754 if (SecLevel() == SecurityLevel::STRONGBOX) {
3755 key_size = 2048;
3756 key = rsa_2048_key;
3757 } else {
3758 key_size = 1024;
3759 key = rsa_key;
3760 }
3761
3762 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3763 .Authorization(TAG_NO_AUTH_REQUIRED)
3764 .SigningKey()
3765 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3766 .Digest(Digest::SHA_2_256)
3767 .Padding(PaddingMode::RSA_PSS)
3768 .SetDefaultValidity(),
3769 KeyFormat::PKCS8, key));
3770
3771 // Key size and public exponent are determined from the imported key material.
3772 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3773 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3774
3775 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3776 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3777 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3778 CheckOrigin();
3779
3780 string message(1024 / 8, 'a');
3781 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3782 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003783 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003784}
3785
3786/*
Selene Huang31ab4042020-04-29 04:22:39 -07003787 * ImportKeyTest.RsaKeySizeMismatch
3788 *
3789 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3790 * correct way.
3791 */
3792TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3793 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3794 ImportKey(AuthorizationSetBuilder()
3795 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3796 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003797 .Padding(PaddingMode::NONE)
3798 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003799 KeyFormat::PKCS8, rsa_key));
3800}
3801
3802/*
3803 * ImportKeyTest.RsaPublicExponentMismatch
3804 *
3805 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3806 * fails in the correct way.
3807 */
3808TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3809 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3810 ImportKey(AuthorizationSetBuilder()
3811 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3812 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003813 .Padding(PaddingMode::NONE)
3814 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003815 KeyFormat::PKCS8, rsa_key));
3816}
3817
3818/*
David Drysdalee60248c2021-10-04 12:54:13 +01003819 * ImportKeyTest.RsaAttestMultiPurposeFail
3820 *
3821 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
3822 */
3823TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
3824 uint32_t key_size = 2048;
3825 string key = rsa_2048_key;
3826
3827 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3828 ImportKey(AuthorizationSetBuilder()
3829 .Authorization(TAG_NO_AUTH_REQUIRED)
3830 .RsaSigningKey(key_size, 65537)
3831 .AttestKey()
3832 .Digest(Digest::SHA_2_256)
3833 .Padding(PaddingMode::RSA_PSS)
3834 .SetDefaultValidity(),
3835 KeyFormat::PKCS8, key));
3836}
3837
3838/*
Selene Huang31ab4042020-04-29 04:22:39 -07003839 * ImportKeyTest.EcdsaSuccess
3840 *
3841 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3842 */
3843TEST_P(ImportKeyTest, EcdsaSuccess) {
3844 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3845 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003846 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003847 .Digest(Digest::SHA_2_256)
3848 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003849 KeyFormat::PKCS8, ec_256_key));
3850
3851 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003852 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3853 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3854
3855 CheckOrigin();
3856
3857 string message(32, 'a');
3858 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3859 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003860 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003861}
3862
3863/*
3864 * ImportKeyTest.EcdsaP256RFC5915Success
3865 *
3866 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3867 * correctly.
3868 */
3869TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3870 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3871 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003872 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003873 .Digest(Digest::SHA_2_256)
3874 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003875 KeyFormat::PKCS8, ec_256_key_rfc5915));
3876
3877 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003878 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3879 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3880
3881 CheckOrigin();
3882
3883 string message(32, 'a');
3884 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3885 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003886 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003887}
3888
3889/*
3890 * ImportKeyTest.EcdsaP256SEC1Success
3891 *
3892 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3893 */
3894TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3895 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3896 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003897 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003898 .Digest(Digest::SHA_2_256)
3899 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003900 KeyFormat::PKCS8, ec_256_key_sec1));
3901
3902 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003903 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3904 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3905
3906 CheckOrigin();
3907
3908 string message(32, 'a');
3909 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3910 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003911 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003912}
3913
3914/*
3915 * ImportKeyTest.Ecdsa521Success
3916 *
3917 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3918 */
3919TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01003920 if (SecLevel() == SecurityLevel::STRONGBOX) {
3921 GTEST_SKIP() << "Test not applicable to StrongBox device";
3922 }
Selene Huang31ab4042020-04-29 04:22:39 -07003923 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3924 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003925 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003926 .Digest(Digest::SHA_2_256)
3927 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003928 KeyFormat::PKCS8, ec_521_key));
3929
3930 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003931 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3932 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3933 CheckOrigin();
3934
3935 string message(32, 'a');
3936 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3937 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003938 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003939}
3940
3941/*
Selene Huang31ab4042020-04-29 04:22:39 -07003942 * ImportKeyTest.EcdsaCurveMismatch
3943 *
3944 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3945 * the correct way.
3946 */
3947TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3948 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3949 ImportKey(AuthorizationSetBuilder()
3950 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003951 .Digest(Digest::NONE)
3952 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003953 KeyFormat::PKCS8, ec_256_key));
3954}
3955
3956/*
David Drysdalee60248c2021-10-04 12:54:13 +01003957 * ImportKeyTest.EcdsaAttestMultiPurposeFail
3958 *
3959 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
3960 */
3961TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
3962 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3963 ImportKey(AuthorizationSetBuilder()
3964 .Authorization(TAG_NO_AUTH_REQUIRED)
3965 .EcdsaSigningKey(EcCurve::P_256)
3966 .AttestKey()
3967 .Digest(Digest::SHA_2_256)
3968 .SetDefaultValidity(),
3969 KeyFormat::PKCS8, ec_256_key));
3970}
3971
3972/*
David Drysdale42fe1892021-10-14 14:43:46 +01003973 * ImportKeyTest.Ed25519RawSuccess
3974 *
3975 * Verifies that importing and using a raw Ed25519 private key works correctly.
3976 */
3977TEST_P(ImportKeyTest, Ed25519RawSuccess) {
3978 if (!Curve25519Supported()) {
3979 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3980 }
3981
3982 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3983 .Authorization(TAG_NO_AUTH_REQUIRED)
3984 .EcdsaSigningKey(EcCurve::CURVE_25519)
3985 .Digest(Digest::NONE)
3986 .SetDefaultValidity(),
3987 KeyFormat::RAW, ed25519_key));
3988 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3989 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
3990 CheckOrigin();
3991
3992 // The returned cert should hold the correct public key.
3993 ASSERT_GT(cert_chain_.size(), 0);
3994 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
3995 ASSERT_NE(kmKeyCert, nullptr);
3996 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
3997 ASSERT_NE(kmPubKey.get(), nullptr);
3998 size_t kmPubKeySize = 32;
3999 uint8_t kmPubKeyData[32];
4000 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4001 ASSERT_EQ(kmPubKeySize, 32);
4002 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4003
4004 string message(32, 'a');
4005 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4006 string signature = SignMessage(message, params);
4007 LocalVerifyMessage(message, signature, params);
4008}
4009
4010/*
4011 * ImportKeyTest.Ed25519Pkcs8Success
4012 *
4013 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4014 */
4015TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4016 if (!Curve25519Supported()) {
4017 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4018 }
4019
4020 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4021 .Authorization(TAG_NO_AUTH_REQUIRED)
4022 .EcdsaSigningKey(EcCurve::CURVE_25519)
4023 .Digest(Digest::NONE)
4024 .SetDefaultValidity(),
4025 KeyFormat::PKCS8, ed25519_pkcs8_key));
4026 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4027 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4028 CheckOrigin();
4029
4030 // The returned cert should hold the correct public key.
4031 ASSERT_GT(cert_chain_.size(), 0);
4032 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4033 ASSERT_NE(kmKeyCert, nullptr);
4034 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4035 ASSERT_NE(kmPubKey.get(), nullptr);
4036 size_t kmPubKeySize = 32;
4037 uint8_t kmPubKeyData[32];
4038 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4039 ASSERT_EQ(kmPubKeySize, 32);
4040 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4041
4042 string message(32, 'a');
4043 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4044 string signature = SignMessage(message, params);
4045 LocalVerifyMessage(message, signature, params);
4046}
4047
4048/*
4049 * ImportKeyTest.Ed25519CurveMismatch
4050 *
4051 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4052 * the correct way.
4053 */
4054TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4055 if (!Curve25519Supported()) {
4056 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4057 }
4058
4059 ASSERT_NE(ErrorCode::OK,
4060 ImportKey(AuthorizationSetBuilder()
4061 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4062 .Digest(Digest::NONE)
4063 .SetDefaultValidity(),
4064 KeyFormat::RAW, ed25519_key));
4065}
4066
4067/*
4068 * ImportKeyTest.Ed25519FormatMismatch
4069 *
4070 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4071 */
4072TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4073 if (!Curve25519Supported()) {
4074 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4075 }
4076
4077 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4078 .EcdsaSigningKey(EcCurve::CURVE_25519)
4079 .Digest(Digest::NONE)
4080 .SetDefaultValidity(),
4081 KeyFormat::PKCS8, ed25519_key));
4082 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4083 .EcdsaSigningKey(EcCurve::CURVE_25519)
4084 .Digest(Digest::NONE)
4085 .SetDefaultValidity(),
4086 KeyFormat::RAW, ed25519_pkcs8_key));
4087}
4088
4089/*
4090 * ImportKeyTest.Ed25519PurposeMismatch
4091 *
4092 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4093 */
4094TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4095 if (!Curve25519Supported()) {
4096 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4097 }
4098
4099 // Can't have both SIGN and ATTEST_KEY
4100 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4101 .EcdsaSigningKey(EcCurve::CURVE_25519)
4102 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4103 .Digest(Digest::NONE)
4104 .SetDefaultValidity(),
4105 KeyFormat::RAW, ed25519_key));
4106 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4107 // PKCS#8 format and so includes an OID).
4108 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4109 .EcdsaKey(EcCurve::CURVE_25519)
4110 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4111 .Digest(Digest::NONE)
4112 .SetDefaultValidity(),
4113 KeyFormat::PKCS8, ed25519_pkcs8_key));
4114}
4115
4116/*
4117 * ImportKeyTest.X25519RawSuccess
4118 *
4119 * Verifies that importing and using a raw X25519 private key works correctly.
4120 */
4121TEST_P(ImportKeyTest, X25519RawSuccess) {
4122 if (!Curve25519Supported()) {
4123 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4124 }
4125
4126 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4127 .Authorization(TAG_NO_AUTH_REQUIRED)
4128 .EcdsaKey(EcCurve::CURVE_25519)
4129 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4130 .SetDefaultValidity(),
4131 KeyFormat::RAW, x25519_key));
4132
4133 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4134 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4135 CheckOrigin();
4136}
4137
4138/*
4139 * ImportKeyTest.X25519Pkcs8Success
4140 *
4141 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4142 */
4143TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4144 if (!Curve25519Supported()) {
4145 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4146 }
4147
4148 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4149 .Authorization(TAG_NO_AUTH_REQUIRED)
4150 .EcdsaKey(EcCurve::CURVE_25519)
4151 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4152 .SetDefaultValidity(),
4153 KeyFormat::PKCS8, x25519_pkcs8_key));
4154
4155 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4156 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4157 CheckOrigin();
4158}
4159
4160/*
4161 * ImportKeyTest.X25519CurveMismatch
4162 *
4163 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4164 * the correct way.
4165 */
4166TEST_P(ImportKeyTest, X25519CurveMismatch) {
4167 if (!Curve25519Supported()) {
4168 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4169 }
4170
4171 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4172 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4173 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4174 .SetDefaultValidity(),
4175 KeyFormat::RAW, x25519_key));
4176}
4177
4178/*
4179 * ImportKeyTest.X25519FormatMismatch
4180 *
4181 * Verifies that importing an X25519 key with an invalid format fails.
4182 */
4183TEST_P(ImportKeyTest, X25519FormatMismatch) {
4184 if (!Curve25519Supported()) {
4185 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4186 }
4187
4188 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4189 .EcdsaKey(EcCurve::CURVE_25519)
4190 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4191 .SetDefaultValidity(),
4192 KeyFormat::PKCS8, x25519_key));
4193 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4194 .EcdsaKey(EcCurve::CURVE_25519)
4195 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4196 .SetDefaultValidity(),
4197 KeyFormat::RAW, x25519_pkcs8_key));
4198}
4199
4200/*
4201 * ImportKeyTest.X25519PurposeMismatch
4202 *
4203 * Verifies that importing an X25519 key pair with an invalid format fails.
4204 */
4205TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4206 if (!Curve25519Supported()) {
4207 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4208 }
4209
4210 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4211 .EcdsaKey(EcCurve::CURVE_25519)
4212 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4213 .SetDefaultValidity(),
4214 KeyFormat::PKCS8, x25519_pkcs8_key));
4215 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4216 .EcdsaSigningKey(EcCurve::CURVE_25519)
4217 .SetDefaultValidity(),
4218 KeyFormat::PKCS8, x25519_pkcs8_key));
4219}
4220
4221/*
Selene Huang31ab4042020-04-29 04:22:39 -07004222 * ImportKeyTest.AesSuccess
4223 *
4224 * Verifies that importing and using an AES key works.
4225 */
4226TEST_P(ImportKeyTest, AesSuccess) {
4227 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4228 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4229 .Authorization(TAG_NO_AUTH_REQUIRED)
4230 .AesEncryptionKey(key.size() * 8)
4231 .EcbMode()
4232 .Padding(PaddingMode::PKCS7),
4233 KeyFormat::RAW, key));
4234
4235 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4236 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4237 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4238 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4239 CheckOrigin();
4240
4241 string message = "Hello World!";
4242 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4243 string ciphertext = EncryptMessage(message, params);
4244 string plaintext = DecryptMessage(ciphertext, params);
4245 EXPECT_EQ(message, plaintext);
4246}
4247
4248/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004249 * ImportKeyTest.AesFailure
4250 *
4251 * Verifies that importing an invalid AES key fails.
4252 */
4253TEST_P(ImportKeyTest, AesFailure) {
4254 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4255 uint32_t bitlen = key.size() * 8;
4256 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004257 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004258 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004259 .Authorization(TAG_NO_AUTH_REQUIRED)
4260 .AesEncryptionKey(key_size)
4261 .EcbMode()
4262 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004263 KeyFormat::RAW, key);
4264 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004265 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4266 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004267 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004268
4269 // Explicit key size matches that of the provided key, but it's not a valid size.
4270 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4271 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4272 ImportKey(AuthorizationSetBuilder()
4273 .Authorization(TAG_NO_AUTH_REQUIRED)
4274 .AesEncryptionKey(long_key.size() * 8)
4275 .EcbMode()
4276 .Padding(PaddingMode::PKCS7),
4277 KeyFormat::RAW, long_key));
4278 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4279 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4280 ImportKey(AuthorizationSetBuilder()
4281 .Authorization(TAG_NO_AUTH_REQUIRED)
4282 .AesEncryptionKey(short_key.size() * 8)
4283 .EcbMode()
4284 .Padding(PaddingMode::PKCS7),
4285 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004286}
4287
4288/*
4289 * ImportKeyTest.TripleDesSuccess
4290 *
4291 * Verifies that importing and using a 3DES key works.
4292 */
4293TEST_P(ImportKeyTest, TripleDesSuccess) {
4294 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4295 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4296 .Authorization(TAG_NO_AUTH_REQUIRED)
4297 .TripleDesEncryptionKey(168)
4298 .EcbMode()
4299 .Padding(PaddingMode::PKCS7),
4300 KeyFormat::RAW, key));
4301
4302 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4303 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4304 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4305 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4306 CheckOrigin();
4307
4308 string message = "Hello World!";
4309 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4310 string ciphertext = EncryptMessage(message, params);
4311 string plaintext = DecryptMessage(ciphertext, params);
4312 EXPECT_EQ(message, plaintext);
4313}
4314
4315/*
4316 * ImportKeyTest.TripleDesFailure
4317 *
4318 * Verifies that importing an invalid 3DES key fails.
4319 */
4320TEST_P(ImportKeyTest, TripleDesFailure) {
4321 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004322 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004323 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004324 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004325 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004326 .Authorization(TAG_NO_AUTH_REQUIRED)
4327 .TripleDesEncryptionKey(key_size)
4328 .EcbMode()
4329 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004330 KeyFormat::RAW, key);
4331 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004332 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4333 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004334 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004335 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004336 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004337 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4338 ImportKey(AuthorizationSetBuilder()
4339 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004340 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004341 .EcbMode()
4342 .Padding(PaddingMode::PKCS7),
4343 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004344 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004345 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4346 ImportKey(AuthorizationSetBuilder()
4347 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004348 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004349 .EcbMode()
4350 .Padding(PaddingMode::PKCS7),
4351 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004352}
4353
4354/*
4355 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004356 *
4357 * Verifies that importing and using an HMAC key works.
4358 */
4359TEST_P(ImportKeyTest, HmacKeySuccess) {
4360 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4361 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4362 .Authorization(TAG_NO_AUTH_REQUIRED)
4363 .HmacKey(key.size() * 8)
4364 .Digest(Digest::SHA_2_256)
4365 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4366 KeyFormat::RAW, key));
4367
4368 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4369 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4370 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4371 CheckOrigin();
4372
4373 string message = "Hello World!";
4374 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4375 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4376}
4377
4378INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4379
4380auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004381 // IKeyMintDevice.aidl
4382 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4383 "020100" // INTEGER length 1 value 0x00 (version)
4384 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4385 "934bf94e2aa28a3f83c9f79297250262"
4386 "fbe3276b5a1c91159bbfa3ef8957aac8"
4387 "4b59b30b455a79c2973480823d8b3863"
4388 "c3deef4a8e243590268d80e18751a0e1"
4389 "30f67ce6a1ace9f79b95e097474febc9"
4390 "81195b1d13a69086c0863f66a7b7fdb4"
4391 "8792227b1ac5e2489febdf087ab54864"
4392 "83033a6f001ca5d1ec1e27f5c30f4cec"
4393 "2642074a39ae68aee552e196627a8e3d"
4394 "867e67a8c01b11e75f13cca0a97ab668"
4395 "b50cda07a8ecb7cd8e3dd7009c963653"
4396 "4f6f239cffe1fc8daa466f78b676c711"
4397 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4398 "99b801597d5220e307eaa5bee507fb94"
4399 "d1fa69f9e519b2de315bac92c36f2ea1"
4400 "fa1df4478c0ddedeae8c70e0233cd098"
4401 "040c" // OCTET STRING length 0x0c (initializationVector)
4402 "d796b02c370f1fa4cc0124f1"
4403 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4404 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4405 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4406 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4407 "3106" // SET length 0x06
4408 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4409 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4410 // } end SET
4411 // } end [1]
4412 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4413 "020120" // INTEGER length 1 value 0x20 (AES)
4414 // } end [2]
4415 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4416 "02020100" // INTEGER length 2 value 0x100
4417 // } end [3]
4418 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4419 "3103" // SET length 0x03 {
4420 "020101" // INTEGER length 1 value 0x01 (ECB)
4421 // } end SET
4422 // } end [4]
4423 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4424 "3103" // SET length 0x03 {
4425 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4426 // } end SET
4427 // } end [5]
4428 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4429 // (noAuthRequired)
4430 "0500" // NULL
4431 // } end [503]
4432 // } end SEQUENCE (AuthorizationList)
4433 // } end SEQUENCE (KeyDescription)
4434 "0420" // OCTET STRING length 0x20 (encryptedKey)
4435 "ccd540855f833a5e1480bfd2d36faf3a"
4436 "eee15df5beabe2691bc82dde2a7aa910"
4437 "0410" // OCTET STRING length 0x10 (tag)
4438 "64c9f689c60ff6223ab6e6999e0eb6e5"
4439 // } SEQUENCE (SecureKeyWrapper)
4440);
Selene Huang31ab4042020-04-29 04:22:39 -07004441
4442auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004443 // IKeyMintDevice.aidl
4444 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4445 "020100" // INTEGER length 1 value 0x00 (version)
4446 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4447 "aad93ed5924f283b4bb5526fbe7a1412"
4448 "f9d9749ec30db9062b29e574a8546f33"
4449 "c88732452f5b8e6a391ee76c39ed1712"
4450 "c61d8df6213dec1cffbc17a8c6d04c7b"
4451 "30893d8daa9b2015213e219468215532"
4452 "07f8f9931c4caba23ed3bee28b36947e"
4453 "47f10e0a5c3dc51c988a628daad3e5e1"
4454 "f4005e79c2d5a96c284b4b8d7e4948f3"
4455 "31e5b85dd5a236f85579f3ea1d1b8484"
4456 "87470bdb0ab4f81a12bee42c99fe0df4"
4457 "bee3759453e69ad1d68a809ce06b949f"
4458 "7694a990429b2fe81e066ff43e56a216"
4459 "02db70757922a4bcc23ab89f1e35da77"
4460 "586775f423e519c2ea394caf48a28d0c"
4461 "8020f1dcf6b3a68ec246f615ae96dae9"
4462 "a079b1f6eb959033c1af5c125fd94168"
4463 "040c" // OCTET STRING length 0x0c (initializationVector)
4464 "6d9721d08589581ab49204a3"
4465 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4466 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4467 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4468 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4469 "3106" // SET length 0x06
4470 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4471 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4472 // } end SET
4473 // } end [1]
4474 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4475 "020120" // INTEGER length 1 value 0x20 (AES)
4476 // } end [2]
4477 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4478 "02020100" // INTEGER length 2 value 0x100
4479 // } end [3]
4480 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4481 "3103" // SET length 0x03 {
4482 "020101" // INTEGER length 1 value 0x01 (ECB)
4483 // } end SET
4484 // } end [4]
4485 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4486 "3103" // SET length 0x03 {
4487 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4488 // } end SET
4489 // } end [5]
4490 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4491 // (noAuthRequired)
4492 "0500" // NULL
4493 // } end [503]
4494 // } end SEQUENCE (AuthorizationList)
4495 // } end SEQUENCE (KeyDescription)
4496 "0420" // OCTET STRING length 0x20 (encryptedKey)
4497 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4498 "c20d1f99a9a024a76f35c8e2cab9b68d"
4499 "0410" // OCTET STRING length 0x10 (tag)
4500 "2560c70109ae67c030f00b98b512a670"
4501 // } SEQUENCE (SecureKeyWrapper)
4502);
Selene Huang31ab4042020-04-29 04:22:39 -07004503
4504auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004505 // RFC 5208 s5
4506 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4507 "020100" // INTEGER length 1 value 0x00 (version)
4508 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4509 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4510 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4511 "0500" // NULL (parameters)
4512 // } SEQUENCE (AlgorithmIdentifier)
4513 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4514 // RFC 8017 A.1.2
4515 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4516 "020100" // INTEGER length 1 value 0x00 (version)
4517 "02820101" // INTEGER length 0x0101 (modulus) value...
4518 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4519 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4520 "7b06e673a837313d56b1c725150a3fef" // 0x30
4521 "86acbddc41bb759c2854eae32d35841e" // 0x40
4522 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4523 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4524 "312d7bd5921ffaea1347c157406fef71" // 0x70
4525 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4526 "f4645c11f5c1374c3886427411c44979" // 0x90
4527 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4528 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4529 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4530 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4531 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4532 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4533 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4534 "55" // 0x101
4535 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4536 "02820100" // INTEGER length 0x100 (privateExponent) value...
4537 "431447b6251908112b1ee76f99f3711a" // 0x10
4538 "52b6630960046c2de70de188d833f8b8" // 0x20
4539 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4540 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4541 "e710b630a03adc683b5d2c43080e52be" // 0x50
4542 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4543 "822bccff087d63c940ba8a45f670feb2" // 0x70
4544 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4545 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4546 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4547 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4548 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4549 "52659d5a5ba05b663737a8696281865b" // 0xd0
4550 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4551 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4552 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4553 "028181" // INTEGER length 0x81 (prime1) value...
4554 "00de392e18d682c829266cc3454e1d61" // 0x10
4555 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4556 "ff841be5bac82a164c5970007047b8c5" // 0x30
4557 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4558 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4559 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4560 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4561 "9e91346130748a6e3c124f9149d71c74" // 0x80
4562 "35"
4563 "028181" // INTEGER length 0x81 (prime2) value...
4564 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4565 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4566 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4567 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4568 "9ed39a2d934c880440aed8832f984316" // 0x50
4569 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4570 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4571 "b880677c068e1be936e81288815252a8" // 0x80
4572 "a1"
4573 "028180" // INTEGER length 0x80 (exponent1) value...
4574 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4575 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4576 "5a063212a4f105a3764743e53281988a" // 0x30
4577 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4578 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4579 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4580 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4581 "4719d6e2b9439823719cd08bcd031781" // 0x80
4582 "028181" // INTEGER length 0x81 (exponent2) value...
4583 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4584 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4585 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4586 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4587 "1254186af30b22c10582a8a43e34fe94" // 0x50
4588 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4589 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4590 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4591 "61"
4592 "028181" // INTEGER length 0x81 (coefficient) value...
4593 "00c931617c77829dfb1270502be9195c" // 0x10
4594 "8f2830885f57dba869536811e6864236" // 0x20
4595 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4596 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4597 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4598 "959356210723287b0affcc9f727044d4" // 0x60
4599 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4600 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4601 "22"
4602 // } SEQUENCE
4603 // } SEQUENCE ()
4604);
Selene Huang31ab4042020-04-29 04:22:39 -07004605
4606string zero_masking_key =
4607 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4608string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4609
4610class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4611
4612TEST_P(ImportWrappedKeyTest, Success) {
4613 auto wrapping_key_desc = AuthorizationSetBuilder()
4614 .RsaEncryptionKey(2048, 65537)
4615 .Digest(Digest::SHA_2_256)
4616 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004617 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4618 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004619
4620 ASSERT_EQ(ErrorCode::OK,
4621 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4622 AuthorizationSetBuilder()
4623 .Digest(Digest::SHA_2_256)
4624 .Padding(PaddingMode::RSA_OAEP)));
4625
4626 string message = "Hello World!";
4627 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4628 string ciphertext = EncryptMessage(message, params);
4629 string plaintext = DecryptMessage(ciphertext, params);
4630 EXPECT_EQ(message, plaintext);
4631}
4632
David Drysdaled2cc8c22021-04-15 13:29:45 +01004633/*
4634 * ImportWrappedKeyTest.SuccessSidsIgnored
4635 *
4636 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
4637 * include Tag:USER_SECURE_ID.
4638 */
4639TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
4640 auto wrapping_key_desc = AuthorizationSetBuilder()
4641 .RsaEncryptionKey(2048, 65537)
4642 .Digest(Digest::SHA_2_256)
4643 .Padding(PaddingMode::RSA_OAEP)
4644 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4645 .SetDefaultValidity();
4646
4647 int64_t password_sid = 42;
4648 int64_t biometric_sid = 24;
4649 ASSERT_EQ(ErrorCode::OK,
4650 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4651 AuthorizationSetBuilder()
4652 .Digest(Digest::SHA_2_256)
4653 .Padding(PaddingMode::RSA_OAEP),
4654 password_sid, biometric_sid));
4655
4656 string message = "Hello World!";
4657 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4658 string ciphertext = EncryptMessage(message, params);
4659 string plaintext = DecryptMessage(ciphertext, params);
4660 EXPECT_EQ(message, plaintext);
4661}
4662
Selene Huang31ab4042020-04-29 04:22:39 -07004663TEST_P(ImportWrappedKeyTest, SuccessMasked) {
4664 auto wrapping_key_desc = AuthorizationSetBuilder()
4665 .RsaEncryptionKey(2048, 65537)
4666 .Digest(Digest::SHA_2_256)
4667 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004668 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4669 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004670
4671 ASSERT_EQ(ErrorCode::OK,
4672 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
4673 AuthorizationSetBuilder()
4674 .Digest(Digest::SHA_2_256)
4675 .Padding(PaddingMode::RSA_OAEP)));
4676}
4677
4678TEST_P(ImportWrappedKeyTest, WrongMask) {
4679 auto wrapping_key_desc = AuthorizationSetBuilder()
4680 .RsaEncryptionKey(2048, 65537)
4681 .Digest(Digest::SHA_2_256)
4682 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004683 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4684 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004685
4686 ASSERT_EQ(
4687 ErrorCode::VERIFICATION_FAILED,
4688 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4689 AuthorizationSetBuilder()
4690 .Digest(Digest::SHA_2_256)
4691 .Padding(PaddingMode::RSA_OAEP)));
4692}
4693
4694TEST_P(ImportWrappedKeyTest, WrongPurpose) {
4695 auto wrapping_key_desc = AuthorizationSetBuilder()
4696 .RsaEncryptionKey(2048, 65537)
4697 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004698 .Padding(PaddingMode::RSA_OAEP)
4699 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004700
4701 ASSERT_EQ(
4702 ErrorCode::INCOMPATIBLE_PURPOSE,
4703 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4704 AuthorizationSetBuilder()
4705 .Digest(Digest::SHA_2_256)
4706 .Padding(PaddingMode::RSA_OAEP)));
4707}
4708
David Drysdaled2cc8c22021-04-15 13:29:45 +01004709TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
4710 auto wrapping_key_desc = AuthorizationSetBuilder()
4711 .RsaEncryptionKey(2048, 65537)
4712 .Digest(Digest::SHA_2_256)
4713 .Padding(PaddingMode::RSA_PSS)
4714 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4715 .SetDefaultValidity();
4716
4717 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
4718 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4719 AuthorizationSetBuilder()
4720 .Digest(Digest::SHA_2_256)
4721 .Padding(PaddingMode::RSA_OAEP)));
4722}
4723
4724TEST_P(ImportWrappedKeyTest, WrongDigest) {
4725 auto wrapping_key_desc = AuthorizationSetBuilder()
4726 .RsaEncryptionKey(2048, 65537)
4727 .Digest(Digest::SHA_2_512)
4728 .Padding(PaddingMode::RSA_OAEP)
4729 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4730 .SetDefaultValidity();
4731
4732 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
4733 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4734 AuthorizationSetBuilder()
4735 .Digest(Digest::SHA_2_256)
4736 .Padding(PaddingMode::RSA_OAEP)));
4737}
4738
Selene Huang31ab4042020-04-29 04:22:39 -07004739INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
4740
4741typedef KeyMintAidlTestBase EncryptionOperationsTest;
4742
4743/*
4744 * EncryptionOperationsTest.RsaNoPaddingSuccess
4745 *
David Drysdale59cae642021-05-12 13:52:03 +01004746 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07004747 */
4748TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00004749 for (uint64_t exponent : ValidExponents()) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01004750 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4751 .Authorization(TAG_NO_AUTH_REQUIRED)
4752 .RsaEncryptionKey(2048, exponent)
4753 .Padding(PaddingMode::NONE)
4754 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004755
David Drysdaled2cc8c22021-04-15 13:29:45 +01004756 string message = string(2048 / 8, 'a');
4757 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004758 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004759 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004760
David Drysdale59cae642021-05-12 13:52:03 +01004761 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004762 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004763
David Drysdaled2cc8c22021-04-15 13:29:45 +01004764 // Unpadded RSA is deterministic
4765 EXPECT_EQ(ciphertext1, ciphertext2);
4766
4767 CheckedDeleteKey();
4768 }
Selene Huang31ab4042020-04-29 04:22:39 -07004769}
4770
4771/*
4772 * EncryptionOperationsTest.RsaNoPaddingShortMessage
4773 *
David Drysdale59cae642021-05-12 13:52:03 +01004774 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07004775 */
4776TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
4777 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4778 .Authorization(TAG_NO_AUTH_REQUIRED)
4779 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004780 .Padding(PaddingMode::NONE)
4781 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004782
4783 string message = "1";
4784 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4785
David Drysdale59cae642021-05-12 13:52:03 +01004786 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004787 EXPECT_EQ(2048U / 8, ciphertext.size());
4788
4789 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
4790 string plaintext = DecryptMessage(ciphertext, params);
4791
4792 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07004793}
4794
4795/*
Selene Huang31ab4042020-04-29 04:22:39 -07004796 * EncryptionOperationsTest.RsaOaepSuccess
4797 *
David Drysdale59cae642021-05-12 13:52:03 +01004798 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07004799 */
4800TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
4801 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4802
4803 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01004804 ASSERT_EQ(ErrorCode::OK,
4805 GenerateKey(AuthorizationSetBuilder()
4806 .Authorization(TAG_NO_AUTH_REQUIRED)
4807 .RsaEncryptionKey(key_size, 65537)
4808 .Padding(PaddingMode::RSA_OAEP)
4809 .Digest(digests)
4810 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
4811 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004812
4813 string message = "Hello";
4814
4815 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01004816 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4817
4818 auto params = AuthorizationSetBuilder()
4819 .Digest(digest)
4820 .Padding(PaddingMode::RSA_OAEP)
4821 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
4822 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004823 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4824 EXPECT_EQ(key_size / 8, ciphertext1.size());
4825
David Drysdale59cae642021-05-12 13:52:03 +01004826 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004827 EXPECT_EQ(key_size / 8, ciphertext2.size());
4828
4829 // OAEP randomizes padding so every result should be different (with astronomically high
4830 // probability).
4831 EXPECT_NE(ciphertext1, ciphertext2);
4832
4833 string plaintext1 = DecryptMessage(ciphertext1, params);
4834 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4835 string plaintext2 = DecryptMessage(ciphertext2, params);
4836 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4837
4838 // Decrypting corrupted ciphertext should fail.
4839 size_t offset_to_corrupt = random() % ciphertext1.size();
4840 char corrupt_byte;
4841 do {
4842 corrupt_byte = static_cast<char>(random() % 256);
4843 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4844 ciphertext1[offset_to_corrupt] = corrupt_byte;
4845
4846 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4847 string result;
4848 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4849 EXPECT_EQ(0U, result.size());
4850 }
4851}
4852
4853/*
4854 * EncryptionOperationsTest.RsaOaepInvalidDigest
4855 *
David Drysdale59cae642021-05-12 13:52:03 +01004856 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07004857 * without a digest.
4858 */
4859TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
4860 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4861 .Authorization(TAG_NO_AUTH_REQUIRED)
4862 .RsaEncryptionKey(2048, 65537)
4863 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004864 .Digest(Digest::NONE)
4865 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004866
4867 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004868 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07004869}
4870
4871/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004872 * EncryptionOperationsTest.RsaOaepInvalidPadding
4873 *
David Drysdale59cae642021-05-12 13:52:03 +01004874 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01004875 * with a padding value that is only suitable for signing/verifying.
4876 */
4877TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
4878 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4879 .Authorization(TAG_NO_AUTH_REQUIRED)
4880 .RsaEncryptionKey(2048, 65537)
4881 .Padding(PaddingMode::RSA_PSS)
4882 .Digest(Digest::NONE)
4883 .SetDefaultValidity()));
4884
4885 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004886 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01004887}
4888
4889/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004890 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07004891 *
David Drysdale59cae642021-05-12 13:52:03 +01004892 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07004893 * with a different digest than was used to encrypt.
4894 */
4895TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01004896 if (SecLevel() == SecurityLevel::STRONGBOX) {
4897 GTEST_SKIP() << "Test not applicable to StrongBox device";
4898 }
Selene Huang31ab4042020-04-29 04:22:39 -07004899
4900 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4901 .Authorization(TAG_NO_AUTH_REQUIRED)
4902 .RsaEncryptionKey(1024, 65537)
4903 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004904 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
4905 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004906 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01004907 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07004908 message,
4909 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
4910
4911 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4912 .Digest(Digest::SHA_2_256)
4913 .Padding(PaddingMode::RSA_OAEP)));
4914 string result;
4915 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
4916 EXPECT_EQ(0U, result.size());
4917}
4918
4919/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004920 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
4921 *
David Drysdale59cae642021-05-12 13:52:03 +01004922 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004923 * digests.
4924 */
4925TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
4926 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4927
4928 size_t key_size = 2048; // Need largish key for SHA-512 test.
4929 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4930 .OaepMGFDigest(digests)
4931 .Authorization(TAG_NO_AUTH_REQUIRED)
4932 .RsaEncryptionKey(key_size, 65537)
4933 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004934 .Digest(Digest::SHA_2_256)
4935 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004936
4937 string message = "Hello";
4938
4939 for (auto digest : digests) {
4940 auto params = AuthorizationSetBuilder()
4941 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4942 .Digest(Digest::SHA_2_256)
4943 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01004944 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004945 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4946 EXPECT_EQ(key_size / 8, ciphertext1.size());
4947
David Drysdale59cae642021-05-12 13:52:03 +01004948 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004949 EXPECT_EQ(key_size / 8, ciphertext2.size());
4950
4951 // OAEP randomizes padding so every result should be different (with astronomically high
4952 // probability).
4953 EXPECT_NE(ciphertext1, ciphertext2);
4954
4955 string plaintext1 = DecryptMessage(ciphertext1, params);
4956 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4957 string plaintext2 = DecryptMessage(ciphertext2, params);
4958 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4959
4960 // Decrypting corrupted ciphertext should fail.
4961 size_t offset_to_corrupt = random() % ciphertext1.size();
4962 char corrupt_byte;
4963 do {
4964 corrupt_byte = static_cast<char>(random() % 256);
4965 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4966 ciphertext1[offset_to_corrupt] = corrupt_byte;
4967
4968 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4969 string result;
4970 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4971 EXPECT_EQ(0U, result.size());
4972 }
4973}
4974
4975/*
4976 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
4977 *
David Drysdale59cae642021-05-12 13:52:03 +01004978 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004979 * with incompatible MGF digest.
4980 */
4981TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4982 ASSERT_EQ(ErrorCode::OK,
4983 GenerateKey(AuthorizationSetBuilder()
4984 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4985 .Authorization(TAG_NO_AUTH_REQUIRED)
4986 .RsaEncryptionKey(2048, 65537)
4987 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004988 .Digest(Digest::SHA_2_256)
4989 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004990 string message = "Hello World!";
4991
4992 auto params = AuthorizationSetBuilder()
4993 .Padding(PaddingMode::RSA_OAEP)
4994 .Digest(Digest::SHA_2_256)
4995 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004996 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004997}
4998
4999/*
5000 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5001 *
5002 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5003 * with unsupported MGF digest.
5004 */
5005TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5006 ASSERT_EQ(ErrorCode::OK,
5007 GenerateKey(AuthorizationSetBuilder()
5008 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5009 .Authorization(TAG_NO_AUTH_REQUIRED)
5010 .RsaEncryptionKey(2048, 65537)
5011 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005012 .Digest(Digest::SHA_2_256)
5013 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005014 string message = "Hello World!";
5015
5016 auto params = AuthorizationSetBuilder()
5017 .Padding(PaddingMode::RSA_OAEP)
5018 .Digest(Digest::SHA_2_256)
5019 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005020 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005021}
5022
5023/*
Selene Huang31ab4042020-04-29 04:22:39 -07005024 * EncryptionOperationsTest.RsaPkcs1Success
5025 *
5026 * Verifies that RSA PKCS encryption/decrypts works.
5027 */
5028TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5029 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5030 .Authorization(TAG_NO_AUTH_REQUIRED)
5031 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005032 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5033 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005034
5035 string message = "Hello World!";
5036 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005037 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005038 EXPECT_EQ(2048U / 8, ciphertext1.size());
5039
David Drysdale59cae642021-05-12 13:52:03 +01005040 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005041 EXPECT_EQ(2048U / 8, ciphertext2.size());
5042
5043 // PKCS1 v1.5 randomizes padding so every result should be different.
5044 EXPECT_NE(ciphertext1, ciphertext2);
5045
5046 string plaintext = DecryptMessage(ciphertext1, params);
5047 EXPECT_EQ(message, plaintext);
5048
5049 // Decrypting corrupted ciphertext should fail.
5050 size_t offset_to_corrupt = random() % ciphertext1.size();
5051 char corrupt_byte;
5052 do {
5053 corrupt_byte = static_cast<char>(random() % 256);
5054 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5055 ciphertext1[offset_to_corrupt] = corrupt_byte;
5056
5057 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5058 string result;
5059 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5060 EXPECT_EQ(0U, result.size());
5061}
5062
5063/*
Selene Huang31ab4042020-04-29 04:22:39 -07005064 * EncryptionOperationsTest.EcdsaEncrypt
5065 *
5066 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5067 */
5068TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5069 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5070 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005071 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005072 .Digest(Digest::NONE)
5073 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005074 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5075 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5076 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5077}
5078
5079/*
5080 * EncryptionOperationsTest.HmacEncrypt
5081 *
5082 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5083 */
5084TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5085 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5086 .Authorization(TAG_NO_AUTH_REQUIRED)
5087 .HmacKey(128)
5088 .Digest(Digest::SHA_2_256)
5089 .Padding(PaddingMode::NONE)
5090 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5091 auto params = AuthorizationSetBuilder()
5092 .Digest(Digest::SHA_2_256)
5093 .Padding(PaddingMode::NONE)
5094 .Authorization(TAG_MAC_LENGTH, 128);
5095 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5096 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5097}
5098
5099/*
5100 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5101 *
5102 * Verifies that AES ECB mode works.
5103 */
5104TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5105 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5106 .Authorization(TAG_NO_AUTH_REQUIRED)
5107 .AesEncryptionKey(128)
5108 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5109 .Padding(PaddingMode::NONE)));
5110
5111 ASSERT_GT(key_blob_.size(), 0U);
5112 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5113
5114 // Two-block message.
5115 string message = "12345678901234567890123456789012";
5116 string ciphertext1 = EncryptMessage(message, params);
5117 EXPECT_EQ(message.size(), ciphertext1.size());
5118
5119 string ciphertext2 = EncryptMessage(string(message), params);
5120 EXPECT_EQ(message.size(), ciphertext2.size());
5121
5122 // ECB is deterministic.
5123 EXPECT_EQ(ciphertext1, ciphertext2);
5124
5125 string plaintext = DecryptMessage(ciphertext1, params);
5126 EXPECT_EQ(message, plaintext);
5127}
5128
5129/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005130 * EncryptionOperationsTest.AesEcbUnknownTag
5131 *
5132 * Verifies that AES ECB operations ignore unknown tags.
5133 */
5134TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5135 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5136 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5137 KeyParameter unknown_param;
5138 unknown_param.tag = unknown_tag;
5139
5140 vector<KeyCharacteristics> key_characteristics;
5141 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5142 .Authorization(TAG_NO_AUTH_REQUIRED)
5143 .AesEncryptionKey(128)
5144 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5145 .Padding(PaddingMode::NONE)
5146 .Authorization(unknown_param),
5147 &key_blob_, &key_characteristics));
5148 ASSERT_GT(key_blob_.size(), 0U);
5149
5150 // Unknown tags should not be returned in key characteristics.
5151 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5152 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5153 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5154 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5155
5156 // Encrypt without mentioning the unknown parameter.
5157 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5158 string message = "12345678901234567890123456789012";
5159 string ciphertext = EncryptMessage(message, params);
5160 EXPECT_EQ(message.size(), ciphertext.size());
5161
5162 // Decrypt including the unknown parameter.
5163 auto decrypt_params = AuthorizationSetBuilder()
5164 .BlockMode(BlockMode::ECB)
5165 .Padding(PaddingMode::NONE)
5166 .Authorization(unknown_param);
5167 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5168 EXPECT_EQ(message, plaintext);
5169}
5170
5171/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005172 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005173 *
5174 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5175 */
5176TEST_P(EncryptionOperationsTest, AesWrongMode) {
5177 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5178 .Authorization(TAG_NO_AUTH_REQUIRED)
5179 .AesEncryptionKey(128)
5180 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5181 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005182 ASSERT_GT(key_blob_.size(), 0U);
5183
Selene Huang31ab4042020-04-29 04:22:39 -07005184 EXPECT_EQ(
5185 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5186 Begin(KeyPurpose::ENCRYPT,
5187 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5188}
5189
5190/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005191 * EncryptionOperationsTest.AesWrongPadding
5192 *
5193 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5194 */
5195TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5196 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5197 .Authorization(TAG_NO_AUTH_REQUIRED)
5198 .AesEncryptionKey(128)
5199 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5200 .Padding(PaddingMode::NONE)));
5201 ASSERT_GT(key_blob_.size(), 0U);
5202
5203 EXPECT_EQ(
5204 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5205 Begin(KeyPurpose::ENCRYPT,
5206 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5207}
5208
5209/*
5210 * EncryptionOperationsTest.AesInvalidParams
5211 *
5212 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5213 */
5214TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5215 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5216 .Authorization(TAG_NO_AUTH_REQUIRED)
5217 .AesEncryptionKey(128)
5218 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5219 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5220 .Padding(PaddingMode::NONE)
5221 .Padding(PaddingMode::PKCS7)));
5222 ASSERT_GT(key_blob_.size(), 0U);
5223
5224 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5225 .BlockMode(BlockMode::CBC)
5226 .BlockMode(BlockMode::ECB)
5227 .Padding(PaddingMode::NONE));
5228 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5229 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5230
5231 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5232 .BlockMode(BlockMode::ECB)
5233 .Padding(PaddingMode::NONE)
5234 .Padding(PaddingMode::PKCS7));
5235 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5236 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5237}
5238
5239/*
Selene Huang31ab4042020-04-29 04:22:39 -07005240 * EncryptionOperationsTest.AesWrongPurpose
5241 *
5242 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5243 * specified.
5244 */
5245TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5246 auto err = GenerateKey(AuthorizationSetBuilder()
5247 .Authorization(TAG_NO_AUTH_REQUIRED)
5248 .AesKey(128)
5249 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5250 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5251 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5252 .Padding(PaddingMode::NONE));
5253 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5254 ASSERT_GT(key_blob_.size(), 0U);
5255
5256 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5257 .BlockMode(BlockMode::GCM)
5258 .Padding(PaddingMode::NONE)
5259 .Authorization(TAG_MAC_LENGTH, 128));
5260 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5261
5262 CheckedDeleteKey();
5263
5264 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5265 .Authorization(TAG_NO_AUTH_REQUIRED)
5266 .AesKey(128)
5267 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5268 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5269 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5270 .Padding(PaddingMode::NONE)));
5271
5272 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5273 .BlockMode(BlockMode::GCM)
5274 .Padding(PaddingMode::NONE)
5275 .Authorization(TAG_MAC_LENGTH, 128));
5276 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5277}
5278
5279/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005280 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005281 *
5282 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5283 * multiple of the block size and no padding is specified.
5284 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005285TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5286 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5287 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5288 .Authorization(TAG_NO_AUTH_REQUIRED)
5289 .AesEncryptionKey(128)
5290 .Authorization(TAG_BLOCK_MODE, blockMode)
5291 .Padding(PaddingMode::NONE)));
5292 // Message is slightly shorter than two blocks.
5293 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005294
David Drysdaled2cc8c22021-04-15 13:29:45 +01005295 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5296 AuthorizationSet out_params;
5297 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5298 string ciphertext;
5299 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5300 EXPECT_EQ(0U, ciphertext.size());
5301
5302 CheckedDeleteKey();
5303 }
Selene Huang31ab4042020-04-29 04:22:39 -07005304}
5305
5306/*
5307 * EncryptionOperationsTest.AesEcbPkcs7Padding
5308 *
5309 * Verifies that AES PKCS7 padding works for any message length.
5310 */
5311TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5312 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5313 .Authorization(TAG_NO_AUTH_REQUIRED)
5314 .AesEncryptionKey(128)
5315 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5316 .Padding(PaddingMode::PKCS7)));
5317
5318 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5319
5320 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005321 for (size_t i = 0; i <= 48; i++) {
5322 SCOPED_TRACE(testing::Message() << "i = " << i);
5323 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5324 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005325 string ciphertext = EncryptMessage(message, params);
5326 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5327 string plaintext = DecryptMessage(ciphertext, params);
5328 EXPECT_EQ(message, plaintext);
5329 }
5330}
5331
5332/*
5333 * EncryptionOperationsTest.AesEcbWrongPadding
5334 *
5335 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5336 * specified.
5337 */
5338TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5339 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5340 .Authorization(TAG_NO_AUTH_REQUIRED)
5341 .AesEncryptionKey(128)
5342 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5343 .Padding(PaddingMode::NONE)));
5344
5345 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5346
5347 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005348 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005349 string message(i, 'a');
5350 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5351 }
5352}
5353
5354/*
5355 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5356 *
5357 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5358 */
5359TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5360 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5361 .Authorization(TAG_NO_AUTH_REQUIRED)
5362 .AesEncryptionKey(128)
5363 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5364 .Padding(PaddingMode::PKCS7)));
5365
5366 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5367
5368 string message = "a";
5369 string ciphertext = EncryptMessage(message, params);
5370 EXPECT_EQ(16U, ciphertext.size());
5371 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005372
Seth Moore7a55ae32021-06-23 14:28:11 -07005373 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5374 ++ciphertext[ciphertext.size() / 2];
5375
5376 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5377 string plaintext;
5378 ErrorCode error = Finish(message, &plaintext);
5379 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
5380 // This is the expected error, we can exit the test now.
5381 return;
5382 } else {
5383 // Very small chance we got valid decryption, so try again.
5384 ASSERT_EQ(error, ErrorCode::OK);
5385 }
5386 }
5387 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005388}
5389
5390vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5391 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005392 EXPECT_TRUE(iv);
5393 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005394}
5395
5396/*
5397 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5398 *
5399 * Verifies that AES CTR mode works.
5400 */
5401TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5402 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5403 .Authorization(TAG_NO_AUTH_REQUIRED)
5404 .AesEncryptionKey(128)
5405 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5406 .Padding(PaddingMode::NONE)));
5407
5408 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5409
5410 string message = "123";
5411 AuthorizationSet out_params;
5412 string ciphertext1 = EncryptMessage(message, params, &out_params);
5413 vector<uint8_t> iv1 = CopyIv(out_params);
5414 EXPECT_EQ(16U, iv1.size());
5415
5416 EXPECT_EQ(message.size(), ciphertext1.size());
5417
5418 out_params.Clear();
5419 string ciphertext2 = EncryptMessage(message, params, &out_params);
5420 vector<uint8_t> iv2 = CopyIv(out_params);
5421 EXPECT_EQ(16U, iv2.size());
5422
5423 // IVs should be random, so ciphertexts should differ.
5424 EXPECT_NE(ciphertext1, ciphertext2);
5425
5426 auto params_iv1 =
5427 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5428 auto params_iv2 =
5429 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5430
5431 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5432 EXPECT_EQ(message, plaintext);
5433 plaintext = DecryptMessage(ciphertext2, params_iv2);
5434 EXPECT_EQ(message, plaintext);
5435
5436 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5437 plaintext = DecryptMessage(ciphertext1, params_iv2);
5438 EXPECT_NE(message, plaintext);
5439 plaintext = DecryptMessage(ciphertext2, params_iv1);
5440 EXPECT_NE(message, plaintext);
5441}
5442
5443/*
5444 * EncryptionOperationsTest.AesIncremental
5445 *
5446 * Verifies that AES works, all modes, when provided data in various size increments.
5447 */
5448TEST_P(EncryptionOperationsTest, AesIncremental) {
5449 auto block_modes = {
5450 BlockMode::ECB,
5451 BlockMode::CBC,
5452 BlockMode::CTR,
5453 BlockMode::GCM,
5454 };
5455
5456 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5457 .Authorization(TAG_NO_AUTH_REQUIRED)
5458 .AesEncryptionKey(128)
5459 .BlockMode(block_modes)
5460 .Padding(PaddingMode::NONE)
5461 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5462
5463 for (int increment = 1; increment <= 240; ++increment) {
5464 for (auto block_mode : block_modes) {
5465 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07005466 auto params =
5467 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
5468 if (block_mode == BlockMode::GCM) {
5469 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
5470 }
Selene Huang31ab4042020-04-29 04:22:39 -07005471
5472 AuthorizationSet output_params;
5473 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
5474
5475 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005476 string to_send;
5477 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07005478 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005479 }
Shawn Willden92d79c02021-02-19 07:31:55 -07005480 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
5481 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07005482
5483 switch (block_mode) {
5484 case BlockMode::GCM:
5485 EXPECT_EQ(message.size() + 16, ciphertext.size());
5486 break;
5487 case BlockMode::CTR:
5488 EXPECT_EQ(message.size(), ciphertext.size());
5489 break;
5490 case BlockMode::CBC:
5491 case BlockMode::ECB:
5492 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
5493 break;
5494 }
5495
5496 auto iv = output_params.GetTagValue(TAG_NONCE);
5497 switch (block_mode) {
5498 case BlockMode::CBC:
5499 case BlockMode::GCM:
5500 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005501 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
5502 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
5503 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005504 break;
5505
5506 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005507 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07005508 break;
5509 }
5510
5511 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
5512 << "Decrypt begin() failed for block mode " << block_mode;
5513
5514 string plaintext;
5515 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07005516 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005517 }
5518 ErrorCode error = Finish(to_send, &plaintext);
5519 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
5520 << " and increment " << increment;
5521 if (error == ErrorCode::OK) {
5522 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
5523 << block_mode << " and increment " << increment;
5524 }
5525 }
5526 }
5527}
5528
5529struct AesCtrSp80038aTestVector {
5530 const char* key;
5531 const char* nonce;
5532 const char* plaintext;
5533 const char* ciphertext;
5534};
5535
5536// These test vectors are taken from
5537// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
5538static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
5539 // AES-128
5540 {
5541 "2b7e151628aed2a6abf7158809cf4f3c",
5542 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5543 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5544 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5545 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
5546 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
5547 },
5548 // AES-192
5549 {
5550 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
5551 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5552 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5553 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5554 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
5555 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
5556 },
5557 // AES-256
5558 {
5559 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
5560 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5561 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5562 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5563 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
5564 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
5565 },
5566};
5567
5568/*
5569 * EncryptionOperationsTest.AesCtrSp80038aTestVector
5570 *
5571 * Verifies AES CTR implementation against SP800-38A test vectors.
5572 */
5573TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
5574 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
5575 for (size_t i = 0; i < 3; i++) {
5576 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
5577 const string key = hex2str(test.key);
5578 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
5579 InvalidSizes.end())
5580 continue;
5581 const string nonce = hex2str(test.nonce);
5582 const string plaintext = hex2str(test.plaintext);
5583 const string ciphertext = hex2str(test.ciphertext);
5584 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
5585 }
5586}
5587
5588/*
5589 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
5590 *
5591 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
5592 */
5593TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
5594 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5595 .Authorization(TAG_NO_AUTH_REQUIRED)
5596 .AesEncryptionKey(128)
5597 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5598 .Padding(PaddingMode::PKCS7)));
5599 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5600 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5601}
5602
5603/*
5604 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
5605 *
5606 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5607 */
5608TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
5609 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5610 .Authorization(TAG_NO_AUTH_REQUIRED)
5611 .AesEncryptionKey(128)
5612 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5613 .Authorization(TAG_CALLER_NONCE)
5614 .Padding(PaddingMode::NONE)));
5615
5616 auto params = AuthorizationSetBuilder()
5617 .BlockMode(BlockMode::CTR)
5618 .Padding(PaddingMode::NONE)
5619 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
5620 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5621
5622 params = AuthorizationSetBuilder()
5623 .BlockMode(BlockMode::CTR)
5624 .Padding(PaddingMode::NONE)
5625 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
5626 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5627
5628 params = AuthorizationSetBuilder()
5629 .BlockMode(BlockMode::CTR)
5630 .Padding(PaddingMode::NONE)
5631 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
5632 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5633}
5634
5635/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005636 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07005637 *
5638 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5639 */
5640TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
5641 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5642 .Authorization(TAG_NO_AUTH_REQUIRED)
5643 .AesEncryptionKey(128)
5644 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5645 .Padding(PaddingMode::NONE)));
5646 // Two-block message.
5647 string message = "12345678901234567890123456789012";
5648 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5649 AuthorizationSet out_params;
5650 string ciphertext1 = EncryptMessage(message, params, &out_params);
5651 vector<uint8_t> iv1 = CopyIv(out_params);
5652 EXPECT_EQ(message.size(), ciphertext1.size());
5653
5654 out_params.Clear();
5655
5656 string ciphertext2 = EncryptMessage(message, params, &out_params);
5657 vector<uint8_t> iv2 = CopyIv(out_params);
5658 EXPECT_EQ(message.size(), ciphertext2.size());
5659
5660 // IVs should be random, so ciphertexts should differ.
5661 EXPECT_NE(ciphertext1, ciphertext2);
5662
5663 params.push_back(TAG_NONCE, iv1);
5664 string plaintext = DecryptMessage(ciphertext1, params);
5665 EXPECT_EQ(message, plaintext);
5666}
5667
5668/*
5669 * EncryptionOperationsTest.AesCallerNonce
5670 *
5671 * Verifies that AES caller-provided nonces work correctly.
5672 */
5673TEST_P(EncryptionOperationsTest, AesCallerNonce) {
5674 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5675 .Authorization(TAG_NO_AUTH_REQUIRED)
5676 .AesEncryptionKey(128)
5677 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5678 .Authorization(TAG_CALLER_NONCE)
5679 .Padding(PaddingMode::NONE)));
5680
5681 string message = "12345678901234567890123456789012";
5682
5683 // Don't specify nonce, should get a random one.
5684 AuthorizationSetBuilder params =
5685 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5686 AuthorizationSet out_params;
5687 string ciphertext = EncryptMessage(message, params, &out_params);
5688 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005689 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005690
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005691 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005692 string plaintext = DecryptMessage(ciphertext, params);
5693 EXPECT_EQ(message, plaintext);
5694
5695 // Now specify a nonce, should also work.
5696 params = AuthorizationSetBuilder()
5697 .BlockMode(BlockMode::CBC)
5698 .Padding(PaddingMode::NONE)
5699 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5700 out_params.Clear();
5701 ciphertext = EncryptMessage(message, params, &out_params);
5702
5703 // Decrypt with correct nonce.
5704 plaintext = DecryptMessage(ciphertext, params);
5705 EXPECT_EQ(message, plaintext);
5706
5707 // Try with wrong nonce.
5708 params = AuthorizationSetBuilder()
5709 .BlockMode(BlockMode::CBC)
5710 .Padding(PaddingMode::NONE)
5711 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
5712 plaintext = DecryptMessage(ciphertext, params);
5713 EXPECT_NE(message, plaintext);
5714}
5715
5716/*
5717 * EncryptionOperationsTest.AesCallerNonceProhibited
5718 *
5719 * Verifies that caller-provided nonces are not permitted when not specified in the key
5720 * authorizations.
5721 */
5722TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
5723 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5724 .Authorization(TAG_NO_AUTH_REQUIRED)
5725 .AesEncryptionKey(128)
5726 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5727 .Padding(PaddingMode::NONE)));
5728
5729 string message = "12345678901234567890123456789012";
5730
5731 // Don't specify nonce, should get a random one.
5732 AuthorizationSetBuilder params =
5733 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5734 AuthorizationSet out_params;
5735 string ciphertext = EncryptMessage(message, params, &out_params);
5736 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005737 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005738
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005739 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005740 string plaintext = DecryptMessage(ciphertext, params);
5741 EXPECT_EQ(message, plaintext);
5742
5743 // Now specify a nonce, should fail
5744 params = AuthorizationSetBuilder()
5745 .BlockMode(BlockMode::CBC)
5746 .Padding(PaddingMode::NONE)
5747 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5748 out_params.Clear();
5749 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5750}
5751
5752/*
5753 * EncryptionOperationsTest.AesGcmRoundTripSuccess
5754 *
5755 * Verifies that AES GCM mode works.
5756 */
5757TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
5758 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5759 .Authorization(TAG_NO_AUTH_REQUIRED)
5760 .AesEncryptionKey(128)
5761 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5762 .Padding(PaddingMode::NONE)
5763 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5764
5765 string aad = "foobar";
5766 string message = "123456789012345678901234567890123456";
5767
5768 auto begin_params = AuthorizationSetBuilder()
5769 .BlockMode(BlockMode::GCM)
5770 .Padding(PaddingMode::NONE)
5771 .Authorization(TAG_MAC_LENGTH, 128);
5772
Selene Huang31ab4042020-04-29 04:22:39 -07005773 // Encrypt
5774 AuthorizationSet begin_out_params;
5775 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5776 << "Begin encrypt";
5777 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005778 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5779 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005780 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5781
5782 // Grab nonce
5783 begin_params.push_back(begin_out_params);
5784
5785 // Decrypt.
5786 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07005787 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005788 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005789 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005790 EXPECT_EQ(message.length(), plaintext.length());
5791 EXPECT_EQ(message, plaintext);
5792}
5793
5794/*
5795 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
5796 *
5797 * Verifies that AES GCM mode works, even when there's a long delay
5798 * between operations.
5799 */
5800TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
5801 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5802 .Authorization(TAG_NO_AUTH_REQUIRED)
5803 .AesEncryptionKey(128)
5804 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5805 .Padding(PaddingMode::NONE)
5806 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5807
5808 string aad = "foobar";
5809 string message = "123456789012345678901234567890123456";
5810
5811 auto begin_params = AuthorizationSetBuilder()
5812 .BlockMode(BlockMode::GCM)
5813 .Padding(PaddingMode::NONE)
5814 .Authorization(TAG_MAC_LENGTH, 128);
5815
Selene Huang31ab4042020-04-29 04:22:39 -07005816 // Encrypt
5817 AuthorizationSet begin_out_params;
5818 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5819 << "Begin encrypt";
5820 string ciphertext;
5821 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005822 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005823 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005824 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005825
5826 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5827
5828 // Grab nonce
5829 begin_params.push_back(begin_out_params);
5830
5831 // Decrypt.
5832 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
5833 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005834 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005835 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005836 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005837 sleep(5);
5838 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
5839 EXPECT_EQ(message.length(), plaintext.length());
5840 EXPECT_EQ(message, plaintext);
5841}
5842
5843/*
5844 * EncryptionOperationsTest.AesGcmDifferentNonces
5845 *
5846 * Verifies that encrypting the same data with different nonces produces different outputs.
5847 */
5848TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
5849 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5850 .Authorization(TAG_NO_AUTH_REQUIRED)
5851 .AesEncryptionKey(128)
5852 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5853 .Padding(PaddingMode::NONE)
5854 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5855 .Authorization(TAG_CALLER_NONCE)));
5856
5857 string aad = "foobar";
5858 string message = "123456789012345678901234567890123456";
5859 string nonce1 = "000000000000";
5860 string nonce2 = "111111111111";
5861 string nonce3 = "222222222222";
5862
5863 string ciphertext1 =
5864 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
5865 string ciphertext2 =
5866 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
5867 string ciphertext3 =
5868 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
5869
5870 ASSERT_NE(ciphertext1, ciphertext2);
5871 ASSERT_NE(ciphertext1, ciphertext3);
5872 ASSERT_NE(ciphertext2, ciphertext3);
5873}
5874
5875/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005876 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
5877 *
5878 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
5879 */
5880TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
5881 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5882 .Authorization(TAG_NO_AUTH_REQUIRED)
5883 .AesEncryptionKey(128)
5884 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5885 .Padding(PaddingMode::NONE)
5886 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5887
5888 string aad = "foobar";
5889 string message = "123456789012345678901234567890123456";
5890
5891 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5892 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5893 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5894
5895 ASSERT_NE(ciphertext1, ciphertext2);
5896 ASSERT_NE(ciphertext1, ciphertext3);
5897 ASSERT_NE(ciphertext2, ciphertext3);
5898}
5899
5900/*
Selene Huang31ab4042020-04-29 04:22:39 -07005901 * EncryptionOperationsTest.AesGcmTooShortTag
5902 *
5903 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
5904 */
5905TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
5906 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5907 .Authorization(TAG_NO_AUTH_REQUIRED)
5908 .AesEncryptionKey(128)
5909 .BlockMode(BlockMode::GCM)
5910 .Padding(PaddingMode::NONE)
5911 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5912 string message = "123456789012345678901234567890123456";
5913 auto params = AuthorizationSetBuilder()
5914 .BlockMode(BlockMode::GCM)
5915 .Padding(PaddingMode::NONE)
5916 .Authorization(TAG_MAC_LENGTH, 96);
5917
5918 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
5919}
5920
5921/*
5922 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
5923 *
5924 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
5925 */
5926TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
5927 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5928 .Authorization(TAG_NO_AUTH_REQUIRED)
5929 .AesEncryptionKey(128)
5930 .BlockMode(BlockMode::GCM)
5931 .Padding(PaddingMode::NONE)
5932 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5933 string aad = "foobar";
5934 string message = "123456789012345678901234567890123456";
5935 auto params = AuthorizationSetBuilder()
5936 .BlockMode(BlockMode::GCM)
5937 .Padding(PaddingMode::NONE)
5938 .Authorization(TAG_MAC_LENGTH, 128);
5939
Selene Huang31ab4042020-04-29 04:22:39 -07005940 // Encrypt
5941 AuthorizationSet begin_out_params;
5942 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5943 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005944 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005945
5946 AuthorizationSet finish_out_params;
5947 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005948 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5949 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005950
5951 params = AuthorizationSetBuilder()
5952 .Authorizations(begin_out_params)
5953 .BlockMode(BlockMode::GCM)
5954 .Padding(PaddingMode::NONE)
5955 .Authorization(TAG_MAC_LENGTH, 96);
5956
5957 // Decrypt.
5958 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
5959}
5960
5961/*
5962 * EncryptionOperationsTest.AesGcmCorruptKey
5963 *
5964 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
5965 */
5966TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
5967 const uint8_t nonce_bytes[] = {
5968 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
5969 };
5970 string nonce = make_string(nonce_bytes);
5971 const uint8_t ciphertext_bytes[] = {
5972 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
5973 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
5974 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
5975 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5976 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5977 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5978 };
5979 string ciphertext = make_string(ciphertext_bytes);
5980
5981 auto params = AuthorizationSetBuilder()
5982 .BlockMode(BlockMode::GCM)
5983 .Padding(PaddingMode::NONE)
5984 .Authorization(TAG_MAC_LENGTH, 128)
5985 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5986
5987 auto import_params = AuthorizationSetBuilder()
5988 .Authorization(TAG_NO_AUTH_REQUIRED)
5989 .AesEncryptionKey(128)
5990 .BlockMode(BlockMode::GCM)
5991 .Padding(PaddingMode::NONE)
5992 .Authorization(TAG_CALLER_NONCE)
5993 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5994
5995 // Import correct key and decrypt
5996 const uint8_t key_bytes[] = {
5997 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5998 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5999 };
6000 string key = make_string(key_bytes);
6001 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6002 string plaintext = DecryptMessage(ciphertext, params);
6003 CheckedDeleteKey();
6004
6005 // Corrupt key and attempt to decrypt
6006 key[0] = 0;
6007 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6008 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6009 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6010 CheckedDeleteKey();
6011}
6012
6013/*
6014 * EncryptionOperationsTest.AesGcmAadNoData
6015 *
6016 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6017 * encrypt.
6018 */
6019TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6020 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6021 .Authorization(TAG_NO_AUTH_REQUIRED)
6022 .AesEncryptionKey(128)
6023 .BlockMode(BlockMode::GCM)
6024 .Padding(PaddingMode::NONE)
6025 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6026
6027 string aad = "1234567890123456";
6028 auto params = AuthorizationSetBuilder()
6029 .BlockMode(BlockMode::GCM)
6030 .Padding(PaddingMode::NONE)
6031 .Authorization(TAG_MAC_LENGTH, 128);
6032
Selene Huang31ab4042020-04-29 04:22:39 -07006033 // Encrypt
6034 AuthorizationSet begin_out_params;
6035 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6036 string ciphertext;
6037 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006038 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6039 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006040 EXPECT_TRUE(finish_out_params.empty());
6041
6042 // Grab nonce
6043 params.push_back(begin_out_params);
6044
6045 // Decrypt.
6046 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006047 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006048 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006049 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006050
6051 EXPECT_TRUE(finish_out_params.empty());
6052
6053 EXPECT_EQ("", plaintext);
6054}
6055
6056/*
6057 * EncryptionOperationsTest.AesGcmMultiPartAad
6058 *
6059 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6060 * chunks.
6061 */
6062TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6063 const size_t tag_bits = 128;
6064 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6065 .Authorization(TAG_NO_AUTH_REQUIRED)
6066 .AesEncryptionKey(128)
6067 .BlockMode(BlockMode::GCM)
6068 .Padding(PaddingMode::NONE)
6069 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6070
6071 string message = "123456789012345678901234567890123456";
6072 auto begin_params = AuthorizationSetBuilder()
6073 .BlockMode(BlockMode::GCM)
6074 .Padding(PaddingMode::NONE)
6075 .Authorization(TAG_MAC_LENGTH, tag_bits);
6076 AuthorizationSet begin_out_params;
6077
Selene Huang31ab4042020-04-29 04:22:39 -07006078 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
6079
6080 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006081 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6082 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006083 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006084 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6085 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006086
Selene Huang31ab4042020-04-29 04:22:39 -07006087 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006088 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006089
6090 // Grab nonce.
6091 begin_params.push_back(begin_out_params);
6092
6093 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07006094 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006095 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006096 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006097 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006098 EXPECT_EQ(message, plaintext);
6099}
6100
6101/*
6102 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6103 *
6104 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6105 */
6106TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6107 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6108 .Authorization(TAG_NO_AUTH_REQUIRED)
6109 .AesEncryptionKey(128)
6110 .BlockMode(BlockMode::GCM)
6111 .Padding(PaddingMode::NONE)
6112 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6113
6114 string message = "123456789012345678901234567890123456";
6115 auto begin_params = AuthorizationSetBuilder()
6116 .BlockMode(BlockMode::GCM)
6117 .Padding(PaddingMode::NONE)
6118 .Authorization(TAG_MAC_LENGTH, 128);
6119 AuthorizationSet begin_out_params;
6120
Selene Huang31ab4042020-04-29 04:22:39 -07006121 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
6122
Shawn Willden92d79c02021-02-19 07:31:55 -07006123 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006124 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006125 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6126 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006127
David Drysdaled2cc8c22021-04-15 13:29:45 +01006128 // The failure should have already cancelled the operation.
6129 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6130
Shawn Willden92d79c02021-02-19 07:31:55 -07006131 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006132}
6133
6134/*
6135 * EncryptionOperationsTest.AesGcmBadAad
6136 *
6137 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6138 */
6139TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6140 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6141 .Authorization(TAG_NO_AUTH_REQUIRED)
6142 .AesEncryptionKey(128)
6143 .BlockMode(BlockMode::GCM)
6144 .Padding(PaddingMode::NONE)
6145 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6146
6147 string message = "12345678901234567890123456789012";
6148 auto begin_params = AuthorizationSetBuilder()
6149 .BlockMode(BlockMode::GCM)
6150 .Padding(PaddingMode::NONE)
6151 .Authorization(TAG_MAC_LENGTH, 128);
6152
Selene Huang31ab4042020-04-29 04:22:39 -07006153 // Encrypt
6154 AuthorizationSet begin_out_params;
6155 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006156 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006157 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006158 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006159
6160 // Grab nonce
6161 begin_params.push_back(begin_out_params);
6162
Selene Huang31ab4042020-04-29 04:22:39 -07006163 // Decrypt.
6164 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006165 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006166 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006167 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006168}
6169
6170/*
6171 * EncryptionOperationsTest.AesGcmWrongNonce
6172 *
6173 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6174 */
6175TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6176 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6177 .Authorization(TAG_NO_AUTH_REQUIRED)
6178 .AesEncryptionKey(128)
6179 .BlockMode(BlockMode::GCM)
6180 .Padding(PaddingMode::NONE)
6181 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6182
6183 string message = "12345678901234567890123456789012";
6184 auto begin_params = AuthorizationSetBuilder()
6185 .BlockMode(BlockMode::GCM)
6186 .Padding(PaddingMode::NONE)
6187 .Authorization(TAG_MAC_LENGTH, 128);
6188
Selene Huang31ab4042020-04-29 04:22:39 -07006189 // Encrypt
6190 AuthorizationSet begin_out_params;
6191 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006192 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006193 string ciphertext;
6194 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006195 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006196
6197 // Wrong nonce
6198 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6199
6200 // Decrypt.
6201 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006202 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006203 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006204 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006205
6206 // With wrong nonce, should have gotten garbage plaintext (or none).
6207 EXPECT_NE(message, plaintext);
6208}
6209
6210/*
6211 * EncryptionOperationsTest.AesGcmCorruptTag
6212 *
6213 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6214 */
6215TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6216 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6217 .Authorization(TAG_NO_AUTH_REQUIRED)
6218 .AesEncryptionKey(128)
6219 .BlockMode(BlockMode::GCM)
6220 .Padding(PaddingMode::NONE)
6221 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6222
6223 string aad = "1234567890123456";
6224 string message = "123456789012345678901234567890123456";
6225
6226 auto params = AuthorizationSetBuilder()
6227 .BlockMode(BlockMode::GCM)
6228 .Padding(PaddingMode::NONE)
6229 .Authorization(TAG_MAC_LENGTH, 128);
6230
Selene Huang31ab4042020-04-29 04:22:39 -07006231 // Encrypt
6232 AuthorizationSet begin_out_params;
6233 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006234 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006235 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006236 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006237
6238 // Corrupt tag
6239 ++(*ciphertext.rbegin());
6240
6241 // Grab nonce
6242 params.push_back(begin_out_params);
6243
6244 // Decrypt.
6245 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006246 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006247 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006248 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006249}
6250
6251/*
6252 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
6253 *
6254 * Verifies that 3DES is basically functional.
6255 */
6256TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
6257 auto auths = AuthorizationSetBuilder()
6258 .TripleDesEncryptionKey(168)
6259 .BlockMode(BlockMode::ECB)
6260 .Authorization(TAG_NO_AUTH_REQUIRED)
6261 .Padding(PaddingMode::NONE);
6262
6263 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
6264 // Two-block message.
6265 string message = "1234567890123456";
6266 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6267 string ciphertext1 = EncryptMessage(message, inParams);
6268 EXPECT_EQ(message.size(), ciphertext1.size());
6269
6270 string ciphertext2 = EncryptMessage(string(message), inParams);
6271 EXPECT_EQ(message.size(), ciphertext2.size());
6272
6273 // ECB is deterministic.
6274 EXPECT_EQ(ciphertext1, ciphertext2);
6275
6276 string plaintext = DecryptMessage(ciphertext1, inParams);
6277 EXPECT_EQ(message, plaintext);
6278}
6279
6280/*
6281 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
6282 *
6283 * Verifies that CBC keys reject ECB usage.
6284 */
6285TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
6286 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6287 .TripleDesEncryptionKey(168)
6288 .BlockMode(BlockMode::CBC)
6289 .Authorization(TAG_NO_AUTH_REQUIRED)
6290 .Padding(PaddingMode::NONE)));
6291
6292 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6293 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
6294}
6295
6296/*
6297 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
6298 *
6299 * Tests ECB mode with PKCS#7 padding, various message sizes.
6300 */
6301TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
6302 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6303 .TripleDesEncryptionKey(168)
6304 .BlockMode(BlockMode::ECB)
6305 .Authorization(TAG_NO_AUTH_REQUIRED)
6306 .Padding(PaddingMode::PKCS7)));
6307
6308 for (size_t i = 0; i < 32; ++i) {
6309 string message(i, 'a');
6310 auto inParams =
6311 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6312 string ciphertext = EncryptMessage(message, inParams);
6313 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6314 string plaintext = DecryptMessage(ciphertext, inParams);
6315 EXPECT_EQ(message, plaintext);
6316 }
6317}
6318
6319/*
6320 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
6321 *
6322 * Verifies that keys configured for no padding reject PKCS7 padding
6323 */
6324TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
6325 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6326 .TripleDesEncryptionKey(168)
6327 .BlockMode(BlockMode::ECB)
6328 .Authorization(TAG_NO_AUTH_REQUIRED)
6329 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00006330 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6331 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07006332}
6333
6334/*
6335 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
6336 *
6337 * Verifies that corrupted padding is detected.
6338 */
6339TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
6340 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6341 .TripleDesEncryptionKey(168)
6342 .BlockMode(BlockMode::ECB)
6343 .Authorization(TAG_NO_AUTH_REQUIRED)
6344 .Padding(PaddingMode::PKCS7)));
6345
6346 string message = "a";
6347 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
6348 EXPECT_EQ(8U, ciphertext.size());
6349 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006350
6351 AuthorizationSetBuilder begin_params;
6352 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
6353 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07006354
6355 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
6356 ++ciphertext[ciphertext.size() / 2];
6357
6358 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
6359 string plaintext;
6360 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6361 ErrorCode error = Finish(&plaintext);
6362 if (error == ErrorCode::INVALID_ARGUMENT) {
6363 // This is the expected error, we can exit the test now.
6364 return;
6365 } else {
6366 // Very small chance we got valid decryption, so try again.
6367 ASSERT_EQ(error, ErrorCode::OK);
6368 }
6369 }
6370 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006371}
6372
6373struct TripleDesTestVector {
6374 const char* name;
6375 const KeyPurpose purpose;
6376 const BlockMode block_mode;
6377 const PaddingMode padding_mode;
6378 const char* key;
6379 const char* iv;
6380 const char* input;
6381 const char* output;
6382};
6383
6384// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
6385// of the NIST vectors are multiples of the block size.
6386static const TripleDesTestVector kTripleDesTestVectors[] = {
6387 {
6388 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6389 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
6390 "", // IV
6391 "329d86bdf1bc5af4", // input
6392 "d946c2756d78633f", // output
6393 },
6394 {
6395 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6396 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
6397 "", // IV
6398 "6b1540781b01ce1997adae102dbf3c5b", // input
6399 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
6400 },
6401 {
6402 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6403 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
6404 "", // IV
6405 "6daad94ce08acfe7", // input
6406 "660e7d32dcc90e79", // output
6407 },
6408 {
6409 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6410 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
6411 "", // IV
6412 "e9653a0a1f05d31b9acd12d73aa9879d", // input
6413 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
6414 },
6415 {
6416 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6417 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
6418 "43f791134c5647ba", // IV
6419 "dcc153cef81d6f24", // input
6420 "92538bd8af18d3ba", // output
6421 },
6422 {
6423 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6424 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6425 "c2e999cb6249023c", // IV
6426 "c689aee38a301bb316da75db36f110b5", // input
6427 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
6428 },
6429 {
6430 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
6431 PaddingMode::PKCS7,
6432 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6433 "c2e999cb6249023c", // IV
6434 "c689aee38a301bb316da75db36f110b500", // input
6435 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
6436 },
6437 {
6438 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
6439 PaddingMode::PKCS7,
6440 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6441 "c2e999cb6249023c", // IV
6442 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
6443 "c689aee38a301bb316da75db36f110b500", // output
6444 },
6445 {
6446 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6447 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
6448 "41746c7e442d3681", // IV
6449 "c53a7b0ec40600fe", // input
6450 "d4f00eb455de1034", // output
6451 },
6452 {
6453 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6454 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
6455 "3982bc02c3727d45", // IV
6456 "6006f10adef52991fcc777a1238bbb65", // input
6457 "edae09288e9e3bc05746d872b48e3b29", // output
6458 },
6459};
6460
6461/*
6462 * EncryptionOperationsTest.TripleDesTestVector
6463 *
6464 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
6465 */
6466TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
6467 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
6468 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
6469 SCOPED_TRACE(test->name);
6470 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
6471 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
6472 hex2str(test->output));
6473 }
6474}
6475
6476/*
6477 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
6478 *
6479 * Validates CBC mode functionality.
6480 */
6481TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
6482 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6483 .TripleDesEncryptionKey(168)
6484 .BlockMode(BlockMode::CBC)
6485 .Authorization(TAG_NO_AUTH_REQUIRED)
6486 .Padding(PaddingMode::NONE)));
6487
6488 ASSERT_GT(key_blob_.size(), 0U);
6489
Brian J Murray734c8412022-01-13 14:55:30 -08006490 // Four-block message.
6491 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07006492 vector<uint8_t> iv1;
6493 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
6494 EXPECT_EQ(message.size(), ciphertext1.size());
6495
6496 vector<uint8_t> iv2;
6497 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
6498 EXPECT_EQ(message.size(), ciphertext2.size());
6499
6500 // IVs should be random, so ciphertexts should differ.
6501 EXPECT_NE(iv1, iv2);
6502 EXPECT_NE(ciphertext1, ciphertext2);
6503
6504 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
6505 EXPECT_EQ(message, plaintext);
6506}
6507
6508/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006509 * EncryptionOperationsTest.TripleDesInvalidCallerIv
6510 *
6511 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
6512 */
6513TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
6514 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6515 .TripleDesEncryptionKey(168)
6516 .BlockMode(BlockMode::CBC)
6517 .Authorization(TAG_NO_AUTH_REQUIRED)
6518 .Authorization(TAG_CALLER_NONCE)
6519 .Padding(PaddingMode::NONE)));
6520 auto params = AuthorizationSetBuilder()
6521 .BlockMode(BlockMode::CBC)
6522 .Padding(PaddingMode::NONE)
6523 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
6524 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6525}
6526
6527/*
Selene Huang31ab4042020-04-29 04:22:39 -07006528 * EncryptionOperationsTest.TripleDesCallerIv
6529 *
6530 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
6531 */
6532TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
6533 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6534 .TripleDesEncryptionKey(168)
6535 .BlockMode(BlockMode::CBC)
6536 .Authorization(TAG_NO_AUTH_REQUIRED)
6537 .Authorization(TAG_CALLER_NONCE)
6538 .Padding(PaddingMode::NONE)));
6539 string message = "1234567890123456";
6540 vector<uint8_t> iv;
6541 // Don't specify IV, should get a random one.
6542 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6543 EXPECT_EQ(message.size(), ciphertext1.size());
6544 EXPECT_EQ(8U, iv.size());
6545
6546 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6547 EXPECT_EQ(message, plaintext);
6548
6549 // Now specify an IV, should also work.
6550 iv = AidlBuf("abcdefgh");
6551 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
6552
6553 // Decrypt with correct IV.
6554 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
6555 EXPECT_EQ(message, plaintext);
6556
6557 // Now try with wrong IV.
6558 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
6559 EXPECT_NE(message, plaintext);
6560}
6561
6562/*
6563 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
6564 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01006565 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07006566 */
6567TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
6568 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6569 .TripleDesEncryptionKey(168)
6570 .BlockMode(BlockMode::CBC)
6571 .Authorization(TAG_NO_AUTH_REQUIRED)
6572 .Padding(PaddingMode::NONE)));
6573
6574 string message = "12345678901234567890123456789012";
6575 vector<uint8_t> iv;
6576 // Don't specify nonce, should get a random one.
6577 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6578 EXPECT_EQ(message.size(), ciphertext1.size());
6579 EXPECT_EQ(8U, iv.size());
6580
6581 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6582 EXPECT_EQ(message, plaintext);
6583
6584 // Now specify a nonce, should fail.
6585 auto input_params = AuthorizationSetBuilder()
6586 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
6587 .BlockMode(BlockMode::CBC)
6588 .Padding(PaddingMode::NONE);
6589 AuthorizationSet output_params;
6590 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
6591 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6592}
6593
6594/*
6595 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
6596 *
6597 * Verifies that 3DES ECB-only keys do not allow CBC usage.
6598 */
6599TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
6600 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6601 .TripleDesEncryptionKey(168)
6602 .BlockMode(BlockMode::ECB)
6603 .Authorization(TAG_NO_AUTH_REQUIRED)
6604 .Padding(PaddingMode::NONE)));
6605 // Two-block message.
6606 string message = "1234567890123456";
6607 auto begin_params =
6608 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6609 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6610}
6611
6612/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006613 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07006614 *
6615 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
6616 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01006617TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
6618 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
6619 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6620 .TripleDesEncryptionKey(168)
6621 .BlockMode(blockMode)
6622 .Authorization(TAG_NO_AUTH_REQUIRED)
6623 .Padding(PaddingMode::NONE)));
6624 // Message is slightly shorter than two blocks.
6625 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07006626
David Drysdaled2cc8c22021-04-15 13:29:45 +01006627 auto begin_params =
6628 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
6629 AuthorizationSet output_params;
6630 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
6631 string ciphertext;
6632 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
6633
6634 CheckedDeleteKey();
6635 }
Selene Huang31ab4042020-04-29 04:22:39 -07006636}
6637
6638/*
6639 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
6640 *
6641 * Verifies that PKCS7 padding works correctly in CBC mode.
6642 */
6643TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
6644 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6645 .TripleDesEncryptionKey(168)
6646 .BlockMode(BlockMode::CBC)
6647 .Authorization(TAG_NO_AUTH_REQUIRED)
6648 .Padding(PaddingMode::PKCS7)));
6649
6650 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08006651 for (size_t i = 0; i <= 32; i++) {
6652 SCOPED_TRACE(testing::Message() << "i = " << i);
6653 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
6654 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07006655 vector<uint8_t> iv;
6656 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6657 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6658 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
6659 EXPECT_EQ(message, plaintext);
6660 }
6661}
6662
6663/*
6664 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
6665 *
6666 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
6667 */
6668TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
6669 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6670 .TripleDesEncryptionKey(168)
6671 .BlockMode(BlockMode::CBC)
6672 .Authorization(TAG_NO_AUTH_REQUIRED)
6673 .Padding(PaddingMode::NONE)));
6674
6675 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08006676 for (size_t i = 0; i <= 32; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07006677 auto begin_params =
6678 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
6679 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6680 }
6681}
6682
6683/*
6684 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
6685 *
6686 * Verifies that corrupted PKCS7 padding is rejected during decryption.
6687 */
6688TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
6689 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6690 .TripleDesEncryptionKey(168)
6691 .BlockMode(BlockMode::CBC)
6692 .Authorization(TAG_NO_AUTH_REQUIRED)
6693 .Padding(PaddingMode::PKCS7)));
6694
6695 string message = "a";
6696 vector<uint8_t> iv;
6697 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6698 EXPECT_EQ(8U, ciphertext.size());
6699 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006700
6701 auto begin_params = AuthorizationSetBuilder()
6702 .BlockMode(BlockMode::CBC)
6703 .Padding(PaddingMode::PKCS7)
6704 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07006705
6706 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08006707 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07006708 ++ciphertext[ciphertext.size() / 2];
6709 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
6710 string plaintext;
6711 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6712 ErrorCode error = Finish(&plaintext);
6713 if (error == ErrorCode::INVALID_ARGUMENT) {
6714 // This is the expected error, we can exit the test now.
6715 return;
6716 } else {
6717 // Very small chance we got valid decryption, so try again.
6718 ASSERT_EQ(error, ErrorCode::OK);
6719 }
6720 }
6721 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006722}
6723
6724/*
6725 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
6726 *
6727 * Verifies that 3DES CBC works with many different input sizes.
6728 */
6729TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
6730 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6731 .TripleDesEncryptionKey(168)
6732 .BlockMode(BlockMode::CBC)
6733 .Authorization(TAG_NO_AUTH_REQUIRED)
6734 .Padding(PaddingMode::NONE)));
6735
6736 int increment = 7;
6737 string message(240, 'a');
6738 AuthorizationSet input_params =
6739 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6740 AuthorizationSet output_params;
6741 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6742
6743 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07006744 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006745 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006746 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
6747 EXPECT_EQ(message.size(), ciphertext.size());
6748
6749 // Move TAG_NONCE into input_params
6750 input_params = output_params;
6751 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
6752 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
6753 output_params.Clear();
6754
6755 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
6756 string plaintext;
6757 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006758 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006759 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
6760 EXPECT_EQ(ciphertext.size(), plaintext.size());
6761 EXPECT_EQ(message, plaintext);
6762}
6763
6764INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
6765
6766typedef KeyMintAidlTestBase MaxOperationsTest;
6767
6768/*
6769 * MaxOperationsTest.TestLimitAes
6770 *
6771 * Verifies that the max uses per boot tag works correctly with AES keys.
6772 */
6773TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006774 if (SecLevel() == SecurityLevel::STRONGBOX) {
6775 GTEST_SKIP() << "Test not applicable to StrongBox device";
6776 }
Selene Huang31ab4042020-04-29 04:22:39 -07006777
6778 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6779 .Authorization(TAG_NO_AUTH_REQUIRED)
6780 .AesEncryptionKey(128)
6781 .EcbMode()
6782 .Padding(PaddingMode::NONE)
6783 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
6784
6785 string message = "1234567890123456";
6786
6787 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6788
6789 EncryptMessage(message, params);
6790 EncryptMessage(message, params);
6791 EncryptMessage(message, params);
6792
6793 // Fourth time should fail.
6794 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
6795}
6796
6797/*
Qi Wud22ec842020-11-26 13:27:53 +08006798 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07006799 *
6800 * Verifies that the max uses per boot tag works correctly with RSA keys.
6801 */
6802TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006803 if (SecLevel() == SecurityLevel::STRONGBOX) {
6804 GTEST_SKIP() << "Test not applicable to StrongBox device";
6805 }
Selene Huang31ab4042020-04-29 04:22:39 -07006806
6807 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6808 .Authorization(TAG_NO_AUTH_REQUIRED)
6809 .RsaSigningKey(1024, 65537)
6810 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006811 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
6812 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006813
6814 string message = "1234567890123456";
6815
6816 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6817
6818 SignMessage(message, params);
6819 SignMessage(message, params);
6820 SignMessage(message, params);
6821
6822 // Fourth time should fail.
6823 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
6824}
6825
6826INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
6827
Qi Wud22ec842020-11-26 13:27:53 +08006828typedef KeyMintAidlTestBase UsageCountLimitTest;
6829
6830/*
Qi Wubeefae42021-01-28 23:16:37 +08006831 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006832 *
Qi Wubeefae42021-01-28 23:16:37 +08006833 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006834 */
Qi Wubeefae42021-01-28 23:16:37 +08006835TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006836 if (SecLevel() == SecurityLevel::STRONGBOX) {
6837 GTEST_SKIP() << "Test not applicable to StrongBox device";
6838 }
Qi Wud22ec842020-11-26 13:27:53 +08006839
6840 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6841 .Authorization(TAG_NO_AUTH_REQUIRED)
6842 .AesEncryptionKey(128)
6843 .EcbMode()
6844 .Padding(PaddingMode::NONE)
6845 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
6846
6847 // Check the usage count limit tag appears in the authorizations.
6848 AuthorizationSet auths;
6849 for (auto& entry : key_characteristics_) {
6850 auths.push_back(AuthorizationSet(entry.authorizations));
6851 }
6852 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6853 << "key usage count limit " << 1U << " missing";
6854
6855 string message = "1234567890123456";
6856 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6857
Qi Wubeefae42021-01-28 23:16:37 +08006858 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6859 AuthorizationSet keystore_auths =
6860 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6861
Qi Wud22ec842020-11-26 13:27:53 +08006862 // First usage of AES key should work.
6863 EncryptMessage(message, params);
6864
Qi Wud22ec842020-11-26 13:27:53 +08006865 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6866 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6867 // must be invalidated from secure storage (such as RPMB partition).
6868 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6869 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006870 // Usage count limit tag is enforced by keystore, keymint does nothing.
6871 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08006872 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6873 }
6874}
6875
6876/*
Qi Wubeefae42021-01-28 23:16:37 +08006877 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006878 *
Qi Wubeefae42021-01-28 23:16:37 +08006879 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006880 */
Qi Wubeefae42021-01-28 23:16:37 +08006881TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006882 if (SecLevel() == SecurityLevel::STRONGBOX) {
6883 GTEST_SKIP() << "Test not applicable to StrongBox device";
6884 }
Qi Wubeefae42021-01-28 23:16:37 +08006885
6886 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6887 .Authorization(TAG_NO_AUTH_REQUIRED)
6888 .AesEncryptionKey(128)
6889 .EcbMode()
6890 .Padding(PaddingMode::NONE)
6891 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
6892
6893 // Check the usage count limit tag appears in the authorizations.
6894 AuthorizationSet auths;
6895 for (auto& entry : key_characteristics_) {
6896 auths.push_back(AuthorizationSet(entry.authorizations));
6897 }
6898 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6899 << "key usage count limit " << 3U << " missing";
6900
6901 string message = "1234567890123456";
6902 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6903
6904 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6905 AuthorizationSet keystore_auths =
6906 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6907
6908 EncryptMessage(message, params);
6909 EncryptMessage(message, params);
6910 EncryptMessage(message, params);
6911
6912 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6913 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6914 // must be invalidated from secure storage (such as RPMB partition).
6915 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6916 } else {
6917 // Usage count limit tag is enforced by keystore, keymint does nothing.
6918 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
6919 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6920 }
6921}
6922
6923/*
6924 * UsageCountLimitTest.TestSingleUseRsa
6925 *
6926 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
6927 */
6928TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006929 if (SecLevel() == SecurityLevel::STRONGBOX) {
6930 GTEST_SKIP() << "Test not applicable to StrongBox device";
6931 }
Qi Wud22ec842020-11-26 13:27:53 +08006932
6933 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6934 .Authorization(TAG_NO_AUTH_REQUIRED)
6935 .RsaSigningKey(1024, 65537)
6936 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006937 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6938 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08006939
6940 // Check the usage count limit tag appears in the authorizations.
6941 AuthorizationSet auths;
6942 for (auto& entry : key_characteristics_) {
6943 auths.push_back(AuthorizationSet(entry.authorizations));
6944 }
6945 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6946 << "key usage count limit " << 1U << " missing";
6947
6948 string message = "1234567890123456";
6949 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6950
Qi Wubeefae42021-01-28 23:16:37 +08006951 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6952 AuthorizationSet keystore_auths =
6953 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6954
Qi Wud22ec842020-11-26 13:27:53 +08006955 // First usage of RSA key should work.
6956 SignMessage(message, params);
6957
Qi Wud22ec842020-11-26 13:27:53 +08006958 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6959 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6960 // must be invalidated from secure storage (such as RPMB partition).
6961 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6962 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006963 // Usage count limit tag is enforced by keystore, keymint does nothing.
6964 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
6965 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6966 }
6967}
6968
6969/*
6970 * UsageCountLimitTest.TestLimitUseRsa
6971 *
6972 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
6973 */
6974TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006975 if (SecLevel() == SecurityLevel::STRONGBOX) {
6976 GTEST_SKIP() << "Test not applicable to StrongBox device";
6977 }
Qi Wubeefae42021-01-28 23:16:37 +08006978
6979 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6980 .Authorization(TAG_NO_AUTH_REQUIRED)
6981 .RsaSigningKey(1024, 65537)
6982 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006983 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
6984 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08006985
6986 // Check the usage count limit tag appears in the authorizations.
6987 AuthorizationSet auths;
6988 for (auto& entry : key_characteristics_) {
6989 auths.push_back(AuthorizationSet(entry.authorizations));
6990 }
6991 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6992 << "key usage count limit " << 3U << " missing";
6993
6994 string message = "1234567890123456";
6995 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6996
6997 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6998 AuthorizationSet keystore_auths =
6999 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7000
7001 SignMessage(message, params);
7002 SignMessage(message, params);
7003 SignMessage(message, params);
7004
7005 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7006 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7007 // must be invalidated from secure storage (such as RPMB partition).
7008 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7009 } else {
7010 // Usage count limit tag is enforced by keystore, keymint does nothing.
7011 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08007012 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
7013 }
7014}
7015
Qi Wu8e727f72021-02-11 02:49:33 +08007016/*
7017 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7018 *
7019 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7020 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7021 * in hardware.
7022 */
7023TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01007024 if (SecLevel() == SecurityLevel::STRONGBOX) {
7025 GTEST_SKIP() << "Test not applicable to StrongBox device";
7026 }
Qi Wu8e727f72021-02-11 02:49:33 +08007027
7028 auto error = GenerateKey(AuthorizationSetBuilder()
7029 .RsaSigningKey(2048, 65537)
7030 .Digest(Digest::NONE)
7031 .Padding(PaddingMode::NONE)
7032 .Authorization(TAG_NO_AUTH_REQUIRED)
7033 .Authorization(TAG_ROLLBACK_RESISTANCE)
7034 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007035 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7036 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007037 }
David Drysdale513bf122021-10-06 11:53:13 +01007038
7039 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7040 ASSERT_EQ(ErrorCode::OK, error);
7041 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7042 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7043 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7044
7045 // The KeyMint should also enforce single use key in hardware when it supports rollback
7046 // resistance.
7047 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7048 .Authorization(TAG_NO_AUTH_REQUIRED)
7049 .RsaSigningKey(1024, 65537)
7050 .NoDigestOrPadding()
7051 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7052 .SetDefaultValidity()));
7053
7054 // Check the usage count limit tag appears in the hardware authorizations.
7055 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7056 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7057 << "key usage count limit " << 1U << " missing";
7058
7059 string message = "1234567890123456";
7060 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7061
7062 // First usage of RSA key should work.
7063 SignMessage(message, params);
7064
7065 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7066 // must be invalidated from secure storage (such as RPMB partition).
7067 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007068}
7069
Qi Wud22ec842020-11-26 13:27:53 +08007070INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7071
David Drysdale7de9feb2021-03-05 14:56:19 +00007072typedef KeyMintAidlTestBase GetHardwareInfoTest;
7073
7074TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7075 // Retrieving hardware info should give the same result each time.
7076 KeyMintHardwareInfo info;
7077 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7078 KeyMintHardwareInfo info2;
7079 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7080 EXPECT_EQ(info, info2);
7081}
7082
7083INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7084
Selene Huang31ab4042020-04-29 04:22:39 -07007085typedef KeyMintAidlTestBase AddEntropyTest;
7086
7087/*
7088 * AddEntropyTest.AddEntropy
7089 *
7090 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7091 * is actually added.
7092 */
7093TEST_P(AddEntropyTest, AddEntropy) {
7094 string data = "foo";
7095 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7096}
7097
7098/*
7099 * AddEntropyTest.AddEmptyEntropy
7100 *
7101 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7102 */
7103TEST_P(AddEntropyTest, AddEmptyEntropy) {
7104 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7105}
7106
7107/*
7108 * AddEntropyTest.AddLargeEntropy
7109 *
7110 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7111 */
7112TEST_P(AddEntropyTest, AddLargeEntropy) {
7113 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7114}
7115
David Drysdalebb3d85e2021-04-13 11:15:51 +01007116/*
7117 * AddEntropyTest.AddTooLargeEntropy
7118 *
7119 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7120 */
7121TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7122 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7123 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7124}
7125
Selene Huang31ab4042020-04-29 04:22:39 -07007126INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7127
Selene Huang31ab4042020-04-29 04:22:39 -07007128typedef KeyMintAidlTestBase KeyDeletionTest;
7129
7130/**
7131 * KeyDeletionTest.DeleteKey
7132 *
7133 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7134 * valid key blob.
7135 */
7136TEST_P(KeyDeletionTest, DeleteKey) {
7137 auto error = GenerateKey(AuthorizationSetBuilder()
7138 .RsaSigningKey(2048, 65537)
7139 .Digest(Digest::NONE)
7140 .Padding(PaddingMode::NONE)
7141 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007142 .Authorization(TAG_ROLLBACK_RESISTANCE)
7143 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007144 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7145 GTEST_SKIP() << "Rollback resistance not supported";
7146 }
Selene Huang31ab4042020-04-29 04:22:39 -07007147
7148 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007149 ASSERT_EQ(ErrorCode::OK, error);
7150 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7151 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007152
David Drysdale513bf122021-10-06 11:53:13 +01007153 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007154
David Drysdale513bf122021-10-06 11:53:13 +01007155 string message = "12345678901234567890123456789012";
7156 AuthorizationSet begin_out_params;
7157 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7158 Begin(KeyPurpose::SIGN, key_blob_,
7159 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7160 &begin_out_params));
7161 AbortIfNeeded();
7162 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007163}
7164
7165/**
7166 * KeyDeletionTest.DeleteInvalidKey
7167 *
7168 * This test checks that the HAL excepts invalid key blobs..
7169 */
7170TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7171 // Generate key just to check if rollback protection is implemented
7172 auto error = GenerateKey(AuthorizationSetBuilder()
7173 .RsaSigningKey(2048, 65537)
7174 .Digest(Digest::NONE)
7175 .Padding(PaddingMode::NONE)
7176 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007177 .Authorization(TAG_ROLLBACK_RESISTANCE)
7178 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007179 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7180 GTEST_SKIP() << "Rollback resistance not supported";
7181 }
Selene Huang31ab4042020-04-29 04:22:39 -07007182
7183 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007184 ASSERT_EQ(ErrorCode::OK, error);
7185 AuthorizationSet enforced(SecLevelAuthorizations());
7186 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007187
David Drysdale513bf122021-10-06 11:53:13 +01007188 // Delete the key we don't care about the result at this point.
7189 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007190
David Drysdale513bf122021-10-06 11:53:13 +01007191 // Now create an invalid key blob and delete it.
7192 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007193
David Drysdale513bf122021-10-06 11:53:13 +01007194 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007195}
7196
7197/**
7198 * KeyDeletionTest.DeleteAllKeys
7199 *
7200 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7201 *
7202 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7203 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7204 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7205 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7206 * credentials stored in Keystore/Keymint.
7207 */
7208TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007209 if (!arm_deleteAllKeys) {
7210 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7211 return;
7212 }
Selene Huang31ab4042020-04-29 04:22:39 -07007213 auto error = GenerateKey(AuthorizationSetBuilder()
7214 .RsaSigningKey(2048, 65537)
7215 .Digest(Digest::NONE)
7216 .Padding(PaddingMode::NONE)
7217 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007218 .Authorization(TAG_ROLLBACK_RESISTANCE)
7219 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007220 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7221 GTEST_SKIP() << "Rollback resistance not supported";
7222 }
Selene Huang31ab4042020-04-29 04:22:39 -07007223
7224 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007225 ASSERT_EQ(ErrorCode::OK, error);
7226 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7227 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007228
David Drysdale513bf122021-10-06 11:53:13 +01007229 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007230
David Drysdale513bf122021-10-06 11:53:13 +01007231 string message = "12345678901234567890123456789012";
7232 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07007233
David Drysdale513bf122021-10-06 11:53:13 +01007234 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7235 Begin(KeyPurpose::SIGN, key_blob_,
7236 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7237 &begin_out_params));
7238 AbortIfNeeded();
7239 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007240}
7241
7242INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
7243
David Drysdaled2cc8c22021-04-15 13:29:45 +01007244typedef KeyMintAidlTestBase KeyUpgradeTest;
7245
7246/**
7247 * KeyUpgradeTest.UpgradeInvalidKey
7248 *
7249 * This test checks that the HAL excepts invalid key blobs..
7250 */
7251TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
7252 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
7253
7254 std::vector<uint8_t> new_blob;
7255 Status result = keymint_->upgradeKey(key_blob,
7256 AuthorizationSetBuilder()
7257 .Authorization(TAG_APPLICATION_ID, "clientid")
7258 .Authorization(TAG_APPLICATION_DATA, "appdata")
7259 .vector_data(),
7260 &new_blob);
7261 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
7262}
7263
7264INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
7265
Selene Huang31ab4042020-04-29 04:22:39 -07007266using UpgradeKeyTest = KeyMintAidlTestBase;
7267
7268/*
7269 * UpgradeKeyTest.UpgradeKey
7270 *
7271 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
7272 */
7273TEST_P(UpgradeKeyTest, UpgradeKey) {
7274 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7275 .AesEncryptionKey(128)
7276 .Padding(PaddingMode::NONE)
7277 .Authorization(TAG_NO_AUTH_REQUIRED)));
7278
7279 auto result = UpgradeKey(key_blob_);
7280
7281 // Key doesn't need upgrading. Should get okay, but no new key blob.
7282 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
7283}
7284
7285INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
7286
7287using ClearOperationsTest = KeyMintAidlTestBase;
7288
7289/*
7290 * ClearSlotsTest.TooManyOperations
7291 *
7292 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
7293 * operations are started without being finished or aborted. Also verifies
7294 * that aborting the operations clears the operations.
7295 *
7296 */
7297TEST_P(ClearOperationsTest, TooManyOperations) {
7298 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7299 .Authorization(TAG_NO_AUTH_REQUIRED)
7300 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08007301 .Padding(PaddingMode::NONE)
7302 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007303
7304 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
7305 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08007306 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07007307 AuthorizationSet out_params;
7308 ErrorCode result;
7309 size_t i;
7310
7311 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00007312 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07007313 if (ErrorCode::OK != result) {
7314 break;
7315 }
7316 }
7317 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
7318 // Try again just in case there's a weird overflow bug
7319 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00007320 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007321 for (size_t j = 0; j < i; j++) {
7322 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
7323 << "Aboort failed for i = " << j << std::endl;
7324 }
subrahmanyaman05642492022-02-05 07:10:56 +00007325 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007326 AbortIfNeeded();
7327}
7328
7329INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
7330
7331typedef KeyMintAidlTestBase TransportLimitTest;
7332
7333/*
David Drysdale7de9feb2021-03-05 14:56:19 +00007334 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07007335 *
7336 * Verifies that passing input data to finish succeeds as expected.
7337 */
7338TEST_P(TransportLimitTest, LargeFinishInput) {
7339 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7340 .Authorization(TAG_NO_AUTH_REQUIRED)
7341 .AesEncryptionKey(128)
7342 .BlockMode(BlockMode::ECB)
7343 .Padding(PaddingMode::NONE)));
7344
7345 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
7346 auto cipher_params =
7347 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7348
7349 AuthorizationSet out_params;
7350 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
7351
7352 string plain_message = std::string(1 << msg_size, 'x');
7353 string encrypted_message;
7354 auto rc = Finish(plain_message, &encrypted_message);
7355
7356 EXPECT_EQ(ErrorCode::OK, rc);
7357 EXPECT_EQ(plain_message.size(), encrypted_message.size())
7358 << "Encrypt finish returned OK, but did not consume all of the given input";
7359 cipher_params.push_back(out_params);
7360
7361 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
7362
7363 string decrypted_message;
7364 rc = Finish(encrypted_message, &decrypted_message);
7365 EXPECT_EQ(ErrorCode::OK, rc);
7366 EXPECT_EQ(plain_message.size(), decrypted_message.size())
7367 << "Decrypt finish returned OK, did not consume all of the given input";
7368 }
7369}
7370
7371INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
7372
Seth Moored79a0ec2021-12-13 20:03:33 +00007373static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05007374 switch (curve) {
7375 case EcCurve::P_224:
7376 return NID_secp224r1;
7377 case EcCurve::P_256:
7378 return NID_X9_62_prime256v1;
7379 case EcCurve::P_384:
7380 return NID_secp384r1;
7381 case EcCurve::P_521:
7382 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00007383 case EcCurve::CURVE_25519:
7384 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05007385 }
7386}
7387
David Drysdale42fe1892021-10-14 14:43:46 +01007388class KeyAgreementTest : public KeyMintAidlTestBase {
7389 protected:
7390 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
7391 std::vector<uint8_t>* localPublicKey) {
7392 // Generate EC key locally (with access to private key material)
7393 if (localCurve == EcCurve::CURVE_25519) {
7394 uint8_t privKeyData[32];
7395 uint8_t pubKeyData[32];
7396 X25519_keypair(pubKeyData, privKeyData);
7397 *localPublicKey = vector<uint8_t>(pubKeyData, pubKeyData + 32);
7398 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
7399 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
7400 } else {
7401 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
7402 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
7403 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
7404 ASSERT_NE(group, nullptr);
7405 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
7406 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
7407 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
7408 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
7409
7410 // Get encoded form of the public part of the locally generated key...
7411 unsigned char* p = nullptr;
7412 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
7413 ASSERT_GT(localPublicKeySize, 0);
7414 *localPublicKey =
7415 vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
7416 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
7417 OPENSSL_free(p);
7418 }
7419 }
7420
7421 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
7422 vector<uint8_t> challenge = {0x41, 0x42};
7423 ErrorCode result =
7424 GenerateKey(AuthorizationSetBuilder()
7425 .Authorization(TAG_NO_AUTH_REQUIRED)
7426 .Authorization(TAG_EC_CURVE, curve)
7427 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7428 .Authorization(TAG_ALGORITHM, Algorithm::EC)
7429 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
7430 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
7431 .SetDefaultValidity());
7432 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
7433 ASSERT_GT(cert_chain_.size(), 0);
7434 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7435 ASSERT_NE(kmKeyCert, nullptr);
7436 // Check that keyAgreement (bit 4) is set in KeyUsage
7437 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
7438 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
7439 ASSERT_NE(*kmPubKey, nullptr);
7440 if (dump_Attestations) {
7441 for (size_t n = 0; n < cert_chain_.size(); n++) {
7442 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
7443 }
7444 }
7445 }
7446
7447 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
7448 const std::vector<uint8_t>& localPublicKey) {
7449 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7450 string ZabFromKeyMintStr;
7451 ASSERT_EQ(ErrorCode::OK,
7452 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
7453 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
7454 vector<uint8_t> ZabFromTest;
7455
7456 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
7457 size_t kmPubKeySize = 32;
7458 uint8_t kmPubKeyData[32];
7459 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7460 ASSERT_EQ(kmPubKeySize, 32);
7461
7462 uint8_t localPrivKeyData[32];
7463 size_t localPrivKeySize = 32;
7464 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
7465 &localPrivKeySize));
7466 ASSERT_EQ(localPrivKeySize, 32);
7467
7468 uint8_t sharedKey[32];
7469 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
7470 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
7471 } else {
7472 // Perform local ECDH between the two keys so we can check if we get the same Zab..
7473 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
7474 ASSERT_NE(ctx, nullptr);
7475 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
7476 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
7477 size_t ZabFromTestLen = 0;
7478 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
7479 ZabFromTest.resize(ZabFromTestLen);
7480 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
7481 }
7482 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
7483 }
7484};
7485
David Zeuthene0c40892021-01-08 12:54:11 -05007486/*
7487 * KeyAgreementTest.Ecdh
7488 *
David Drysdale42fe1892021-10-14 14:43:46 +01007489 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05007490 */
7491TEST_P(KeyAgreementTest, Ecdh) {
7492 // Because it's possible to use this API with keys on different curves, we
7493 // check all N^2 combinations where N is the number of supported
7494 // curves.
7495 //
7496 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
7497 // lot more curves we can be smart about things and just pick |otherCurve| so
7498 // it's not |curve| and that way we end up with only 2*N runs
7499 //
7500 for (auto curve : ValidCurves()) {
7501 for (auto localCurve : ValidCurves()) {
7502 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007503 EVP_PKEY_Ptr localPrivKey;
7504 vector<uint8_t> localPublicKey;
7505 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007506
7507 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007508 EVP_PKEY_Ptr kmPubKey;
7509 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007510
7511 // Now that we have the two keys, we ask KeyMint to perform ECDH...
7512 if (curve != localCurve) {
7513 // If the keys are using different curves KeyMint should fail with
7514 // ErrorCode:INVALID_ARGUMENT. Check that.
7515 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7516 string ZabFromKeyMintStr;
7517 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01007518 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05007519 &ZabFromKeyMintStr));
7520
7521 } else {
7522 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01007523 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007524 }
7525
7526 CheckedDeleteKey();
7527 }
7528 }
7529}
7530
David Drysdale42fe1892021-10-14 14:43:46 +01007531/*
7532 * KeyAgreementTest.EcdhCurve25519
7533 *
7534 * Verifies that ECDH works for curve25519. This is also covered by the general
7535 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
7536 * KeyMint 1.0.
7537 */
7538TEST_P(KeyAgreementTest, EcdhCurve25519) {
7539 if (!Curve25519Supported()) {
7540 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7541 }
7542
7543 // Generate EC key in KeyMint (only access to public key material)
7544 EcCurve curve = EcCurve::CURVE_25519;
7545 EVP_PKEY_Ptr kmPubKey = nullptr;
7546 GenerateKeyMintEcKey(curve, &kmPubKey);
7547
7548 // Generate EC key on same curve locally (with access to private key material).
7549 EVP_PKEY_Ptr privKey;
7550 vector<uint8_t> encodedPublicKey;
7551 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7552
7553 // Agree on a key between local and KeyMint and check it.
7554 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7555
7556 CheckedDeleteKey();
7557}
7558
7559/*
7560 * KeyAgreementTest.EcdhCurve25519Imported
7561 *
7562 * Verifies that ECDH works for an imported curve25519 key.
7563 */
7564TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
7565 if (!Curve25519Supported()) {
7566 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7567 }
7568
7569 // Import x25519 key into KeyMint.
7570 EcCurve curve = EcCurve::CURVE_25519;
7571 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
7572 .Authorization(TAG_NO_AUTH_REQUIRED)
7573 .EcdsaKey(EcCurve::CURVE_25519)
7574 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7575 .SetDefaultValidity(),
7576 KeyFormat::PKCS8, x25519_pkcs8_key));
7577 ASSERT_GT(cert_chain_.size(), 0);
7578 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7579 ASSERT_NE(kmKeyCert, nullptr);
7580 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
7581 ASSERT_NE(kmPubKey.get(), nullptr);
7582
7583 // Expect the import to emit corresponding public key data.
7584 size_t kmPubKeySize = 32;
7585 uint8_t kmPubKeyData[32];
7586 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7587 ASSERT_EQ(kmPubKeySize, 32);
7588 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
7589 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
7590
7591 // Generate EC key on same curve locally (with access to private key material).
7592 EVP_PKEY_Ptr privKey;
7593 vector<uint8_t> encodedPublicKey;
7594 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7595
7596 // Agree on a key between local and KeyMint and check it.
7597 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7598
7599 CheckedDeleteKey();
7600}
7601
7602/*
7603 * KeyAgreementTest.EcdhCurve25519InvalidSize
7604 *
7605 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
7606 */
7607TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
7608 if (!Curve25519Supported()) {
7609 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7610 }
7611
7612 // Generate EC key in KeyMint (only access to public key material)
7613 EcCurve curve = EcCurve::CURVE_25519;
7614 EVP_PKEY_Ptr kmPubKey = nullptr;
7615 GenerateKeyMintEcKey(curve, &kmPubKey);
7616
7617 // Generate EC key on same curve locally (with access to private key material).
7618 EVP_PKEY_Ptr privKey;
7619 vector<uint8_t> encodedPublicKey;
7620 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7621
7622 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7623 string ZabFromKeyMintStr;
7624 // Send in an incomplete public key.
7625 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
7626 &ZabFromKeyMintStr));
7627
7628 CheckedDeleteKey();
7629}
7630
7631/*
7632 * KeyAgreementTest.EcdhCurve25519Mismatch
7633 *
7634 * Verifies that ECDH fails between curve25519 and other curves.
7635 */
7636TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
7637 if (!Curve25519Supported()) {
7638 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7639 }
7640
7641 // Generate EC key in KeyMint (only access to public key material)
7642 EcCurve curve = EcCurve::CURVE_25519;
7643 EVP_PKEY_Ptr kmPubKey = nullptr;
7644 GenerateKeyMintEcKey(curve, &kmPubKey);
7645
7646 for (auto localCurve : ValidCurves()) {
7647 if (localCurve == curve) {
7648 continue;
7649 }
7650 // Generate EC key on a different curve locally (with access to private key material).
7651 EVP_PKEY_Ptr privKey;
7652 vector<uint8_t> encodedPublicKey;
7653 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
7654
7655 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7656 string ZabFromKeyMintStr;
7657 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
7658 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
7659 &ZabFromKeyMintStr));
7660 }
7661
7662 CheckedDeleteKey();
7663}
7664
David Zeuthene0c40892021-01-08 12:54:11 -05007665INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
7666
David Drysdaled2cc8c22021-04-15 13:29:45 +01007667using DestroyAttestationIdsTest = KeyMintAidlTestBase;
7668
7669// This is a problematic test, as it can render the device under test permanently unusable.
7670// Re-enable and run at your own risk.
7671TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
7672 auto result = DestroyAttestationIds();
7673 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
7674}
7675
7676INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
7677
Shawn Willdend659c7c2021-02-19 14:51:51 -07007678using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007679
David Drysdaledb0dcf52021-05-18 11:43:31 +01007680/*
7681 * EarlyBootKeyTest.CreateEarlyBootKeys
7682 *
7683 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
7684 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007685TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01007686 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007687 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7688 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7689
David Drysdaleadfe6112021-05-27 12:00:53 +01007690 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
7691 ASSERT_GT(keyData.blob.size(), 0U);
7692 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7693 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7694 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007695 CheckedDeleteKey(&aesKeyData.blob);
7696 CheckedDeleteKey(&hmacKeyData.blob);
7697 CheckedDeleteKey(&rsaKeyData.blob);
7698 CheckedDeleteKey(&ecdsaKeyData.blob);
7699}
7700
David Drysdaledb0dcf52021-05-18 11:43:31 +01007701/*
David Drysdaleadfe6112021-05-27 12:00:53 +01007702 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
7703 *
7704 * Verifies that creating an early boot key with attestation succeeds.
7705 */
7706TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
7707 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
7708 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
7709 builder->AttestationChallenge("challenge");
7710 builder->AttestationApplicationId("app_id");
7711 });
7712
7713 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00007714 // Strongbox may not support factory attestation. Key creation might fail with
7715 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
7716 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
7717 continue;
7718 }
David Drysdaleadfe6112021-05-27 12:00:53 +01007719 ASSERT_GT(keyData.blob.size(), 0U);
7720 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7721 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7722 }
7723 CheckedDeleteKey(&aesKeyData.blob);
7724 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00007725 if (rsaKeyData.blob.size() != 0U) {
7726 CheckedDeleteKey(&rsaKeyData.blob);
7727 }
7728 if (ecdsaKeyData.blob.size() != 0U) {
7729 CheckedDeleteKey(&ecdsaKeyData.blob);
7730 }
David Drysdaleadfe6112021-05-27 12:00:53 +01007731}
7732
7733/*
7734 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01007735 *
7736 * Verifies that using early boot keys at a later stage fails.
7737 */
7738TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
7739 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7740 .Authorization(TAG_NO_AUTH_REQUIRED)
7741 .Authorization(TAG_EARLY_BOOT_ONLY)
7742 .HmacKey(128)
7743 .Digest(Digest::SHA_2_256)
7744 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
7745 AuthorizationSet output_params;
7746 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
7747 AuthorizationSetBuilder()
7748 .Digest(Digest::SHA_2_256)
7749 .Authorization(TAG_MAC_LENGTH, 256),
7750 &output_params));
7751}
7752
7753/*
7754 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
7755 *
7756 * Verifies that importing early boot keys fails.
7757 */
7758TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
7759 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
7760 .Authorization(TAG_NO_AUTH_REQUIRED)
7761 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01007762 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01007763 .Digest(Digest::SHA_2_256)
7764 .SetDefaultValidity(),
7765 KeyFormat::PKCS8, ec_256_key));
7766}
7767
David Drysdaled2cc8c22021-04-15 13:29:45 +01007768// 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 +00007769// boot stage, which no proper Android device is by the time we can run VTS. To use this,
7770// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
7771// early boot, so you'll have to reboot between runs.
7772TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
7773 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7774 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7775 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
7776 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7777 EXPECT_TRUE(
7778 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7779 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7780 EXPECT_TRUE(
7781 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7782
7783 // Should be able to use keys, since early boot has not ended
7784 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7785 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
7786 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
7787 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
7788
7789 // End early boot
7790 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
7791 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
7792
7793 // Should not be able to use already-created keys.
7794 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
7795 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
7796 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
7797 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
7798
7799 CheckedDeleteKey(&aesKeyData.blob);
7800 CheckedDeleteKey(&hmacKeyData.blob);
7801 CheckedDeleteKey(&rsaKeyData.blob);
7802 CheckedDeleteKey(&ecdsaKeyData.blob);
7803
7804 // Should not be able to create new keys
7805 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
7806 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
7807
7808 CheckedDeleteKey(&aesKeyData.blob);
7809 CheckedDeleteKey(&hmacKeyData.blob);
7810 CheckedDeleteKey(&rsaKeyData.blob);
7811 CheckedDeleteKey(&ecdsaKeyData.blob);
7812}
Shawn Willdend659c7c2021-02-19 14:51:51 -07007813
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007814INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
7815
Shawn Willdend659c7c2021-02-19 14:51:51 -07007816using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007817
7818// This may be a problematic test. It can't be run repeatedly without unlocking the device in
7819// between runs... and on most test devices there are no enrolled credentials so it can't be
7820// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
7821// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
7822// a manual test process, which includes unlocking between runs, which is why it's included here.
7823// Well, that and the fact that it's the only test we can do without also making calls into the
7824// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
7825// implications might be, so that may or may not be a solution.
7826TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
7827 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7828 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
7829
7830 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7831 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
7832 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
7833 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
7834
7835 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01007836 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007837 ASSERT_EQ(ErrorCode::OK, rc);
7838 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
7839 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
7840 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
7841 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
7842
7843 CheckedDeleteKey(&aesKeyData.blob);
7844 CheckedDeleteKey(&hmacKeyData.blob);
7845 CheckedDeleteKey(&rsaKeyData.blob);
7846 CheckedDeleteKey(&ecdsaKeyData.blob);
7847}
Shawn Willdend659c7c2021-02-19 14:51:51 -07007848
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007849INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
7850
Janis Danisevskis24c04702020-12-16 18:28:39 -08007851} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07007852
7853int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07007854 std::cout << "Testing ";
7855 auto halInstances =
7856 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
7857 std::cout << "HAL instances:\n";
7858 for (auto& entry : halInstances) {
7859 std::cout << " " << entry << '\n';
7860 }
7861
Selene Huang31ab4042020-04-29 04:22:39 -07007862 ::testing::InitGoogleTest(&argc, argv);
7863 for (int i = 1; i < argc; ++i) {
7864 if (argv[i][0] == '-') {
7865 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07007866 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
7867 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07007868 }
7869 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07007870 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
7871 dump_Attestations = true;
7872 } else {
7873 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07007874 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00007875 if (std::string(argv[i]) == "--skip_boot_pl_check") {
7876 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
7877 // be run in emulated environments that don't have the normal bootloader
7878 // interactions.
7879 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
7880 }
Selene Huang31ab4042020-04-29 04:22:39 -07007881 }
7882 }
Shawn Willden08a7e432020-12-11 13:05:27 +00007883 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07007884}