blob: 4a32c2f37bc14641f43187223964d7056cb3c8f3 [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
David Drysdale37af4b32021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Drysdale42fe1892021-10-14 14:43:46 +010025#include <openssl/curve25519.h>
David Zeuthene0c40892021-01-08 12:54:11 -050026#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070027#include <openssl/evp.h>
28#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050029#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070030
31#include <cutils/properties.h>
32
David Drysdale4dc01072021-04-01 12:17:35 +010033#include <android/binder_manager.h>
34
35#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080036#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070037
Shawn Willden08a7e432020-12-11 13:05:27 +000038#include <keymint_support/key_param_output.h>
39#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070040
41#include "KeyMintAidlTestBase.h"
42
Janis Danisevskis24c04702020-12-16 18:28:39 -080043using aidl::android::hardware::security::keymint::AuthorizationSet;
44using aidl::android::hardware::security::keymint::KeyCharacteristics;
45using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070046
Selene Huang31ab4042020-04-29 04:22:39 -070047namespace std {
48
Janis Danisevskis24c04702020-12-16 18:28:39 -080049using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070050
51template <>
52struct std::equal_to<KeyCharacteristics> {
53 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070054 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070055
Shawn Willden7f424372021-01-10 18:06:50 -070056 // this isn't very efficient. Oh, well.
57 AuthorizationSet a_auths(a.authorizations);
58 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070059
Shawn Willden7f424372021-01-10 18:06:50 -070060 a_auths.Sort();
61 b_auths.Sort();
62
63 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070064 }
65};
66
67} // namespace std
68
Janis Danisevskis24c04702020-12-16 18:28:39 -080069namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000070
Selene Huang31ab4042020-04-29 04:22:39 -070071namespace {
72
David Drysdalefeab5d92022-01-06 15:46:23 +000073// Maximum supported Ed25519 message size.
74const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
75
David Drysdaledbbbe2e2021-12-02 07:44:23 +000076// Whether to check that BOOT_PATCHLEVEL is populated.
77bool check_boot_pl = true;
78
Seth Moore7a55ae32021-06-23 14:28:11 -070079// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000080// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070081// is a small (roughly 1/256) chance that corrupting ciphertext still results
82// in valid PKCS7 padding.
83constexpr size_t kMaxPaddingCorruptionRetries = 8;
84
Selene Huang31ab4042020-04-29 04:22:39 -070085template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000086bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
87 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070088 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080089 if (auto p = authorizationValue(ttag, param)) {
90 return *p == expected_value;
91 }
92 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070093 });
94 return (it != set.end());
95}
96
97template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000098bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070099 auto it = std::find_if(set.begin(), set.end(),
100 [&](const KeyParameter& param) { return param.tag == tag; });
101 return (it != set.end());
102}
103
104constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
108 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
110 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
111 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
114 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
115 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
117 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
120
121string hex2str(string a) {
122 string b;
123 size_t num = a.size() / 2;
124 b.resize(num);
125 for (size_t i = 0; i < num; i++) {
126 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
127 }
128 return b;
129}
130
David Drysdaled2cc8c22021-04-15 13:29:45 +0100131string rsa_key = hex2str(
132 // RFC 5208 s5
133 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
134 "020100" // INTEGER length 1 value 0x00 (version)
135 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
136 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
137 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
138 "0500" // NULL (parameters)
139 // } end SEQUENCE (AlgorithmIdentifier)
140 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
141 // RFC 8017 A.1.2
142 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
143 "020100" // INTEGER length 1 value 0x00 (version)
144 "028181" // INTEGER length 0x81 value (modulus) ...
145 "00c6095409047d8634812d5a218176e4"
146 "5c41d60a75b13901f234226cffe77652"
147 "1c5a77b9e389417b71c0b6a44d13afe4"
148 "e4a2805d46c9da2935adb1ff0c1f24ea"
149 "06e62b20d776430a4d435157233c6f91"
150 "6783c30e310fcbd89b85c2d567711697"
151 "85ac12bca244abda72bfb19fc44d27c8"
152 "1e1d92de284f4061edfd99280745ea6d"
153 "25"
154 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
155 "028180" // INTEGER length 0x80 (privateExponent) value...
156 "1be0f04d9cae3718691f035338308e91"
157 "564b55899ffb5084d2460e6630257e05"
158 "b3ceab02972dfabcd6ce5f6ee2589eb6"
159 "7911ed0fac16e43a444b8c861e544a05"
160 "93365772f8baf6b22fc9e3c5f1024b06"
161 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
162 "ace7240290bef16c0b3f7f3cdd64ce3a"
163 "b5912cf6e32f39ab188358afcccd8081"
164 "0241" // INTEGER length 0x41 (prime1)
165 "00e4b49ef50f765d3b24dde01aceaaf1"
166 "30f2c76670a91a61ae08af497b4a82be"
167 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
168 "8c92bfab137fba2285227b83c342ff7c"
169 "55"
170 "0241" // INTEGER length 0x41 (prime2)
171 "00ddabb5839c4c7f6bf3d4183231f005"
172 "b31aa58affdda5c79e4cce217f6bc930"
173 "dbe563d480706c24e9ebfcab28a6cdef"
174 "d324b77e1bf7251b709092c24ff501fd"
175 "91"
176 "0240" // INTEGER length 0x40 (exponent1)
177 "23d4340eda3445d8cd26c14411da6fdc"
178 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
179 "842c1d280405bc2f6c1bea214a1d742a"
180 "b996b35b63a82a5e470fa88dbf823cdd"
181 "0240" // INTEGER length 0x40 (exponent2)
182 "1b7b57449ad30d1518249a5f56bb9829"
183 "4d4b6ac12ffc86940497a5a5837a6cf9"
184 "46262b494526d328c11e1126380fde04"
185 "c24f916dec250892db09a6d77cdba351"
186 "0240" // INTEGER length 0x40 (coefficient)
187 "7762cd8f4d050da56bd591adb515d24d"
188 "7ccd32cca0d05f866d583514bd7324d5"
189 "f33645e8ed8b4a1cb3cc4a1d67987399"
190 "f2a09f5b3fb68c88d5e5d90ac33492d6"
191 // } end SEQUENCE (PrivateKey)
192 // } end SEQUENCE (PrivateKeyInfo)
193);
Selene Huang31ab4042020-04-29 04:22:39 -0700194
Selene Huange5727e62021-04-13 22:41:20 -0700195/*
196 * DER-encoded PKCS#8 format RSA key. Generated using:
197 *
198 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
199 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100200string rsa_2048_key = hex2str(
201 // RFC 5208 s5
202 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
203 "020100" // INTEGER length 1 value 0x00 (version)
204 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
205 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
206 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
207 "0500" // NULL (parameters)
208 // } end SEQUENCE (AlgorithmIdentifier)
209 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
210 // RFC 8017 A.1.2
211 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
212 "020100" // INTEGER length 1 value 0x00 (version)
213 "02820101" // INTEGER length 0x101 value (modulus) ...
214 "00BEBC342B56D443B1299F9A6A7056E8"
215 "0A897E318476A5A18029E63B2ED739A6"
216 "1791D339F58DC763D9D14911F2EDEC38"
217 "3DEE11F6319B44510E7A3ECD9B79B973"
218 "82E49500ACF8117DC89CAF0E621F7775"
219 "6554A2FD4664BFE7AB8B59AB48340DBF"
220 "A27B93B5A81F6ECDEB02D0759307128D"
221 "F3E3BAD4055C8B840216DFAA5700670E"
222 "6C5126F0962FCB70FF308F25049164CC"
223 "F76CC2DA66A7DD9A81A714C2809D6918"
224 "6133D29D84568E892B6FFBF3199BDB14"
225 "383EE224407F190358F111A949552ABA"
226 "6714227D1BD7F6B20DD0CB88F9467B71"
227 "9339F33BFF35B3870B3F62204E4286B0"
228 "948EA348B524544B5F9838F29EE643B0"
229 "79EEF8A713B220D7806924CDF7295070"
230 "C5"
231 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
232 "02820100" // INTEGER length 0x100 (privateExponent) value...
233 "69F377F35F2F584EF075353CCD1CA997"
234 "38DB3DBC7C7FF35F9366CE176DFD1B13"
235 "5AB10030344ABF5FBECF1D4659FDEF1C"
236 "0FC430834BE1BE3911951377BB3D563A"
237 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
238 "2686C7B4B3C09A7B8354133E6F93F790"
239 "D59EAEB92E84C9A4339302CCE28FDF04"
240 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
241 "6AB706645BF074A4E4090D06FB163124"
242 "365FD5EE7A20D350E9958CC30D91326E"
243 "1B292E9EF5DB408EC42DAF737D201497"
244 "04D0A678A0FB5B5446863B099228A352"
245 "D604BA8091A164D01D5AB05397C71EAD"
246 "20BE2A08FC528FE442817809C787FEE4"
247 "AB97F97B9130D022153EDC6EB6CBE7B0"
248 "F8E3473F2E901209B5DB10F93604DB01"
249 "028181" // INTEGER length 0x81 (prime1)
250 "00E83C0998214941EA4F9293F1B77E2E"
251 "99E6CF305FAF358238E126124FEAF2EB"
252 "9724B2EA7B78E6032343821A80E55D1D"
253 "88FB12D220C3F41A56142FEC85796D19"
254 "17F1E8C774F142B67D3D6E7B7E6B4383"
255 "E94DB5929089DBB346D5BDAB40CC2D96"
256 "EE0409475E175C63BF78CFD744136740"
257 "838127EA723FF3FE7FA368C1311B4A4E"
258 "05"
259 "028181" // INTEGER length 0x81 (prime2)
260 "00D240FCC0F5D7715CDE21CB2DC86EA1"
261 "46132EA3B06F61FF2AF54BF38473F59D"
262 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
263 "B1B58C39F95E4798CCBB43E83D0119AC"
264 "F532F359CA743C85199F0286610E2009"
265 "97D7312917179AC9B67558773212EC96"
266 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
267 "94D94E066A0900B7B70E82A44FB30053"
268 "C1"
269 "028181" // INTEGER length 0x81 (exponent1)
270 "00AD15DA1CBD6A492B66851BA8C316D3"
271 "8AB700E2CFDDD926A658003513C54BAA"
272 "152B30021D667D20078F500F8AD3E7F3"
273 "945D74A891ED1A28EAD0FEEAEC8C14A8"
274 "E834CF46A13D1378C99D18940823CFDD"
275 "27EC5810D59339E0C34198AC638E09C8"
276 "7CBB1B634A9864AE9F4D5EB2D53514F6"
277 "7B4CAEC048C8AB849A02E397618F3271"
278 "35"
279 "028180" // INTEGER length 0x80 (exponent2)
280 "1FA2C1A5331880A92D8F3E281C617108"
281 "BF38244F16E352E69ED417C7153F9EC3"
282 "18F211839C643DCF8B4DD67CE2AC312E"
283 "95178D5D952F06B1BF779F4916924B70"
284 "F582A23F11304E02A5E7565AE22A35E7"
285 "4FECC8B6FDC93F92A1A37703E4CF0E63"
286 "783BD02EB716A7ECBBFA606B10B74D01"
287 "579522E7EF84D91FC522292108D902C1"
288 "028180" // INTEGER length 0x80 (coefficient)
289 "796FE3825F9DCC85DF22D58690065D93"
290 "898ACD65C087BEA8DA3A63BF4549B795"
291 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
292 "0D74F40DED8E1102C52152A31B6165F8"
293 "3A6722AECFCC35A493D7634664B888A0"
294 "8D3EB034F12EA28BFEE346E205D33482"
295 "7F778B16ED40872BD29FCB36536B6E93"
296 "FFB06778696B4A9D81BB0A9423E63DE5"
297 // } end SEQUENCE (PrivateKey)
298 // } end SEQUENCE (PrivateKeyInfo)
299);
Selene Huange5727e62021-04-13 22:41:20 -0700300
David Drysdaled2cc8c22021-04-15 13:29:45 +0100301string ec_256_key = hex2str(
302 // RFC 5208 s5
303 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
304 "020100" // INTEGER length 1 value 0 (version)
305 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
306 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
307 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
308 "0608" // OBJECT IDENTIFIER length 8 (param)
309 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
310 // } end SEQUENCE (AlgorithmIdentifier)
311 "046d" // OCTET STRING length 0x6d (privateKey) holding...
312 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
313 "020101" // INTEGER length 1 value 1 (version)
314 "0420" // OCTET STRING length 0x20 (privateKey)
315 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
316 "941eed09366bc03299986481f3a4d859"
317 "a144" // TAG [1] len 0x44 (publicKey) {
318 "03420004bf85d7720d07c25461683bc6"
319 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
320 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
321 "bcc41c6eb00083cf3376d11fd44949e0"
322 "b2183bfe"
323 // } end SEQUENCE (ECPrivateKey)
324 // } end SEQUENCE (PrivateKeyInfo)
325);
Selene Huang31ab4042020-04-29 04:22:39 -0700326
David Drysdaled2cc8c22021-04-15 13:29:45 +0100327string ec_521_key = hex2str(
328 // RFC 5208 s5
329 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
330 "020100" // INTEGER length 1 value 0 (version)
331 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
332 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
333 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
334 "0605" // OBJECT IDENTIFIER length 5 (param)
335 "2B81040023" // 1.3.132.0.35 (secp521r1)
336 // } end SEQUENCE (AlgorithmIdentifier)
337 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
338 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
339 "020101" // INTEGER length 1 value 1 (version)
340 "0442" // OCTET STRING length 0x42 (privateKey)
341 "0011458C586DB5DAA92AFAB03F4FE46A"
342 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
343 "9D18D7D08B5BCFA0E53C75B064AD51C4"
344 "49BAE0258D54B94B1E885DED08ED4FB2"
345 "5CE9"
346 "A18189" // TAG [1] len 0x89 (publicKey) {
347 "03818600040149EC11C6DF0FA122C6A9"
348 "AFD9754A4FA9513A627CA329E349535A"
349 "5629875A8ADFBE27DCB932C051986377"
350 "108D054C28C6F39B6F2C9AF81802F9F3"
351 "26B842FF2E5F3C00AB7635CFB36157FC"
352 "0882D574A10D839C1A0C049DC5E0D775"
353 "E2EE50671A208431BB45E78E70BEFE93"
354 "0DB34818EE4D5C26259F5C6B8E28A652"
355 "950F9F88D7B4B2C9D9"
356 // } end SEQUENCE (ECPrivateKey)
357 // } end SEQUENCE (PrivateKeyInfo)
358);
Selene Huang31ab4042020-04-29 04:22:39 -0700359
David Drysdaled2cc8c22021-04-15 13:29:45 +0100360string ec_256_key_rfc5915 = hex2str(
361 // RFC 5208 s5
362 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
363 "020100" // INTEGER length 1 value 0 (version)
364 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
365 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
366 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
367 "0608" // OBJECT IDENTIFIER length 8 (param)
368 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
369 // } end SEQUENCE (AlgorithmIdentifier)
370 "0479" // OCTET STRING length 0x79 (privateKey) holding...
371 // RFC 5915 s3
372 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
373 "020101" // INTEGER length 1 value 1 (version)
374 "0420" // OCTET STRING length 0x42 (privateKey)
375 "782370a8c8ce5537baadd04dcff079c8"
376 "158cfa9c67b818b38e8d21c9fa750c1d"
377 "a00a" // TAG [0] length 0xa (parameters)
378 "0608" // OBJECT IDENTIFIER length 8
379 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
380 // } end TAG [0]
381 "a144" // TAG [1] length 0x44 (publicKey) {
382 "0342" // BIT STRING length 0x42
383 "00" // no pad bits
384 "04e2cc561ee701da0ad0ef0d176bb0c9"
385 "19d42e79c393fdc1bd6c4010d85cf2cf"
386 "8e68c905464666f98dad4f01573ba810"
387 "78b3428570a439ba3229fbc026c55068"
388 "2f"
389 // } end SEQUENCE (ECPrivateKey)
390 // } end SEQUENCE (PrivateKeyInfo)
391);
Selene Huang31ab4042020-04-29 04:22:39 -0700392
David Drysdaled2cc8c22021-04-15 13:29:45 +0100393string ec_256_key_sec1 = hex2str(
394 // RFC 5208 s5
395 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
396 "020100" // INTEGER length 1 value 0 (version)
397 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
398 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
399 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
400 "0608" // OBJECT IDENTIFIER length 8 (param)
401 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
402 // } end SEQUENCE (AlgorithmIdentifier)
403 "046d" // OCTET STRING length 0x6d (privateKey) holding...
404 // SEC1-v2 C.4
405 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
406 "020101" // INTEGER length 1 value 0x01 (version)
407 "0420" // OCTET STRING length 0x20 (privateKey)
408 "782370a8c8ce5537baadd04dcff079c8"
409 "158cfa9c67b818b38e8d21c9fa750c1d"
410 "a144" // TAG [1] length 0x44 (publicKey) {
411 "0342" // BIT STRING length 0x42
412 "00" // no pad bits
413 "04e2cc561ee701da0ad0ef0d176bb0c9"
414 "19d42e79c393fdc1bd6c4010d85cf2cf"
415 "8e68c905464666f98dad4f01573ba810"
416 "78b3428570a439ba3229fbc026c55068"
417 "2f"
418 // } end TAG [1] (publicKey)
419 // } end SEQUENCE (PrivateKeyInfo)
420);
Selene Huang31ab4042020-04-29 04:22:39 -0700421
David Drysdale42fe1892021-10-14 14:43:46 +0100422/**
423 * Ed25519 key pair generated as follows:
424 * ```
425 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
426 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
427 * Generating a ED25519 private key writing new private key to
428 * 'ed25519_priv.key'
429 * -----
430 * % cat ed25519_priv.key
431 * -----BEGIN PRIVATE KEY-----
432 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
433 * -----END PRIVATE KEY-----
434 * % der2ascii -pem -i ed25519_priv.key
435 * SEQUENCE {
436 * INTEGER { 0 }
437 * SEQUENCE {
438 * # ed25519
439 * OBJECT_IDENTIFIER { 1.3.101.112 }
440 * }
441 * OCTET_STRING {
442 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
443 * }
444 * }
445 * % cat ed25519.pem
446 * -----BEGIN CERTIFICATE-----
447 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
448 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
449 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
450 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
451 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
452 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
453 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
454 * -----END CERTIFICATE-----
455 * % openssl x509 -in ed25519.pem -text -noout
456 * Certificate:
457 * Data:
458 * Version: 3 (0x2)
459 * Serial Number:
460 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
461 * Signature Algorithm: ED25519
462 * Issuer: CN = fake.ed25519.com
463 * Validity
464 * Not Before: Oct 20 08:27:42 2021 GMT
465 * Not After : Sep 20 08:27:42 2023 GMT
466 * Subject: CN = fake.ed25519.com
467 * Subject Public Key Info:
468 * Public Key Algorithm: ED25519
469 * ED25519 Public-Key:
470 * pub:
471 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
472 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
473 * 56:91
474 * X509v3 extensions:
475 * X509v3 Subject Key Identifier:
476 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
477 * X509v3 Authority Key Identifier:
478 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
479 *
480 * X509v3 Basic Constraints: critical
481 * CA:TRUE
482 * Signature Algorithm: ED25519
483 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
484 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
485 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
486 * e7:07:32:60:32:8d:bb:eb:f6:0f
487 * ```
488 */
489string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
490string ed25519_pkcs8_key = hex2str(
491 // RFC 5208 s5
492 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
493 "0201" // INTEGER length 1 (Version)
494 "00" // version 0
495 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
496 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
497 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
498 // } end SEQUENCE (AlgorithmIdentifier)
499 "0422" // OCTET STRING length 0x22 (PrivateKey)
500 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
501 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
502 // } end SEQUENCE (PrivateKeyInfo)
503);
504string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
505
506/**
507 * X25519 key pair generated as follows:
508 * ```
509 * % openssl genpkey -algorithm X25519 > x25519_priv.key
510 * % cat x25519_priv.key
511 * -----BEGIN PRIVATE KEY-----
512 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
513 * -----END PRIVATE KEY-----
514 * % der2ascii -pem -i x25519_priv.key
515 * SEQUENCE {
516 * INTEGER { 0 }
517 * SEQUENCE {
518 * # x25519
519 * OBJECT_IDENTIFIER { 1.3.101.110 }
520 * }
521 * OCTET_STRING {
522 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
523 * }
524 * }
525 * ```
526 */
527
528string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
529string x25519_pkcs8_key = hex2str(
530 // RFC 5208 s5
531 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
532 "0201" // INTEGER length 1 (Version)
533 "00" // version 0
534 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
535 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
536 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
537 "0422" // OCTET STRING length 0x22 (PrivateKey)
538 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
539 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
540string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
541
Selene Huang31ab4042020-04-29 04:22:39 -0700542struct RSA_Delete {
543 void operator()(RSA* p) { RSA_free(p); }
544};
545
Selene Huang31ab4042020-04-29 04:22:39 -0700546std::string make_string(const uint8_t* data, size_t length) {
547 return std::string(reinterpret_cast<const char*>(data), length);
548}
549
550template <size_t N>
551std::string make_string(const uint8_t (&a)[N]) {
552 return make_string(a, N);
553}
554
555class AidlBuf : public vector<uint8_t> {
556 typedef vector<uint8_t> super;
557
558 public:
559 AidlBuf() {}
560 AidlBuf(const super& other) : super(other) {}
561 AidlBuf(super&& other) : super(std::move(other)) {}
562 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
563
564 AidlBuf& operator=(const super& other) {
565 super::operator=(other);
566 return *this;
567 }
568
569 AidlBuf& operator=(super&& other) {
570 super::operator=(std::move(other));
571 return *this;
572 }
573
574 AidlBuf& operator=(const string& other) {
575 resize(other.size());
576 for (size_t i = 0; i < other.size(); ++i) {
577 (*this)[i] = static_cast<uint8_t>(other[i]);
578 }
579 return *this;
580 }
581
582 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
583};
584
David Drysdale4dc01072021-04-01 12:17:35 +0100585string device_suffix(const string& name) {
586 size_t pos = name.find('/');
587 if (pos == string::npos) {
588 return name;
589 }
590 return name.substr(pos + 1);
591}
592
593bool matching_rp_instance(const string& km_name,
594 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
595 string km_suffix = device_suffix(km_name);
596
597 vector<string> rp_names =
598 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
599 for (const string& rp_name : rp_names) {
600 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
601 // KeyMint instance, assume they match.
602 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
603 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
604 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
605 return true;
606 }
607 }
608 return false;
609}
610
Selene Huang31ab4042020-04-29 04:22:39 -0700611} // namespace
612
613class NewKeyGenerationTest : public KeyMintAidlTestBase {
614 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700615 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000616 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700617 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700618
Selene Huang31ab4042020-04-29 04:22:39 -0700619 // Check that some unexpected tags/values are NOT present.
620 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
621 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000622 }
623
624 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
625 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
626 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
627 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
628
629 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000630 }
631
632 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
633 // TODO(swillden): Distinguish which params should be in which auth list.
634 AuthorizationSet auths;
635 for (auto& entry : keyCharacteristics) {
636 auths.push_back(AuthorizationSet(entry.authorizations));
637 }
638 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
639
640 // Verify that App data, ROT and auth timeout are NOT included.
641 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
642 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700643 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
644
David Drysdaled2cc8c22021-04-15 13:29:45 +0100645 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
646 // never adds it.
647 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
648
David Drysdale7de9feb2021-03-05 14:56:19 +0000649 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700650 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000651 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700652 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700653 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000654 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700655 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000656
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000657 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100658 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
659 EXPECT_TRUE(vendor_pl);
660 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000661
662 // Should include boot patchlevel (but there are some test scenarios where this is not
663 // possible).
664 if (check_boot_pl) {
665 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
666 EXPECT_TRUE(boot_pl);
667 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100668
David Drysdale7de9feb2021-03-05 14:56:19 +0000669 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700670 }
671};
672
673/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000674 * NewKeyGenerationTest.Aes
675 *
676 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
677 * have correct characteristics.
678 */
679TEST_P(NewKeyGenerationTest, Aes) {
680 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
681 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
682 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
683 SCOPED_TRACE(testing::Message()
684 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
685 vector<uint8_t> key_blob;
686 vector<KeyCharacteristics> key_characteristics;
687 auto builder = AuthorizationSetBuilder()
688 .AesEncryptionKey(key_size)
689 .BlockMode(block_mode)
690 .Padding(padding_mode)
691 .SetDefaultValidity();
692 if (block_mode == BlockMode::GCM) {
693 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
694 }
695 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
696
697 EXPECT_GT(key_blob.size(), 0U);
698 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100699 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000700
701 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
702
703 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
704 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
705 << "Key size " << key_size << "missing";
706
707 CheckedDeleteKey(&key_blob);
708 }
709 }
710 }
711}
712
713/*
714 * NewKeyGenerationTest.AesInvalidSize
715 *
716 * Verifies that specifying an invalid key size for AES key generation returns
717 * UNSUPPORTED_KEY_SIZE.
718 */
719TEST_P(NewKeyGenerationTest, AesInvalidSize) {
720 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
721 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
722 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
723 SCOPED_TRACE(testing::Message()
724 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
725 vector<uint8_t> key_blob;
726 vector<KeyCharacteristics> key_characteristics;
727 auto builder = AuthorizationSetBuilder()
728 .AesEncryptionKey(key_size)
729 .BlockMode(block_mode)
730 .Padding(padding_mode)
731 .SetDefaultValidity();
732 if (block_mode == BlockMode::GCM) {
733 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
734 }
735 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
736 GenerateKey(builder, &key_blob, &key_characteristics));
737 }
738 }
739 }
740
741 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
742 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
743 vector<uint8_t> key_blob;
744 vector<KeyCharacteristics> key_characteristics;
745 // No key size specified
746 auto builder = AuthorizationSetBuilder()
747 .Authorization(TAG_ALGORITHM, Algorithm::AES)
748 .BlockMode(block_mode)
749 .Padding(padding_mode)
750 .SetDefaultValidity();
751 if (block_mode == BlockMode::GCM) {
752 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
753 }
754 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
755 GenerateKey(builder, &key_blob, &key_characteristics));
756 }
757 }
758}
759
760/*
761 * NewKeyGenerationTest.AesInvalidPadding
762 *
763 * Verifies that specifying an invalid padding on AES keys gives a failure
764 * somewhere along the way.
765 */
766TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
767 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
768 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
769 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
770 SCOPED_TRACE(testing::Message()
771 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000772 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800773 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000774 .AesEncryptionKey(key_size)
775 .BlockMode(block_mode)
776 .Padding(padding_mode)
777 .SetDefaultValidity();
778 if (block_mode == BlockMode::GCM) {
779 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
780 }
781
Tommy Chiu3950b452021-05-03 22:01:46 +0800782 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000783 if (result == ErrorCode::OK) {
784 // Key creation was OK but has generated a key that cannot be used.
785 auto params =
786 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800787 if (block_mode == BlockMode::GCM) {
788 params.Authorization(TAG_MAC_LENGTH, 128);
789 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000790 auto result = Begin(KeyPurpose::ENCRYPT, params);
791 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100792 result == ErrorCode::INVALID_KEY_BLOB)
793 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000794 } else {
795 // The KeyMint implementation detected that the generated key
796 // is unusable.
797 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
798 }
799 }
800 }
801 }
802}
803
804/*
805 * NewKeyGenerationTest.AesGcmMissingMinMac
806 *
807 * Verifies that specifying an invalid key size for AES key generation returns
808 * UNSUPPORTED_KEY_SIZE.
809 */
810TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
811 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
812 BlockMode block_mode = BlockMode::GCM;
813 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
814 SCOPED_TRACE(testing::Message()
815 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
816 vector<uint8_t> key_blob;
817 vector<KeyCharacteristics> key_characteristics;
818 // No MIN_MAC_LENGTH provided.
819 auto builder = AuthorizationSetBuilder()
820 .AesEncryptionKey(key_size)
821 .BlockMode(block_mode)
822 .Padding(padding_mode)
823 .SetDefaultValidity();
824 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
825 GenerateKey(builder, &key_blob, &key_characteristics));
826 }
827 }
828}
829
830/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100831 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
832 *
833 * Verifies that specifying an invalid min MAC size for AES key generation returns
834 * UNSUPPORTED_MIN_MAC_LENGTH.
835 */
836TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
837 for (size_t min_mac_len : {88, 136}) {
838 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
839 BlockMode block_mode = BlockMode::GCM;
840 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
841 SCOPED_TRACE(testing::Message()
842 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
843 vector<uint8_t> key_blob;
844 vector<KeyCharacteristics> key_characteristics;
845 auto builder = AuthorizationSetBuilder()
846 .AesEncryptionKey(key_size)
847 .BlockMode(block_mode)
848 .Padding(padding_mode)
849 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
850 .SetDefaultValidity();
851 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
852 GenerateKey(builder, &key_blob, &key_characteristics));
853 }
854 }
855 }
856}
857
858/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000859 * NewKeyGenerationTest.TripleDes
860 *
861 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
862 * have correct characteristics.
863 */
864TEST_P(NewKeyGenerationTest, TripleDes) {
865 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
866 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
867 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
868 SCOPED_TRACE(testing::Message()
869 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
870 vector<uint8_t> key_blob;
871 vector<KeyCharacteristics> key_characteristics;
872 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
873 .TripleDesEncryptionKey(key_size)
874 .BlockMode(block_mode)
875 .Padding(padding_mode)
876 .Authorization(TAG_NO_AUTH_REQUIRED)
877 .SetDefaultValidity(),
878 &key_blob, &key_characteristics));
879
880 EXPECT_GT(key_blob.size(), 0U);
881 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100882 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000883
884 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
885
886 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
887 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
888 << "Key size " << key_size << "missing";
889
890 CheckedDeleteKey(&key_blob);
891 }
892 }
893 }
894}
895
896/*
897 * NewKeyGenerationTest.TripleDesWithAttestation
898 *
899 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
900 * have correct characteristics.
901 *
902 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
903 * put in a certificate) but which isn't an error.
904 */
905TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
906 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
907 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
908 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
909 SCOPED_TRACE(testing::Message()
910 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
911
912 auto challenge = "hello";
913 auto app_id = "foo";
914
915 vector<uint8_t> key_blob;
916 vector<KeyCharacteristics> key_characteristics;
917 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
918 .TripleDesEncryptionKey(key_size)
919 .BlockMode(block_mode)
920 .Padding(padding_mode)
921 .Authorization(TAG_NO_AUTH_REQUIRED)
922 .AttestationChallenge(challenge)
923 .AttestationApplicationId(app_id)
924 .SetDefaultValidity(),
925 &key_blob, &key_characteristics));
926
927 EXPECT_GT(key_blob.size(), 0U);
928 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100929 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000930
931 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
932
933 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
934 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
935 << "Key size " << key_size << "missing";
936
937 CheckedDeleteKey(&key_blob);
938 }
939 }
940 }
941}
942
943/*
944 * NewKeyGenerationTest.TripleDesInvalidSize
945 *
946 * Verifies that specifying an invalid key size for 3-DES key generation returns
947 * UNSUPPORTED_KEY_SIZE.
948 */
949TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
950 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
951 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
952 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
953 SCOPED_TRACE(testing::Message()
954 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
955 vector<uint8_t> key_blob;
956 vector<KeyCharacteristics> key_characteristics;
957 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
958 GenerateKey(AuthorizationSetBuilder()
959 .TripleDesEncryptionKey(key_size)
960 .BlockMode(block_mode)
961 .Padding(padding_mode)
962 .Authorization(TAG_NO_AUTH_REQUIRED)
963 .SetDefaultValidity(),
964 &key_blob, &key_characteristics));
965 }
966 }
967 }
968
969 // Omitting the key size fails.
970 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
971 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
972 SCOPED_TRACE(testing::Message()
973 << "3DES-default-" << block_mode << "-" << padding_mode);
974 vector<uint8_t> key_blob;
975 vector<KeyCharacteristics> key_characteristics;
976 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
977 GenerateKey(AuthorizationSetBuilder()
978 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
979 .BlockMode(block_mode)
980 .Padding(padding_mode)
981 .Authorization(TAG_NO_AUTH_REQUIRED)
982 .SetDefaultValidity(),
983 &key_blob, &key_characteristics));
984 }
985 }
986}
987
988/*
Selene Huang31ab4042020-04-29 04:22:39 -0700989 * NewKeyGenerationTest.Rsa
990 *
991 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
992 * have correct characteristics.
993 */
994TEST_P(NewKeyGenerationTest, Rsa) {
995 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
996 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700997 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700998 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
999 .RsaSigningKey(key_size, 65537)
1000 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001001 .Padding(PaddingMode::NONE)
1002 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001003 &key_blob, &key_characteristics));
1004
1005 ASSERT_GT(key_blob.size(), 0U);
1006 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001007 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001008
Shawn Willden7f424372021-01-10 18:06:50 -07001009 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001010
1011 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1012 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1013 << "Key size " << key_size << "missing";
1014 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1015
1016 CheckedDeleteKey(&key_blob);
1017 }
1018}
1019
1020/*
Qi Wud22ec842020-11-26 13:27:53 +08001021 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001022 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001023 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1024 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001025 */
1026TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001027 auto challenge = "hello";
1028 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001029
Selene Huang6e46f142021-04-20 19:20:11 -07001030 auto subject = "cert subj 2";
1031 vector<uint8_t> subject_der(make_name_from_str(subject));
1032
1033 uint64_t serial_int = 66;
1034 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1035
Selene Huang4f64c222021-04-13 19:54:36 -07001036 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001037 vector<uint8_t> key_blob;
1038 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman05642492022-02-05 07:10:56 +00001039 auto result = GenerateKey(AuthorizationSetBuilder()
1040 .RsaSigningKey(key_size, 65537)
1041 .Digest(Digest::NONE)
1042 .Padding(PaddingMode::NONE)
1043 .AttestationChallenge(challenge)
1044 .AttestationApplicationId(app_id)
1045 .Authorization(TAG_NO_AUTH_REQUIRED)
1046 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1047 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1048 .SetDefaultValidity(),
1049 &key_blob, &key_characteristics);
1050 // Strongbox may not support factory provisioned attestation key.
1051 if (SecLevel() == SecurityLevel::STRONGBOX) {
1052 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1053 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001054
1055 ASSERT_GT(key_blob.size(), 0U);
1056 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001057 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001058
1059 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1060
1061 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1062 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1063 << "Key size " << key_size << "missing";
1064 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1065
Selene Huang6e46f142021-04-20 19:20:11 -07001066 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001067 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001068 ASSERT_GT(cert_chain_.size(), 0);
1069
1070 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1071 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001072 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001073 sw_enforced, hw_enforced, SecLevel(),
1074 cert_chain_[0].encodedCertificate));
1075
1076 CheckedDeleteKey(&key_blob);
1077 }
1078}
1079
1080/*
David Drysdale4dc01072021-04-01 12:17:35 +01001081 * NewKeyGenerationTest.RsaWithRpkAttestation
1082 *
1083 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
1084 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale0fce69d2021-04-13 17:22:13 +01001085 *
1086 * This test is disabled because the KeyMint specification does not require that implementations
1087 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
1088 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +01001089 */
David Drysdale0fce69d2021-04-13 17:22:13 +01001090TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +01001091 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
1092 // instance.
1093 std::shared_ptr<IRemotelyProvisionedComponent> rp;
1094 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
1095 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
1096
1097 // Generate a P-256 keypair to use as an attestation key.
1098 MacedPublicKey macedPubKey;
1099 std::vector<uint8_t> privateKeyBlob;
1100 auto status =
1101 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1102 ASSERT_TRUE(status.isOk());
1103 vector<uint8_t> coseKeyData;
1104 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1105
1106 AttestationKey attestation_key;
1107 attestation_key.keyBlob = std::move(privateKeyBlob);
1108 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1109
1110 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1111 auto challenge = "hello";
1112 auto app_id = "foo";
1113
1114 vector<uint8_t> key_blob;
1115 vector<KeyCharacteristics> key_characteristics;
1116 ASSERT_EQ(ErrorCode::OK,
1117 GenerateKey(AuthorizationSetBuilder()
1118 .RsaSigningKey(key_size, 65537)
1119 .Digest(Digest::NONE)
1120 .Padding(PaddingMode::NONE)
1121 .AttestationChallenge(challenge)
1122 .AttestationApplicationId(app_id)
1123 .Authorization(TAG_NO_AUTH_REQUIRED)
1124 .SetDefaultValidity(),
1125 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1126
1127 ASSERT_GT(key_blob.size(), 0U);
1128 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001129 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001130
1131 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1132
1133 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1134 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1135 << "Key size " << key_size << "missing";
1136 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1137
1138 // Attestation by itself is not valid (last entry is not self-signed).
1139 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1140
1141 // The signature over the attested key should correspond to the P256 public key.
1142 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1143 ASSERT_TRUE(key_cert.get());
1144 EVP_PKEY_Ptr signing_pubkey;
1145 p256_pub_key(coseKeyData, &signing_pubkey);
1146 ASSERT_TRUE(signing_pubkey.get());
1147
1148 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1149 << "Verification of attested certificate failed "
1150 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1151
1152 CheckedDeleteKey(&key_blob);
1153 }
1154}
1155
1156/*
Selene Huang4f64c222021-04-13 19:54:36 -07001157 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1158 *
1159 * Verifies that keymint attestation for RSA encryption keys with challenge and
1160 * app id is also successful.
1161 */
1162TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1163 auto key_size = 2048;
1164 auto challenge = "hello";
1165 auto app_id = "foo";
1166
Selene Huang6e46f142021-04-20 19:20:11 -07001167 auto subject = "subj 2";
1168 vector<uint8_t> subject_der(make_name_from_str(subject));
1169
1170 uint64_t serial_int = 111166;
1171 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1172
Selene Huang4f64c222021-04-13 19:54:36 -07001173 vector<uint8_t> key_blob;
1174 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman05642492022-02-05 07:10:56 +00001175 auto result = GenerateKey(AuthorizationSetBuilder()
1176 .RsaEncryptionKey(key_size, 65537)
1177 .Padding(PaddingMode::NONE)
1178 .AttestationChallenge(challenge)
1179 .AttestationApplicationId(app_id)
1180 .Authorization(TAG_NO_AUTH_REQUIRED)
1181 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1182 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1183 .SetDefaultValidity(),
1184 &key_blob, &key_characteristics);
1185 // Strongbox may not support factory provisioned attestation key.
1186 if (SecLevel() == SecurityLevel::STRONGBOX) {
1187 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1188 }
1189 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001190
1191 ASSERT_GT(key_blob.size(), 0U);
1192 AuthorizationSet auths;
1193 for (auto& entry : key_characteristics) {
1194 auths.push_back(AuthorizationSet(entry.authorizations));
1195 }
1196
1197 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1198 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1199
1200 // Verify that App data and ROT are NOT included.
1201 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1202 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1203
1204 // Check that some unexpected tags/values are NOT present.
1205 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1206 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1207
1208 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1209
1210 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1211 ASSERT_TRUE(os_ver);
1212 EXPECT_EQ(*os_ver, os_version());
1213
1214 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1215
1216 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1217 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1218 << "Key size " << key_size << "missing";
1219 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1220
Selene Huang6e46f142021-04-20 19:20:11 -07001221 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001222 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1223 ASSERT_GT(cert_chain_.size(), 0);
1224
1225 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1226 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001227 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001228 sw_enforced, hw_enforced, SecLevel(),
1229 cert_chain_[0].encodedCertificate));
1230
1231 CheckedDeleteKey(&key_blob);
1232}
1233
1234/*
1235 * NewKeyGenerationTest.RsaWithSelfSign
1236 *
1237 * Verifies that attesting to RSA key generation is successful, and returns
1238 * self signed certificate if no challenge is provided. And signing etc
1239 * works as expected.
1240 */
1241TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001242 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1243 vector<uint8_t> subject_der(make_name_from_str(subject));
1244
1245 uint64_t serial_int = 0;
1246 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1247
Selene Huang4f64c222021-04-13 19:54:36 -07001248 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1249 vector<uint8_t> key_blob;
1250 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001251 ASSERT_EQ(ErrorCode::OK,
1252 GenerateKey(AuthorizationSetBuilder()
1253 .RsaSigningKey(key_size, 65537)
1254 .Digest(Digest::NONE)
1255 .Padding(PaddingMode::NONE)
1256 .Authorization(TAG_NO_AUTH_REQUIRED)
1257 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1258 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1259 .SetDefaultValidity(),
1260 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001261
1262 ASSERT_GT(key_blob.size(), 0U);
1263 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001264 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001265
1266 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1267
1268 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1269 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1270 << "Key size " << key_size << "missing";
1271 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1272
Selene Huang6e46f142021-04-20 19:20:11 -07001273 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001274 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1275 ASSERT_EQ(cert_chain_.size(), 1);
1276
1277 CheckedDeleteKey(&key_blob);
1278 }
1279}
1280
1281/*
1282 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1283 *
1284 * Verifies that attesting to RSA checks for missing app ID.
1285 */
1286TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1287 auto challenge = "hello";
1288 vector<uint8_t> key_blob;
1289 vector<KeyCharacteristics> key_characteristics;
1290
subrahmanyaman05642492022-02-05 07:10:56 +00001291 auto result = GenerateKey(AuthorizationSetBuilder()
1292 .RsaSigningKey(2048, 65537)
1293 .Digest(Digest::NONE)
1294 .Padding(PaddingMode::NONE)
1295 .AttestationChallenge(challenge)
1296 .Authorization(TAG_NO_AUTH_REQUIRED)
1297 .SetDefaultValidity(),
1298 &key_blob, &key_characteristics);
1299 // Strongbox may not support factory provisioned attestation key.
1300 if (SecLevel() == SecurityLevel::STRONGBOX) {
1301 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1302 }
1303 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001304}
1305
1306/*
1307 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1308 *
1309 * Verifies that attesting to RSA ignores app id if challenge is missing.
1310 */
1311TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1312 auto key_size = 2048;
1313 auto app_id = "foo";
1314
Selene Huang6e46f142021-04-20 19:20:11 -07001315 auto subject = "cert subj 2";
1316 vector<uint8_t> subject_der(make_name_from_str(subject));
1317
1318 uint64_t serial_int = 1;
1319 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1320
Selene Huang4f64c222021-04-13 19:54:36 -07001321 vector<uint8_t> key_blob;
1322 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001323 ASSERT_EQ(ErrorCode::OK,
1324 GenerateKey(AuthorizationSetBuilder()
1325 .RsaSigningKey(key_size, 65537)
1326 .Digest(Digest::NONE)
1327 .Padding(PaddingMode::NONE)
1328 .AttestationApplicationId(app_id)
1329 .Authorization(TAG_NO_AUTH_REQUIRED)
1330 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1331 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1332 .SetDefaultValidity(),
1333 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001334
1335 ASSERT_GT(key_blob.size(), 0U);
1336 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001337 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001338
1339 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1340
1341 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1342 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1343 << "Key size " << key_size << "missing";
1344 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1345
Selene Huang6e46f142021-04-20 19:20:11 -07001346 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001347 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1348 ASSERT_EQ(cert_chain_.size(), 1);
1349
1350 CheckedDeleteKey(&key_blob);
1351}
1352
1353/*
Qi Wud22ec842020-11-26 13:27:53 +08001354 * NewKeyGenerationTest.LimitedUsageRsa
1355 *
1356 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1357 * resulting keys have correct characteristics.
1358 */
1359TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1360 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1361 vector<uint8_t> key_blob;
1362 vector<KeyCharacteristics> key_characteristics;
1363 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1364 .RsaSigningKey(key_size, 65537)
1365 .Digest(Digest::NONE)
1366 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001367 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1368 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001369 &key_blob, &key_characteristics));
1370
1371 ASSERT_GT(key_blob.size(), 0U);
1372 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001373 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001374
1375 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1376
1377 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1378 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1379 << "Key size " << key_size << "missing";
1380 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1381
1382 // Check the usage count limit tag appears in the authorizations.
1383 AuthorizationSet auths;
1384 for (auto& entry : key_characteristics) {
1385 auths.push_back(AuthorizationSet(entry.authorizations));
1386 }
1387 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1388 << "key usage count limit " << 1U << " missing";
1389
1390 CheckedDeleteKey(&key_blob);
1391 }
1392}
1393
1394/*
Qi Wubeefae42021-01-28 23:16:37 +08001395 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1396 *
1397 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1398 * resulting keys have correct characteristics and attestation.
1399 */
1400TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001401 auto challenge = "hello";
1402 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001403
Selene Huang6e46f142021-04-20 19:20:11 -07001404 auto subject = "cert subj 2";
1405 vector<uint8_t> subject_der(make_name_from_str(subject));
1406
1407 uint64_t serial_int = 66;
1408 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1409
Selene Huang4f64c222021-04-13 19:54:36 -07001410 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001411 vector<uint8_t> key_blob;
1412 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman05642492022-02-05 07:10:56 +00001413 auto result = GenerateKey(AuthorizationSetBuilder()
1414 .RsaSigningKey(key_size, 65537)
1415 .Digest(Digest::NONE)
1416 .Padding(PaddingMode::NONE)
1417 .AttestationChallenge(challenge)
1418 .AttestationApplicationId(app_id)
1419 .Authorization(TAG_NO_AUTH_REQUIRED)
1420 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1421 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1422 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1423 .SetDefaultValidity(),
1424 &key_blob, &key_characteristics);
1425 // Strongbox may not support factory provisioned attestation key.
1426 if (SecLevel() == SecurityLevel::STRONGBOX) {
1427 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1428 }
1429 ASSERT_EQ(ErrorCode::OK, result);
Qi Wubeefae42021-01-28 23:16:37 +08001430
1431 ASSERT_GT(key_blob.size(), 0U);
1432 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001433 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001434
1435 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1436
1437 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1438 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1439 << "Key size " << key_size << "missing";
1440 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1441
1442 // Check the usage count limit tag appears in the authorizations.
1443 AuthorizationSet auths;
1444 for (auto& entry : key_characteristics) {
1445 auths.push_back(AuthorizationSet(entry.authorizations));
1446 }
1447 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1448 << "key usage count limit " << 1U << " missing";
1449
1450 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001451 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001452 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001453 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001454
1455 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1456 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001457 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001458 sw_enforced, hw_enforced, SecLevel(),
1459 cert_chain_[0].encodedCertificate));
1460
1461 CheckedDeleteKey(&key_blob);
1462 }
1463}
1464
1465/*
Selene Huang31ab4042020-04-29 04:22:39 -07001466 * NewKeyGenerationTest.NoInvalidRsaSizes
1467 *
1468 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1469 */
1470TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1471 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1472 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001473 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001474 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1475 GenerateKey(AuthorizationSetBuilder()
1476 .RsaSigningKey(key_size, 65537)
1477 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001478 .Padding(PaddingMode::NONE)
1479 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001480 &key_blob, &key_characteristics));
1481 }
1482}
1483
1484/*
1485 * NewKeyGenerationTest.RsaNoDefaultSize
1486 *
1487 * Verifies that failing to specify a key size for RSA key generation returns
1488 * UNSUPPORTED_KEY_SIZE.
1489 */
1490TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1491 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1492 GenerateKey(AuthorizationSetBuilder()
1493 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1494 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001495 .SigningKey()
1496 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001497}
1498
1499/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001500 * NewKeyGenerationTest.RsaMissingParams
1501 *
1502 * Verifies that omitting optional tags works.
1503 */
1504TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1505 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1506 ASSERT_EQ(ErrorCode::OK,
1507 GenerateKey(
1508 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1509 CheckedDeleteKey();
1510 }
1511}
1512
1513/*
Selene Huang31ab4042020-04-29 04:22:39 -07001514 * NewKeyGenerationTest.Ecdsa
1515 *
David Drysdale42fe1892021-10-14 14:43:46 +01001516 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001517 * have correct characteristics.
1518 */
1519TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001520 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001521 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001522 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001523 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001524 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001525 .Digest(Digest::NONE)
1526 .SetDefaultValidity(),
1527 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001528 ASSERT_GT(key_blob.size(), 0U);
1529 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001530 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001531
Shawn Willden7f424372021-01-10 18:06:50 -07001532 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001533
1534 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001535 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001536
1537 CheckedDeleteKey(&key_blob);
1538 }
1539}
1540
1541/*
David Drysdale42fe1892021-10-14 14:43:46 +01001542 * NewKeyGenerationTest.EcdsaCurve25519
1543 *
1544 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1545 * has correct characteristics.
1546 */
1547TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1548 if (!Curve25519Supported()) {
1549 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1550 }
1551
1552 EcCurve curve = EcCurve::CURVE_25519;
1553 vector<uint8_t> key_blob;
1554 vector<KeyCharacteristics> key_characteristics;
1555 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1556 .EcdsaSigningKey(curve)
1557 .Digest(Digest::NONE)
1558 .SetDefaultValidity(),
1559 &key_blob, &key_characteristics);
1560 ASSERT_EQ(result, ErrorCode::OK);
1561 ASSERT_GT(key_blob.size(), 0U);
1562
1563 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1564 ASSERT_GT(cert_chain_.size(), 0);
1565
1566 CheckBaseParams(key_characteristics);
1567 CheckCharacteristics(key_blob, key_characteristics);
1568
1569 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1570
1571 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1572 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1573
1574 CheckedDeleteKey(&key_blob);
1575}
1576
1577/*
1578 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1579 *
1580 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1581 * SIGN and AGREE_KEY.
1582 */
1583TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1584 if (!Curve25519Supported()) {
1585 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1586 }
1587
1588 EcCurve curve = EcCurve::CURVE_25519;
1589 vector<uint8_t> key_blob;
1590 vector<KeyCharacteristics> key_characteristics;
1591 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1592 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1593 .EcdsaSigningKey(curve)
1594 .Digest(Digest::NONE)
1595 .SetDefaultValidity(),
1596 &key_blob, &key_characteristics);
1597 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1598}
1599
1600/*
Selene Huang4f64c222021-04-13 19:54:36 -07001601 * NewKeyGenerationTest.EcdsaAttestation
1602 *
1603 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1604 * an attestation will be generated.
1605 */
1606TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1607 auto challenge = "hello";
1608 auto app_id = "foo";
1609
Selene Huang6e46f142021-04-20 19:20:11 -07001610 auto subject = "cert subj 2";
1611 vector<uint8_t> subject_der(make_name_from_str(subject));
1612
1613 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1614 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1615
David Drysdaledf09e542021-06-08 15:46:11 +01001616 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001617 vector<uint8_t> key_blob;
1618 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman05642492022-02-05 07:10:56 +00001619 auto result = GenerateKey(AuthorizationSetBuilder()
1620 .Authorization(TAG_NO_AUTH_REQUIRED)
1621 .EcdsaSigningKey(curve)
1622 .Digest(Digest::NONE)
1623 .AttestationChallenge(challenge)
1624 .AttestationApplicationId(app_id)
1625 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1626 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1627 .SetDefaultValidity(),
1628 &key_blob, &key_characteristics);
1629 // Strongbox may not support factory provisioned attestation key.
1630 if (SecLevel() == SecurityLevel::STRONGBOX) {
1631 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1632 }
1633 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001634 ASSERT_GT(key_blob.size(), 0U);
1635 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001636 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001637
1638 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1639
1640 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001641 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001642
1643 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1644 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001645 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001646
1647 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1648 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001649 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001650 sw_enforced, hw_enforced, SecLevel(),
1651 cert_chain_[0].encodedCertificate));
1652
1653 CheckedDeleteKey(&key_blob);
1654 }
1655}
1656
1657/*
David Drysdale42fe1892021-10-14 14:43:46 +01001658 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1659 *
1660 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1661 * an attestation will be generated.
1662 */
1663TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1664 if (!Curve25519Supported()) {
1665 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1666 }
1667
1668 EcCurve curve = EcCurve::CURVE_25519;
1669 auto challenge = "hello";
1670 auto app_id = "foo";
1671
1672 auto subject = "cert subj 2";
1673 vector<uint8_t> subject_der(make_name_from_str(subject));
1674
1675 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1676 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1677
1678 vector<uint8_t> key_blob;
1679 vector<KeyCharacteristics> key_characteristics;
1680 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1681 .Authorization(TAG_NO_AUTH_REQUIRED)
1682 .EcdsaSigningKey(curve)
1683 .Digest(Digest::NONE)
1684 .AttestationChallenge(challenge)
1685 .AttestationApplicationId(app_id)
1686 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1687 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1688 .SetDefaultValidity(),
1689 &key_blob, &key_characteristics);
1690 ASSERT_EQ(ErrorCode::OK, result);
1691 ASSERT_GT(key_blob.size(), 0U);
1692 CheckBaseParams(key_characteristics);
1693 CheckCharacteristics(key_blob, key_characteristics);
1694
1695 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1696
1697 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1698 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1699
1700 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1701 ASSERT_GT(cert_chain_.size(), 0);
1702 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1703
1704 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1705 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1706 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1707 sw_enforced, hw_enforced, SecLevel(),
1708 cert_chain_[0].encodedCertificate));
1709
1710 CheckedDeleteKey(&key_blob);
1711}
1712
1713/*
David Drysdale37af4b32021-05-14 16:46:59 +01001714 * NewKeyGenerationTest.EcdsaAttestationTags
1715 *
1716 * Verifies that creation of an attested ECDSA key includes various tags in the
1717 * attestation extension.
1718 */
1719TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1720 auto challenge = "hello";
1721 auto app_id = "foo";
1722 auto subject = "cert subj 2";
1723 vector<uint8_t> subject_der(make_name_from_str(subject));
1724 uint64_t serial_int = 0x1010;
1725 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1726 const AuthorizationSetBuilder base_builder =
1727 AuthorizationSetBuilder()
1728 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001729 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001730 .Digest(Digest::NONE)
1731 .AttestationChallenge(challenge)
1732 .AttestationApplicationId(app_id)
1733 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1734 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1735 .SetDefaultValidity();
1736
1737 // Various tags that map to fields in the attestation extension ASN.1 schema.
1738 auto extra_tags = AuthorizationSetBuilder()
1739 .Authorization(TAG_ROLLBACK_RESISTANCE)
1740 .Authorization(TAG_EARLY_BOOT_ONLY)
1741 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1742 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1743 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1744 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1745 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1746 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1747 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1748 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1749 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1750 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001751
David Drysdale37af4b32021-05-14 16:46:59 +01001752 for (const KeyParameter& tag : extra_tags) {
1753 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1754 vector<uint8_t> key_blob;
1755 vector<KeyCharacteristics> key_characteristics;
1756 AuthorizationSetBuilder builder = base_builder;
1757 builder.push_back(tag);
1758 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1759 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1760 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1761 continue;
1762 }
Seth Mooreb393b082021-07-12 14:18:28 -07001763 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1764 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001765 continue;
1766 }
subrahmanyaman05642492022-02-05 07:10:56 +00001767 // Strongbox may not support factory provisioned attestation key.
1768 if (SecLevel() == SecurityLevel::STRONGBOX) {
1769 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1770 }
David Drysdale37af4b32021-05-14 16:46:59 +01001771 ASSERT_EQ(result, ErrorCode::OK);
1772 ASSERT_GT(key_blob.size(), 0U);
1773
1774 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1775 ASSERT_GT(cert_chain_.size(), 0);
1776 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1777
1778 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1779 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001780 // Some tags are optional, so don't require them to be in the enforcements.
1781 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001782 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1783 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1784 }
1785
1786 // Verifying the attestation record will check for the specific tag because
1787 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001788 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1789 hw_enforced, SecLevel(),
1790 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01001791
1792 CheckedDeleteKey(&key_blob);
1793 }
1794
David Drysdalec53b7d92021-10-11 12:35:58 +01001795 // Collection of invalid attestation ID tags.
1796 auto invalid_tags =
1797 AuthorizationSetBuilder()
1798 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1799 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1800 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1801 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1802 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
1803 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
1804 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
1805 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01001806 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01001807 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01001808 vector<uint8_t> key_blob;
1809 vector<KeyCharacteristics> key_characteristics;
1810 AuthorizationSetBuilder builder =
1811 AuthorizationSetBuilder()
1812 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001813 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001814 .Digest(Digest::NONE)
1815 .AttestationChallenge(challenge)
1816 .AttestationApplicationId(app_id)
1817 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1818 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1819 .SetDefaultValidity();
1820 builder.push_back(tag);
1821 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1822 GenerateKey(builder, &key_blob, &key_characteristics));
1823 }
1824}
1825
1826/*
David Drysdalec53b7d92021-10-11 12:35:58 +01001827 * NewKeyGenerationTest.EcdsaAttestationIdTags
1828 *
1829 * Verifies that creation of an attested ECDSA key includes various ID tags in the
1830 * attestation extension.
1831 */
1832TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
1833 auto challenge = "hello";
1834 auto app_id = "foo";
1835 auto subject = "cert subj 2";
1836 vector<uint8_t> subject_der(make_name_from_str(subject));
1837 uint64_t serial_int = 0x1010;
1838 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1839 const AuthorizationSetBuilder base_builder =
1840 AuthorizationSetBuilder()
1841 .Authorization(TAG_NO_AUTH_REQUIRED)
1842 .EcdsaSigningKey(EcCurve::P_256)
1843 .Digest(Digest::NONE)
1844 .AttestationChallenge(challenge)
1845 .AttestationApplicationId(app_id)
1846 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1847 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1848 .SetDefaultValidity();
1849
1850 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
1851 auto extra_tags = AuthorizationSetBuilder();
1852 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
1853 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
1854 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
1855 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
1856 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
1857 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
1858
1859 for (const KeyParameter& tag : extra_tags) {
1860 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1861 vector<uint8_t> key_blob;
1862 vector<KeyCharacteristics> key_characteristics;
1863 AuthorizationSetBuilder builder = base_builder;
1864 builder.push_back(tag);
1865 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001866 // Strongbox may not support factory provisioned attestation key.
1867 if (SecLevel() == SecurityLevel::STRONGBOX) {
1868 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1869 }
David Drysdalec53b7d92021-10-11 12:35:58 +01001870 if (result == ErrorCode::CANNOT_ATTEST_IDS) {
1871 // Device ID attestation is optional; KeyMint may not support it at all.
1872 continue;
1873 }
1874 ASSERT_EQ(result, ErrorCode::OK);
1875 ASSERT_GT(key_blob.size(), 0U);
1876
1877 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1878 ASSERT_GT(cert_chain_.size(), 0);
1879 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1880
1881 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1882 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1883
1884 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
1885 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
1886 // attestation extension should contain them, so make sure the extra tag is added.
1887 hw_enforced.push_back(tag);
1888
1889 // Verifying the attestation record will check for the specific tag because
1890 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001891 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1892 hw_enforced, SecLevel(),
1893 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01001894
1895 CheckedDeleteKey(&key_blob);
1896 }
1897}
1898
1899/*
David Drysdale565ccc72021-10-11 12:49:50 +01001900 * NewKeyGenerationTest.EcdsaAttestationUniqueId
1901 *
1902 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
1903 */
1904TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
1905 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00001906 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01001907 auto challenge = "hello";
1908 auto subject = "cert subj 2";
1909 vector<uint8_t> subject_der(make_name_from_str(subject));
1910 uint64_t serial_int = 0x1010;
1911 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00001912 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01001913 AuthorizationSetBuilder()
1914 .Authorization(TAG_NO_AUTH_REQUIRED)
1915 .Authorization(TAG_INCLUDE_UNIQUE_ID)
1916 .EcdsaSigningKey(EcCurve::P_256)
1917 .Digest(Digest::NONE)
1918 .AttestationChallenge(challenge)
1919 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1920 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1921 .AttestationApplicationId(app_id)
1922 .Authorization(TAG_CREATION_DATETIME, datetime)
1923 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00001924 if (reset) {
1925 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
1926 }
David Drysdale565ccc72021-10-11 12:49:50 +01001927
1928 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
1929 ASSERT_GT(key_blob_.size(), 0U);
1930
1931 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1932 ASSERT_GT(cert_chain_.size(), 0);
1933 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1934
1935 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
1936 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
1937
1938 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001939 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1940 hw_enforced, SecLevel(),
1941 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01001942 EXPECT_GT(unique_id->size(), 0);
1943 CheckedDeleteKey();
1944 };
1945
1946 // Generate unique ID
1947 auto app_id = "foo";
1948 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
1949 vector<uint8_t> unique_id;
1950 get_unique_id(app_id, cert_date, &unique_id);
1951
1952 // Generating a new key with the same parameters should give the same unique ID.
1953 vector<uint8_t> unique_id2;
1954 get_unique_id(app_id, cert_date, &unique_id2);
1955 EXPECT_EQ(unique_id, unique_id2);
1956
1957 // Generating a new key with a slightly different date should give the same unique ID.
1958 uint64_t rounded_date = cert_date / 2592000000LLU;
1959 uint64_t min_date = rounded_date * 2592000000LLU;
1960 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
1961
1962 vector<uint8_t> unique_id3;
1963 get_unique_id(app_id, min_date, &unique_id3);
1964 EXPECT_EQ(unique_id, unique_id3);
1965
1966 vector<uint8_t> unique_id4;
1967 get_unique_id(app_id, max_date, &unique_id4);
1968 EXPECT_EQ(unique_id, unique_id4);
1969
1970 // A different attestation application ID should yield a different unique ID.
1971 auto app_id2 = "different_foo";
1972 vector<uint8_t> unique_id5;
1973 get_unique_id(app_id2, cert_date, &unique_id5);
1974 EXPECT_NE(unique_id, unique_id5);
1975
1976 // A radically different date should yield a different unique ID.
1977 vector<uint8_t> unique_id6;
1978 get_unique_id(app_id, 1611621648000, &unique_id6);
1979 EXPECT_NE(unique_id, unique_id6);
1980
1981 vector<uint8_t> unique_id7;
1982 get_unique_id(app_id, max_date + 1, &unique_id7);
1983 EXPECT_NE(unique_id, unique_id7);
1984
1985 vector<uint8_t> unique_id8;
1986 get_unique_id(app_id, min_date - 1, &unique_id8);
1987 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00001988
1989 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
1990 vector<uint8_t> unique_id9;
1991 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
1992 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01001993}
1994
1995/*
David Drysdale37af4b32021-05-14 16:46:59 +01001996 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1997 *
1998 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1999 */
2000TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2001 auto challenge = "hello";
2002 auto attest_app_id = "foo";
2003 auto subject = "cert subj 2";
2004 vector<uint8_t> subject_der(make_name_from_str(subject));
2005 uint64_t serial_int = 0x1010;
2006 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2007
2008 // Earlier versions of the attestation extension schema included a slot:
2009 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2010 // This should never have been included, and should never be filled in.
2011 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2012 // to confirm that this field never makes it into the attestation extension.
2013 vector<uint8_t> key_blob;
2014 vector<KeyCharacteristics> key_characteristics;
2015 auto result = GenerateKey(AuthorizationSetBuilder()
2016 .Authorization(TAG_NO_AUTH_REQUIRED)
2017 .EcdsaSigningKey(EcCurve::P_256)
2018 .Digest(Digest::NONE)
2019 .AttestationChallenge(challenge)
2020 .AttestationApplicationId(attest_app_id)
2021 .Authorization(TAG_APPLICATION_ID, "client_id")
2022 .Authorization(TAG_APPLICATION_DATA, "appdata")
2023 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2024 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2025 .SetDefaultValidity(),
2026 &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002027 // Strongbox may not support factory provisioned attestation key.
2028 if (SecLevel() == SecurityLevel::STRONGBOX) {
2029 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2030 }
David Drysdale37af4b32021-05-14 16:46:59 +01002031 ASSERT_EQ(result, ErrorCode::OK);
2032 ASSERT_GT(key_blob.size(), 0U);
2033
2034 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2035 ASSERT_GT(cert_chain_.size(), 0);
2036 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2037
2038 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2039 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002040 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2041 hw_enforced, SecLevel(),
2042 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002043
2044 // Check that the app id is not in the cert.
2045 string app_id = "clientid";
2046 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2047 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2048 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2049 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2050 cert_chain_[0].encodedCertificate.end());
2051
2052 CheckedDeleteKey(&key_blob);
2053}
2054
2055/*
Selene Huang4f64c222021-04-13 19:54:36 -07002056 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2057 *
2058 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2059 * the key will generate a self signed attestation.
2060 */
2061TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002062 auto subject = "cert subj 2";
2063 vector<uint8_t> subject_der(make_name_from_str(subject));
2064
2065 uint64_t serial_int = 0x123456FFF1234;
2066 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2067
David Drysdaledf09e542021-06-08 15:46:11 +01002068 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002069 vector<uint8_t> key_blob;
2070 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002071 ASSERT_EQ(ErrorCode::OK,
2072 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002073 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002074 .Digest(Digest::NONE)
2075 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2076 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2077 .SetDefaultValidity(),
2078 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002079 ASSERT_GT(key_blob.size(), 0U);
2080 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002081 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002082
2083 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2084
2085 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002086 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002087
2088 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07002089 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002090 ASSERT_EQ(cert_chain_.size(), 1);
2091
2092 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2093 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2094
2095 CheckedDeleteKey(&key_blob);
2096 }
2097}
2098
2099/*
2100 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2101 *
2102 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2103 * app id must also be provided or else it will fail.
2104 */
2105TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2106 auto challenge = "hello";
2107 vector<uint8_t> key_blob;
2108 vector<KeyCharacteristics> key_characteristics;
2109
subrahmanyaman05642492022-02-05 07:10:56 +00002110 auto result = GenerateKey(AuthorizationSetBuilder()
2111 .EcdsaSigningKey(EcCurve::P_256)
2112 .Digest(Digest::NONE)
2113 .AttestationChallenge(challenge)
2114 .SetDefaultValidity(),
2115 &key_blob, &key_characteristics);
2116 // Strongbox may not support factory provisioned attestation key.
2117 if (SecLevel() == SecurityLevel::STRONGBOX) {
2118 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2119 }
2120 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002121}
2122
2123/*
2124 * NewKeyGenerationTest.EcdsaIgnoreAppId
2125 *
2126 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2127 * any appid will be ignored, and keymint will generate a self sign certificate.
2128 */
2129TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2130 auto app_id = "foo";
2131
David Drysdaledf09e542021-06-08 15:46:11 +01002132 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002133 vector<uint8_t> key_blob;
2134 vector<KeyCharacteristics> key_characteristics;
2135 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002136 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002137 .Digest(Digest::NONE)
2138 .AttestationApplicationId(app_id)
2139 .SetDefaultValidity(),
2140 &key_blob, &key_characteristics));
2141
2142 ASSERT_GT(key_blob.size(), 0U);
2143 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002144 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002145
2146 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2147
2148 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002149 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002150
2151 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2152 ASSERT_EQ(cert_chain_.size(), 1);
2153
2154 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2155 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2156
2157 CheckedDeleteKey(&key_blob);
2158 }
2159}
2160
2161/*
2162 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2163 *
2164 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2165 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2166 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2167 * to specify how many following bytes will be used to encode the length.
2168 */
2169TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2170 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002171 std::vector<uint32_t> app_id_lengths{143, 258};
2172
2173 for (uint32_t length : app_id_lengths) {
2174 const string app_id(length, 'a');
2175 vector<uint8_t> key_blob;
2176 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman05642492022-02-05 07:10:56 +00002177 auto result = GenerateKey(AuthorizationSetBuilder()
2178 .Authorization(TAG_NO_AUTH_REQUIRED)
2179 .EcdsaSigningKey(EcCurve::P_256)
2180 .Digest(Digest::NONE)
2181 .AttestationChallenge(challenge)
2182 .AttestationApplicationId(app_id)
2183 .SetDefaultValidity(),
2184 &key_blob, &key_characteristics);
2185 // Strongbox may not support factory provisioned attestation key.
2186 if (SecLevel() == SecurityLevel::STRONGBOX) {
2187 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2188 }
2189 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002190 ASSERT_GT(key_blob.size(), 0U);
2191 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002192 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002193
2194 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2195
2196 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002197 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002198
2199 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2200 ASSERT_GT(cert_chain_.size(), 0);
2201
2202 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2203 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002204 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002205 sw_enforced, hw_enforced, SecLevel(),
2206 cert_chain_[0].encodedCertificate));
2207
2208 CheckedDeleteKey(&key_blob);
2209 }
2210}
2211
2212/*
Qi Wud22ec842020-11-26 13:27:53 +08002213 * NewKeyGenerationTest.LimitedUsageEcdsa
2214 *
2215 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2216 * resulting keys have correct characteristics.
2217 */
2218TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002219 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08002220 vector<uint8_t> key_blob;
2221 vector<KeyCharacteristics> key_characteristics;
2222 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002223 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002224 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002225 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2226 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002227 &key_blob, &key_characteristics));
2228
2229 ASSERT_GT(key_blob.size(), 0U);
2230 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002231 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002232
2233 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2234
2235 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002236 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002237
2238 // Check the usage count limit tag appears in the authorizations.
2239 AuthorizationSet auths;
2240 for (auto& entry : key_characteristics) {
2241 auths.push_back(AuthorizationSet(entry.authorizations));
2242 }
2243 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2244 << "key usage count limit " << 1U << " missing";
2245
2246 CheckedDeleteKey(&key_blob);
2247 }
2248}
2249
2250/*
Selene Huang31ab4042020-04-29 04:22:39 -07002251 * NewKeyGenerationTest.EcdsaDefaultSize
2252 *
David Drysdaledf09e542021-06-08 15:46:11 +01002253 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002254 * UNSUPPORTED_KEY_SIZE.
2255 */
2256TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2257 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2258 GenerateKey(AuthorizationSetBuilder()
2259 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2260 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002261 .Digest(Digest::NONE)
2262 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002263}
2264
2265/*
David Drysdale42fe1892021-10-14 14:43:46 +01002266 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002267 *
David Drysdale42fe1892021-10-14 14:43:46 +01002268 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002269 * UNSUPPORTED_KEY_SIZE.
2270 */
David Drysdale42fe1892021-10-14 14:43:46 +01002271TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002272 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07002273 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002274 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002275 auto result = GenerateKey(AuthorizationSetBuilder()
2276 .EcdsaSigningKey(curve)
2277 .Digest(Digest::NONE)
2278 .SetDefaultValidity(),
2279 &key_blob, &key_characteristics);
2280 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2281 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002282 }
2283
David Drysdaledf09e542021-06-08 15:46:11 +01002284 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2285 GenerateKey(AuthorizationSetBuilder()
2286 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2287 .Authorization(TAG_KEY_SIZE, 190)
2288 .SigningKey()
2289 .Digest(Digest::NONE)
2290 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002291}
2292
2293/*
2294 * NewKeyGenerationTest.EcdsaMismatchKeySize
2295 *
2296 * Verifies that specifying mismatched key size and curve for EC key generation returns
2297 * INVALID_ARGUMENT.
2298 */
2299TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002300 if (SecLevel() == SecurityLevel::STRONGBOX) {
2301 GTEST_SKIP() << "Test not applicable to StrongBox device";
2302 }
Selene Huang31ab4042020-04-29 04:22:39 -07002303
David Drysdaledf09e542021-06-08 15:46:11 +01002304 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002305 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002306 .Authorization(TAG_KEY_SIZE, 224)
2307 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002308 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002309 .Digest(Digest::NONE)
2310 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002311 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002312}
2313
2314/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002315 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002316 *
2317 * Verifies that keymint does not support any curve designated as unsupported.
2318 */
2319TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2320 Digest digest;
2321 if (SecLevel() == SecurityLevel::STRONGBOX) {
2322 digest = Digest::SHA_2_256;
2323 } else {
2324 digest = Digest::SHA_2_512;
2325 }
2326 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08002327 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2328 .EcdsaSigningKey(curve)
2329 .Digest(digest)
2330 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002331 << "Failed to generate key on curve: " << curve;
2332 CheckedDeleteKey();
2333 }
2334}
2335
2336/*
2337 * NewKeyGenerationTest.Hmac
2338 *
2339 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2340 * characteristics.
2341 */
2342TEST_P(NewKeyGenerationTest, Hmac) {
2343 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2344 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002345 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002346 constexpr size_t key_size = 128;
2347 ASSERT_EQ(ErrorCode::OK,
2348 GenerateKey(
2349 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2350 TAG_MIN_MAC_LENGTH, 128),
2351 &key_blob, &key_characteristics));
2352
2353 ASSERT_GT(key_blob.size(), 0U);
2354 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002355 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002356
Shawn Willden7f424372021-01-10 18:06:50 -07002357 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2358 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2359 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2360 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002361
2362 CheckedDeleteKey(&key_blob);
2363 }
2364}
2365
2366/*
Selene Huang4f64c222021-04-13 19:54:36 -07002367 * NewKeyGenerationTest.HmacNoAttestation
2368 *
2369 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2370 * and app id are provided.
2371 */
2372TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2373 auto challenge = "hello";
2374 auto app_id = "foo";
2375
2376 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2377 vector<uint8_t> key_blob;
2378 vector<KeyCharacteristics> key_characteristics;
2379 constexpr size_t key_size = 128;
2380 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2381 .HmacKey(key_size)
2382 .Digest(digest)
2383 .AttestationChallenge(challenge)
2384 .AttestationApplicationId(app_id)
2385 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2386 &key_blob, &key_characteristics));
2387
2388 ASSERT_GT(key_blob.size(), 0U);
2389 ASSERT_EQ(cert_chain_.size(), 0);
2390 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002391 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002392
2393 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2394 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2395 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2396 << "Key size " << key_size << "missing";
2397
2398 CheckedDeleteKey(&key_blob);
2399 }
2400}
2401
2402/*
Qi Wud22ec842020-11-26 13:27:53 +08002403 * NewKeyGenerationTest.LimitedUsageHmac
2404 *
2405 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2406 * resulting keys have correct characteristics.
2407 */
2408TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2409 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2410 vector<uint8_t> key_blob;
2411 vector<KeyCharacteristics> key_characteristics;
2412 constexpr size_t key_size = 128;
2413 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2414 .HmacKey(key_size)
2415 .Digest(digest)
2416 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2417 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2418 &key_blob, &key_characteristics));
2419
2420 ASSERT_GT(key_blob.size(), 0U);
2421 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002422 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002423
2424 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2425 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2426 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2427 << "Key size " << key_size << "missing";
2428
2429 // Check the usage count limit tag appears in the authorizations.
2430 AuthorizationSet auths;
2431 for (auto& entry : key_characteristics) {
2432 auths.push_back(AuthorizationSet(entry.authorizations));
2433 }
2434 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2435 << "key usage count limit " << 1U << " missing";
2436
2437 CheckedDeleteKey(&key_blob);
2438 }
2439}
2440
2441/*
Selene Huang31ab4042020-04-29 04:22:39 -07002442 * NewKeyGenerationTest.HmacCheckKeySizes
2443 *
2444 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2445 */
2446TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2447 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2448 if (key_size < 64 || key_size % 8 != 0) {
2449 // To keep this test from being very slow, we only test a random fraction of
2450 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2451 // them, we expect to run ~40 of them in each run.
2452 if (key_size % 8 == 0 || random() % 10 == 0) {
2453 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2454 GenerateKey(AuthorizationSetBuilder()
2455 .HmacKey(key_size)
2456 .Digest(Digest::SHA_2_256)
2457 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2458 << "HMAC key size " << key_size << " invalid";
2459 }
2460 } else {
2461 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2462 .HmacKey(key_size)
2463 .Digest(Digest::SHA_2_256)
2464 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2465 << "Failed to generate HMAC key of size " << key_size;
2466 CheckedDeleteKey();
2467 }
2468 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002469 if (SecLevel() == SecurityLevel::STRONGBOX) {
2470 // STRONGBOX devices must not support keys larger than 512 bits.
2471 size_t key_size = 520;
2472 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2473 GenerateKey(AuthorizationSetBuilder()
2474 .HmacKey(key_size)
2475 .Digest(Digest::SHA_2_256)
2476 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2477 << "HMAC key size " << key_size << " unexpectedly valid";
2478 }
Selene Huang31ab4042020-04-29 04:22:39 -07002479}
2480
2481/*
2482 * NewKeyGenerationTest.HmacCheckMinMacLengths
2483 *
2484 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2485 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2486 * specific MAC length that failed, so reproducing a failed run will be easy.
2487 */
2488TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2489 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2490 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2491 // To keep this test from being very long, we only test a random fraction of
2492 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2493 // we expect to run ~17 of them in each run.
2494 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2495 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2496 GenerateKey(AuthorizationSetBuilder()
2497 .HmacKey(128)
2498 .Digest(Digest::SHA_2_256)
2499 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2500 << "HMAC min mac length " << min_mac_length << " invalid.";
2501 }
2502 } else {
2503 EXPECT_EQ(ErrorCode::OK,
2504 GenerateKey(AuthorizationSetBuilder()
2505 .HmacKey(128)
2506 .Digest(Digest::SHA_2_256)
2507 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2508 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2509 CheckedDeleteKey();
2510 }
2511 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002512
2513 // Minimum MAC length must be no more than 512 bits.
2514 size_t min_mac_length = 520;
2515 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2516 GenerateKey(AuthorizationSetBuilder()
2517 .HmacKey(128)
2518 .Digest(Digest::SHA_2_256)
2519 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2520 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002521}
2522
2523/*
2524 * NewKeyGenerationTest.HmacMultipleDigests
2525 *
2526 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2527 */
2528TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002529 if (SecLevel() == SecurityLevel::STRONGBOX) {
2530 GTEST_SKIP() << "Test not applicable to StrongBox device";
2531 }
Selene Huang31ab4042020-04-29 04:22:39 -07002532
2533 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2534 GenerateKey(AuthorizationSetBuilder()
2535 .HmacKey(128)
2536 .Digest(Digest::SHA1)
2537 .Digest(Digest::SHA_2_256)
2538 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2539}
2540
2541/*
2542 * NewKeyGenerationTest.HmacDigestNone
2543 *
2544 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2545 */
2546TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2547 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2548 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2549 128)));
2550
2551 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2552 GenerateKey(AuthorizationSetBuilder()
2553 .HmacKey(128)
2554 .Digest(Digest::NONE)
2555 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2556}
2557
Selene Huang4f64c222021-04-13 19:54:36 -07002558/*
2559 * NewKeyGenerationTest.AesNoAttestation
2560 *
2561 * Verifies that attestation parameters to AES keys are ignored and generateKey
2562 * will succeed.
2563 */
2564TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2565 auto challenge = "hello";
2566 auto app_id = "foo";
2567
2568 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2569 .Authorization(TAG_NO_AUTH_REQUIRED)
2570 .AesEncryptionKey(128)
2571 .EcbMode()
2572 .Padding(PaddingMode::PKCS7)
2573 .AttestationChallenge(challenge)
2574 .AttestationApplicationId(app_id)));
2575
2576 ASSERT_EQ(cert_chain_.size(), 0);
2577}
2578
2579/*
2580 * NewKeyGenerationTest.TripleDesNoAttestation
2581 *
2582 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2583 * will be successful. No attestation should be generated.
2584 */
2585TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2586 auto challenge = "hello";
2587 auto app_id = "foo";
2588
2589 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2590 .TripleDesEncryptionKey(168)
2591 .BlockMode(BlockMode::ECB)
2592 .Authorization(TAG_NO_AUTH_REQUIRED)
2593 .Padding(PaddingMode::NONE)
2594 .AttestationChallenge(challenge)
2595 .AttestationApplicationId(app_id)));
2596 ASSERT_EQ(cert_chain_.size(), 0);
2597}
2598
Selene Huang31ab4042020-04-29 04:22:39 -07002599INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2600
2601typedef KeyMintAidlTestBase SigningOperationsTest;
2602
2603/*
2604 * SigningOperationsTest.RsaSuccess
2605 *
2606 * Verifies that raw RSA signature operations succeed.
2607 */
2608TEST_P(SigningOperationsTest, RsaSuccess) {
2609 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2610 .RsaSigningKey(2048, 65537)
2611 .Digest(Digest::NONE)
2612 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002613 .Authorization(TAG_NO_AUTH_REQUIRED)
2614 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002615 string message = "12345678901234567890123456789012";
2616 string signature = SignMessage(
2617 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002618 LocalVerifyMessage(message, signature,
2619 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2620}
2621
2622/*
2623 * SigningOperationsTest.RsaAllPaddingsAndDigests
2624 *
2625 * Verifies RSA signature/verification for all padding modes and digests.
2626 */
2627TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2628 auto authorizations = AuthorizationSetBuilder()
2629 .Authorization(TAG_NO_AUTH_REQUIRED)
2630 .RsaSigningKey(2048, 65537)
2631 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2632 .Padding(PaddingMode::NONE)
2633 .Padding(PaddingMode::RSA_PSS)
2634 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2635 .SetDefaultValidity();
2636
2637 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2638
2639 string message(128, 'a');
2640 string corrupt_message(message);
2641 ++corrupt_message[corrupt_message.size() / 2];
2642
2643 for (auto padding :
2644 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2645 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2646 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2647 // Digesting only makes sense with padding.
2648 continue;
2649 }
2650
2651 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2652 // PSS requires digesting.
2653 continue;
2654 }
2655
2656 string signature =
2657 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2658 LocalVerifyMessage(message, signature,
2659 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2660 }
2661 }
Selene Huang31ab4042020-04-29 04:22:39 -07002662}
2663
2664/*
2665 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2666 *
Shawn Willden7f424372021-01-10 18:06:50 -07002667 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002668 */
2669TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2670 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2671 .Authorization(TAG_NO_AUTH_REQUIRED)
2672 .RsaSigningKey(2048, 65537)
2673 .Digest(Digest::NONE)
2674 .Padding(PaddingMode::NONE)
2675 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002676 .Authorization(TAG_APPLICATION_DATA, "appdata")
2677 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002678
2679 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2680
Selene Huang31ab4042020-04-29 04:22:39 -07002681 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2682 Begin(KeyPurpose::SIGN,
2683 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2684 AbortIfNeeded();
2685 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2686 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2687 .Digest(Digest::NONE)
2688 .Padding(PaddingMode::NONE)
2689 .Authorization(TAG_APPLICATION_ID, "clientid")));
2690 AbortIfNeeded();
2691 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2692 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2693 .Digest(Digest::NONE)
2694 .Padding(PaddingMode::NONE)
2695 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2696 AbortIfNeeded();
2697 EXPECT_EQ(ErrorCode::OK,
2698 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2699 .Digest(Digest::NONE)
2700 .Padding(PaddingMode::NONE)
2701 .Authorization(TAG_APPLICATION_DATA, "appdata")
2702 .Authorization(TAG_APPLICATION_ID, "clientid")));
2703 AbortIfNeeded();
2704}
2705
2706/*
2707 * SigningOperationsTest.RsaPssSha256Success
2708 *
2709 * Verifies that RSA-PSS signature operations succeed.
2710 */
2711TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2712 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2713 .RsaSigningKey(2048, 65537)
2714 .Digest(Digest::SHA_2_256)
2715 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002716 .Authorization(TAG_NO_AUTH_REQUIRED)
2717 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002718 // Use large message, which won't work without digesting.
2719 string message(1024, 'a');
2720 string signature = SignMessage(
2721 message,
2722 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2723}
2724
2725/*
2726 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2727 *
2728 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2729 * supports only unpadded operations.
2730 */
2731TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2732 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2733 .RsaSigningKey(2048, 65537)
2734 .Digest(Digest::NONE)
2735 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002736 .Padding(PaddingMode::NONE)
2737 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002738 string message = "12345678901234567890123456789012";
2739 string signature;
2740
2741 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2742 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2743 .Digest(Digest::NONE)
2744 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2745}
2746
2747/*
2748 * SigningOperationsTest.NoUserConfirmation
2749 *
2750 * Verifies that keymint rejects signing operations for keys with
2751 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2752 * presented.
2753 */
2754TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002755 if (SecLevel() == SecurityLevel::STRONGBOX) {
2756 GTEST_SKIP() << "Test not applicable to StrongBox device";
2757 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002758 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2759 .RsaSigningKey(1024, 65537)
2760 .Digest(Digest::NONE)
2761 .Padding(PaddingMode::NONE)
2762 .Authorization(TAG_NO_AUTH_REQUIRED)
2763 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2764 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002765
2766 const string message = "12345678901234567890123456789012";
2767 EXPECT_EQ(ErrorCode::OK,
2768 Begin(KeyPurpose::SIGN,
2769 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2770 string signature;
2771 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2772}
2773
2774/*
2775 * SigningOperationsTest.RsaPkcs1Sha256Success
2776 *
2777 * Verifies that digested RSA-PKCS1 signature operations succeed.
2778 */
2779TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2780 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2781 .RsaSigningKey(2048, 65537)
2782 .Digest(Digest::SHA_2_256)
2783 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002784 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2785 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002786 string message(1024, 'a');
2787 string signature = SignMessage(message, AuthorizationSetBuilder()
2788 .Digest(Digest::SHA_2_256)
2789 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2790}
2791
2792/*
2793 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2794 *
2795 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2796 */
2797TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2798 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2799 .RsaSigningKey(2048, 65537)
2800 .Digest(Digest::NONE)
2801 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002802 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2803 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002804 string message(53, 'a');
2805 string signature = SignMessage(message, AuthorizationSetBuilder()
2806 .Digest(Digest::NONE)
2807 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2808}
2809
2810/*
2811 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2812 *
2813 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2814 * given a too-long message.
2815 */
2816TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2817 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2818 .RsaSigningKey(2048, 65537)
2819 .Digest(Digest::NONE)
2820 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002821 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2822 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002823 string message(257, 'a');
2824
2825 EXPECT_EQ(ErrorCode::OK,
2826 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2827 .Digest(Digest::NONE)
2828 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2829 string signature;
2830 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2831}
2832
2833/*
2834 * SigningOperationsTest.RsaPssSha512TooSmallKey
2835 *
2836 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2837 * used with a key that is too small for the message.
2838 *
2839 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2840 * keymint specification requires that salt_size == digest_size, so the message will be
2841 * digest_size * 2 +
2842 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2843 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2844 * for a 1024-bit key.
2845 */
2846TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01002847 if (SecLevel() == SecurityLevel::STRONGBOX) {
2848 GTEST_SKIP() << "Test not applicable to StrongBox device";
2849 }
Selene Huang31ab4042020-04-29 04:22:39 -07002850 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2851 .RsaSigningKey(1024, 65537)
2852 .Digest(Digest::SHA_2_512)
2853 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002854 .Padding(PaddingMode::RSA_PSS)
2855 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002856 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2857 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2858 .Digest(Digest::SHA_2_512)
2859 .Padding(PaddingMode::RSA_PSS)));
2860}
2861
2862/*
2863 * SigningOperationsTest.RsaNoPaddingTooLong
2864 *
2865 * Verifies that raw RSA signature operations fail with the correct error code when
2866 * given a too-long message.
2867 */
2868TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2869 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2870 .RsaSigningKey(2048, 65537)
2871 .Digest(Digest::NONE)
2872 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002873 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2874 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002875 // One byte too long
2876 string message(2048 / 8 + 1, 'a');
2877 ASSERT_EQ(ErrorCode::OK,
2878 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2879 .Digest(Digest::NONE)
2880 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2881 string result;
2882 ErrorCode finish_error_code = Finish(message, &result);
2883 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2884 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2885
2886 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2887 message = string(128 * 1024, 'a');
2888 ASSERT_EQ(ErrorCode::OK,
2889 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2890 .Digest(Digest::NONE)
2891 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2892 finish_error_code = Finish(message, &result);
2893 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2894 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2895}
2896
2897/*
2898 * SigningOperationsTest.RsaAbort
2899 *
2900 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2901 * test, but the behavior should be algorithm and purpose-independent.
2902 */
2903TEST_P(SigningOperationsTest, RsaAbort) {
2904 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2905 .RsaSigningKey(2048, 65537)
2906 .Digest(Digest::NONE)
2907 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002908 .Padding(PaddingMode::NONE)
2909 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002910
2911 ASSERT_EQ(ErrorCode::OK,
2912 Begin(KeyPurpose::SIGN,
2913 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2914 EXPECT_EQ(ErrorCode::OK, Abort());
2915
2916 // Another abort should fail
2917 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2918
2919 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002920 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002921}
2922
2923/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002924 * SigningOperationsTest.RsaNonUniqueParams
2925 *
2926 * Verifies that an operation with multiple padding modes is rejected.
2927 */
2928TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2929 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2930 .RsaSigningKey(2048, 65537)
2931 .Digest(Digest::NONE)
2932 .Digest(Digest::SHA1)
2933 .Authorization(TAG_NO_AUTH_REQUIRED)
2934 .Padding(PaddingMode::NONE)
2935 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2936 .SetDefaultValidity()));
2937
2938 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2939 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2940 .Digest(Digest::NONE)
2941 .Padding(PaddingMode::NONE)
2942 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2943
Tommy Chiuc93c4392021-05-11 18:36:50 +08002944 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2945 .Digest(Digest::NONE)
2946 .Digest(Digest::SHA1)
2947 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2948 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002949
2950 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2951 Begin(KeyPurpose::SIGN,
2952 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2953}
2954
2955/*
Selene Huang31ab4042020-04-29 04:22:39 -07002956 * SigningOperationsTest.RsaUnsupportedPadding
2957 *
2958 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2959 * with a padding mode inappropriate for RSA.
2960 */
2961TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2962 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2963 .RsaSigningKey(2048, 65537)
2964 .Authorization(TAG_NO_AUTH_REQUIRED)
2965 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002966 .Padding(PaddingMode::PKCS7)
2967 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002968 ASSERT_EQ(
2969 ErrorCode::UNSUPPORTED_PADDING_MODE,
2970 Begin(KeyPurpose::SIGN,
2971 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002972 CheckedDeleteKey();
2973
2974 ASSERT_EQ(ErrorCode::OK,
2975 GenerateKey(
2976 AuthorizationSetBuilder()
2977 .RsaSigningKey(2048, 65537)
2978 .Authorization(TAG_NO_AUTH_REQUIRED)
2979 .Digest(Digest::SHA_2_256 /* supported digest */)
2980 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2981 .SetDefaultValidity()));
2982 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2983 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2984 .Digest(Digest::SHA_2_256)
2985 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002986}
2987
2988/*
2989 * SigningOperationsTest.RsaPssNoDigest
2990 *
2991 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2992 */
2993TEST_P(SigningOperationsTest, RsaNoDigest) {
2994 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2995 .RsaSigningKey(2048, 65537)
2996 .Authorization(TAG_NO_AUTH_REQUIRED)
2997 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002998 .Padding(PaddingMode::RSA_PSS)
2999 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003000 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3001 Begin(KeyPurpose::SIGN,
3002 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3003
3004 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3005 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3006}
3007
3008/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003009 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003010 *
3011 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3012 * supported in some cases (as validated in other tests), but a mode must be specified.
3013 */
3014TEST_P(SigningOperationsTest, RsaNoPadding) {
3015 // Padding must be specified
3016 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3017 .RsaKey(2048, 65537)
3018 .Authorization(TAG_NO_AUTH_REQUIRED)
3019 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003020 .Digest(Digest::NONE)
3021 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003022 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3023 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3024}
3025
3026/*
3027 * SigningOperationsTest.RsaShortMessage
3028 *
3029 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3030 */
3031TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3032 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3033 .Authorization(TAG_NO_AUTH_REQUIRED)
3034 .RsaSigningKey(2048, 65537)
3035 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003036 .Padding(PaddingMode::NONE)
3037 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003038
3039 // Barely shorter
3040 string message(2048 / 8 - 1, 'a');
3041 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3042
3043 // Much shorter
3044 message = "a";
3045 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3046}
3047
3048/*
3049 * SigningOperationsTest.RsaSignWithEncryptionKey
3050 *
3051 * Verifies that RSA encryption keys cannot be used to sign.
3052 */
3053TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3054 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3055 .Authorization(TAG_NO_AUTH_REQUIRED)
3056 .RsaEncryptionKey(2048, 65537)
3057 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003058 .Padding(PaddingMode::NONE)
3059 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003060 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3061 Begin(KeyPurpose::SIGN,
3062 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3063}
3064
3065/*
3066 * SigningOperationsTest.RsaSignTooLargeMessage
3067 *
3068 * Verifies that attempting a raw signature of a message which is the same length as the key,
3069 * but numerically larger than the public modulus, fails with the correct error.
3070 */
3071TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3072 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3073 .Authorization(TAG_NO_AUTH_REQUIRED)
3074 .RsaSigningKey(2048, 65537)
3075 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003076 .Padding(PaddingMode::NONE)
3077 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003078
3079 // Largest possible message will always be larger than the public modulus.
3080 string message(2048 / 8, static_cast<char>(0xff));
3081 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3082 .Authorization(TAG_NO_AUTH_REQUIRED)
3083 .Digest(Digest::NONE)
3084 .Padding(PaddingMode::NONE)));
3085 string signature;
3086 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3087}
3088
3089/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003090 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3091 *
David Drysdale42fe1892021-10-14 14:43:46 +01003092 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003093 */
3094TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003095
3096 string message = "1234567890";
3097 string corrupt_message = "2234567890";
3098 for (auto curve : ValidCurves()) {
3099 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003100 // Ed25519 only allows Digest::NONE.
3101 auto digests = (curve == EcCurve::CURVE_25519)
3102 ? std::vector<Digest>(1, Digest::NONE)
3103 : ValidDigests(true /* withNone */, false /* withMD5 */);
3104
David Drysdaledf8f52e2021-05-06 08:10:58 +01003105 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3106 .Authorization(TAG_NO_AUTH_REQUIRED)
3107 .EcdsaSigningKey(curve)
3108 .Digest(digests)
3109 .SetDefaultValidity());
3110 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3111 if (error != ErrorCode::OK) {
3112 continue;
3113 }
3114
3115 for (auto digest : digests) {
3116 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3117 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3118 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3119 }
3120
3121 auto rc = DeleteKey();
3122 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3123 }
3124}
3125
3126/*
Selene Huang31ab4042020-04-29 04:22:39 -07003127 * SigningOperationsTest.EcdsaAllCurves
3128 *
David Drysdale42fe1892021-10-14 14:43:46 +01003129 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003130 */
3131TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3132 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003133 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3134 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003135 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3136 .Authorization(TAG_NO_AUTH_REQUIRED)
3137 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003138 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003139 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003140 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3141 if (error != ErrorCode::OK) continue;
3142
3143 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003144 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003145 CheckedDeleteKey();
3146 }
3147}
3148
3149/*
David Drysdale42fe1892021-10-14 14:43:46 +01003150 * SigningOperationsTest.EcdsaCurve25519
3151 *
3152 * Verifies that ECDSA operations succeed with curve25519.
3153 */
3154TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3155 if (!Curve25519Supported()) {
3156 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3157 }
3158
3159 EcCurve curve = EcCurve::CURVE_25519;
3160 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3161 .Authorization(TAG_NO_AUTH_REQUIRED)
3162 .EcdsaSigningKey(curve)
3163 .Digest(Digest::NONE)
3164 .SetDefaultValidity());
3165 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3166
3167 string message(1024, 'a');
3168 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3169 CheckedDeleteKey();
3170}
3171
3172/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003173 * SigningOperationsTest.EcdsaCurve25519MaxSize
3174 *
3175 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3176 */
3177TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3178 if (!Curve25519Supported()) {
3179 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3180 }
3181
3182 EcCurve curve = EcCurve::CURVE_25519;
3183 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3184 .Authorization(TAG_NO_AUTH_REQUIRED)
3185 .EcdsaSigningKey(curve)
3186 .Digest(Digest::NONE)
3187 .SetDefaultValidity());
3188 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3189
3190 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3191
3192 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3193 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3194 string message(msg_size, 'a');
3195
3196 // Attempt to sign via Begin+Finish.
3197 AuthorizationSet out_params;
3198 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3199 EXPECT_TRUE(out_params.empty());
3200 string signature;
3201 auto result = Finish(message, &signature);
3202 EXPECT_EQ(result, ErrorCode::OK);
3203 LocalVerifyMessage(message, signature, params);
3204
3205 // Attempt to sign via Begin+Update+Finish
3206 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3207 EXPECT_TRUE(out_params.empty());
3208 string output;
3209 result = Update(message, &output);
3210 EXPECT_EQ(result, ErrorCode::OK);
3211 EXPECT_EQ(output.size(), 0);
3212 string signature2;
3213 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3214 LocalVerifyMessage(message, signature2, params);
3215 }
3216
3217 CheckedDeleteKey();
3218}
3219
3220/*
3221 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3222 *
3223 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3224 */
3225TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3226 if (!Curve25519Supported()) {
3227 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3228 }
3229
3230 EcCurve curve = EcCurve::CURVE_25519;
3231 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3232 .Authorization(TAG_NO_AUTH_REQUIRED)
3233 .EcdsaSigningKey(curve)
3234 .Digest(Digest::NONE)
3235 .SetDefaultValidity());
3236 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3237
3238 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3239
3240 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3241 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3242 string message(msg_size, 'a');
3243
3244 // Attempt to sign via Begin+Finish.
3245 AuthorizationSet out_params;
3246 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3247 EXPECT_TRUE(out_params.empty());
3248 string signature;
3249 auto result = Finish(message, &signature);
3250 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3251
3252 // Attempt to sign via Begin+Update (but never get to Finish)
3253 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3254 EXPECT_TRUE(out_params.empty());
3255 string output;
3256 result = Update(message, &output);
3257 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3258 }
3259
3260 CheckedDeleteKey();
3261}
3262
3263/*
Selene Huang31ab4042020-04-29 04:22:39 -07003264 * SigningOperationsTest.EcdsaNoDigestHugeData
3265 *
3266 * Verifies that ECDSA operations support very large messages, even without digesting. This
3267 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3268 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3269 * the framework.
3270 */
3271TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3272 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3273 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003274 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003275 .Digest(Digest::NONE)
3276 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003277 string message(1 * 1024, 'a');
3278 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3279}
3280
3281/*
3282 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3283 *
3284 * Verifies that using an EC key requires the correct app ID/data.
3285 */
3286TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3287 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3288 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003289 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003290 .Digest(Digest::NONE)
3291 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003292 .Authorization(TAG_APPLICATION_DATA, "appdata")
3293 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003294
3295 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3296
Selene Huang31ab4042020-04-29 04:22:39 -07003297 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3298 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3299 AbortIfNeeded();
3300 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3301 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3302 .Digest(Digest::NONE)
3303 .Authorization(TAG_APPLICATION_ID, "clientid")));
3304 AbortIfNeeded();
3305 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3306 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3307 .Digest(Digest::NONE)
3308 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3309 AbortIfNeeded();
3310 EXPECT_EQ(ErrorCode::OK,
3311 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3312 .Digest(Digest::NONE)
3313 .Authorization(TAG_APPLICATION_DATA, "appdata")
3314 .Authorization(TAG_APPLICATION_ID, "clientid")));
3315 AbortIfNeeded();
3316}
3317
3318/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003319 * SigningOperationsTest.EcdsaIncompatibleDigest
3320 *
3321 * Verifies that using an EC key requires compatible digest.
3322 */
3323TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3324 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3325 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003326 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003327 .Digest(Digest::NONE)
3328 .Digest(Digest::SHA1)
3329 .SetDefaultValidity()));
3330 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3331 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3332 AbortIfNeeded();
3333}
3334
3335/*
Selene Huang31ab4042020-04-29 04:22:39 -07003336 * SigningOperationsTest.AesEcbSign
3337 *
3338 * Verifies that attempts to use AES keys to sign fail in the correct way.
3339 */
3340TEST_P(SigningOperationsTest, AesEcbSign) {
3341 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3342 .Authorization(TAG_NO_AUTH_REQUIRED)
3343 .SigningKey()
3344 .AesEncryptionKey(128)
3345 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3346
3347 AuthorizationSet out_params;
3348 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3349 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3350 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3351 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3352}
3353
3354/*
3355 * SigningOperationsTest.HmacAllDigests
3356 *
3357 * Verifies that HMAC works with all digests.
3358 */
3359TEST_P(SigningOperationsTest, HmacAllDigests) {
3360 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
3361 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3362 .Authorization(TAG_NO_AUTH_REQUIRED)
3363 .HmacKey(128)
3364 .Digest(digest)
3365 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3366 << "Failed to create HMAC key with digest " << digest;
3367 string message = "12345678901234567890123456789012";
3368 string signature = MacMessage(message, digest, 160);
3369 EXPECT_EQ(160U / 8U, signature.size())
3370 << "Failed to sign with HMAC key with digest " << digest;
3371 CheckedDeleteKey();
3372 }
3373}
3374
3375/*
3376 * SigningOperationsTest.HmacSha256TooLargeMacLength
3377 *
3378 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3379 * digest size.
3380 */
3381TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3382 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3383 .Authorization(TAG_NO_AUTH_REQUIRED)
3384 .HmacKey(128)
3385 .Digest(Digest::SHA_2_256)
3386 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3387 AuthorizationSet output_params;
3388 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3389 AuthorizationSetBuilder()
3390 .Digest(Digest::SHA_2_256)
3391 .Authorization(TAG_MAC_LENGTH, 264),
3392 &output_params));
3393}
3394
3395/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003396 * SigningOperationsTest.HmacSha256InvalidMacLength
3397 *
3398 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3399 * not a multiple of 8.
3400 */
3401TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3402 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3403 .Authorization(TAG_NO_AUTH_REQUIRED)
3404 .HmacKey(128)
3405 .Digest(Digest::SHA_2_256)
3406 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3407 AuthorizationSet output_params;
3408 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3409 AuthorizationSetBuilder()
3410 .Digest(Digest::SHA_2_256)
3411 .Authorization(TAG_MAC_LENGTH, 161),
3412 &output_params));
3413}
3414
3415/*
Selene Huang31ab4042020-04-29 04:22:39 -07003416 * SigningOperationsTest.HmacSha256TooSmallMacLength
3417 *
3418 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3419 * specified minimum MAC length.
3420 */
3421TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3422 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3423 .Authorization(TAG_NO_AUTH_REQUIRED)
3424 .HmacKey(128)
3425 .Digest(Digest::SHA_2_256)
3426 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3427 AuthorizationSet output_params;
3428 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3429 AuthorizationSetBuilder()
3430 .Digest(Digest::SHA_2_256)
3431 .Authorization(TAG_MAC_LENGTH, 120),
3432 &output_params));
3433}
3434
3435/*
3436 * SigningOperationsTest.HmacRfc4231TestCase3
3437 *
3438 * Validates against the test vectors from RFC 4231 test case 3.
3439 */
3440TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3441 string key(20, 0xaa);
3442 string message(50, 0xdd);
3443 uint8_t sha_224_expected[] = {
3444 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3445 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3446 };
3447 uint8_t sha_256_expected[] = {
3448 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3449 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3450 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3451 };
3452 uint8_t sha_384_expected[] = {
3453 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3454 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3455 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3456 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3457 };
3458 uint8_t sha_512_expected[] = {
3459 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3460 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3461 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3462 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3463 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3464 };
3465
3466 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3467 if (SecLevel() != SecurityLevel::STRONGBOX) {
3468 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3469 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3470 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3471 }
3472}
3473
3474/*
3475 * SigningOperationsTest.HmacRfc4231TestCase5
3476 *
3477 * Validates against the test vectors from RFC 4231 test case 5.
3478 */
3479TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3480 string key(20, 0x0c);
3481 string message = "Test With Truncation";
3482
3483 uint8_t sha_224_expected[] = {
3484 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3485 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3486 };
3487 uint8_t sha_256_expected[] = {
3488 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3489 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3490 };
3491 uint8_t sha_384_expected[] = {
3492 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3493 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3494 };
3495 uint8_t sha_512_expected[] = {
3496 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3497 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3498 };
3499
3500 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3501 if (SecLevel() != SecurityLevel::STRONGBOX) {
3502 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3503 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3504 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3505 }
3506}
3507
3508INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3509
3510typedef KeyMintAidlTestBase VerificationOperationsTest;
3511
3512/*
Selene Huang31ab4042020-04-29 04:22:39 -07003513 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3514 *
3515 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3516 */
3517TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3518 string key_material = "HelloThisIsAKey";
3519
3520 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003521 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003522 EXPECT_EQ(ErrorCode::OK,
3523 ImportKey(AuthorizationSetBuilder()
3524 .Authorization(TAG_NO_AUTH_REQUIRED)
3525 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3526 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3527 .Digest(Digest::SHA_2_256)
3528 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3529 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3530 EXPECT_EQ(ErrorCode::OK,
3531 ImportKey(AuthorizationSetBuilder()
3532 .Authorization(TAG_NO_AUTH_REQUIRED)
3533 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3534 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3535 .Digest(Digest::SHA_2_256)
3536 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3537 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3538
3539 string message = "This is a message.";
3540 string signature = SignMessage(
3541 signing_key, message,
3542 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3543
3544 // Signing key should not work.
3545 AuthorizationSet out_params;
3546 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3547 Begin(KeyPurpose::VERIFY, signing_key,
3548 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3549
3550 // Verification key should work.
3551 VerifyMessage(verification_key, message, signature,
3552 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3553
3554 CheckedDeleteKey(&signing_key);
3555 CheckedDeleteKey(&verification_key);
3556}
3557
Prashant Patildec9fdc2021-12-08 15:25:47 +00003558/*
3559 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3560 *
3561 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3562 */
3563TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3564 string key_material = "HelloThisIsAKey";
3565
3566 vector<uint8_t> signing_key, verification_key;
3567 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3568 EXPECT_EQ(ErrorCode::OK,
3569 ImportKey(AuthorizationSetBuilder()
3570 .Authorization(TAG_NO_AUTH_REQUIRED)
3571 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3572 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3573 .Digest(Digest::SHA_2_256)
3574 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3575 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3576 EXPECT_EQ(ErrorCode::OK,
3577 ImportKey(AuthorizationSetBuilder()
3578 .Authorization(TAG_NO_AUTH_REQUIRED)
3579 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3580 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3581 .Digest(Digest::SHA_2_256)
3582 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3583 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3584
3585 string message = "This is a message.";
3586 string signature = SignMessage(
3587 signing_key, message,
3588 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3589
3590 AuthorizationSet begin_out_params;
3591 ASSERT_EQ(ErrorCode::OK,
3592 Begin(KeyPurpose::VERIFY, verification_key,
3593 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3594
3595 string corruptMessage = "This is b message."; // Corrupted message
3596 string output;
3597 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3598
3599 ASSERT_EQ(ErrorCode::OK,
3600 Begin(KeyPurpose::VERIFY, verification_key,
3601 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3602
3603 signature[0] += 1; // Corrupt a signature
3604 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3605
3606 CheckedDeleteKey(&signing_key);
3607 CheckedDeleteKey(&verification_key);
3608}
3609
Selene Huang31ab4042020-04-29 04:22:39 -07003610INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3611
3612typedef KeyMintAidlTestBase ExportKeyTest;
3613
3614/*
3615 * ExportKeyTest.RsaUnsupportedKeyFormat
3616 *
3617 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3618 */
3619// TODO(seleneh) add ExportKey to GenerateKey
3620// check result
3621
3622class ImportKeyTest : public KeyMintAidlTestBase {
3623 public:
3624 template <TagType tag_type, Tag tag, typename ValueT>
3625 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3626 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003627 for (auto& entry : key_characteristics_) {
3628 if (entry.securityLevel == SecLevel()) {
3629 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3630 << "Tag " << tag << " with value " << expected
3631 << " not found at security level" << entry.securityLevel;
3632 } else {
3633 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3634 << "Tag " << tag << " found at security level " << entry.securityLevel;
3635 }
Selene Huang31ab4042020-04-29 04:22:39 -07003636 }
3637 }
3638
3639 void CheckOrigin() {
3640 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003641 // Origin isn't a crypto param, but it always lives with them.
3642 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003643 }
3644};
3645
3646/*
3647 * ImportKeyTest.RsaSuccess
3648 *
3649 * Verifies that importing and using an RSA key pair works correctly.
3650 */
3651TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003652 uint32_t key_size;
3653 string key;
3654
3655 if (SecLevel() == SecurityLevel::STRONGBOX) {
3656 key_size = 2048;
3657 key = rsa_2048_key;
3658 } else {
3659 key_size = 1024;
3660 key = rsa_key;
3661 }
3662
Selene Huang31ab4042020-04-29 04:22:39 -07003663 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3664 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003665 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003666 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003667 .Padding(PaddingMode::RSA_PSS)
3668 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003669 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003670
3671 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003672 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003673 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3674 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3675 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3676 CheckOrigin();
3677
3678 string message(1024 / 8, 'a');
3679 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3680 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003681 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003682}
3683
3684/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003685 * ImportKeyTest.RsaSuccessWithoutParams
3686 *
3687 * Verifies that importing and using an RSA key pair without specifying parameters
3688 * works correctly.
3689 */
3690TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3691 uint32_t key_size;
3692 string key;
3693
3694 if (SecLevel() == SecurityLevel::STRONGBOX) {
3695 key_size = 2048;
3696 key = rsa_2048_key;
3697 } else {
3698 key_size = 1024;
3699 key = rsa_key;
3700 }
3701
3702 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3703 .Authorization(TAG_NO_AUTH_REQUIRED)
3704 .SigningKey()
3705 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3706 .Digest(Digest::SHA_2_256)
3707 .Padding(PaddingMode::RSA_PSS)
3708 .SetDefaultValidity(),
3709 KeyFormat::PKCS8, key));
3710
3711 // Key size and public exponent are determined from the imported key material.
3712 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3713 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3714
3715 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3716 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3717 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3718 CheckOrigin();
3719
3720 string message(1024 / 8, 'a');
3721 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3722 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003723 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003724}
3725
3726/*
Selene Huang31ab4042020-04-29 04:22:39 -07003727 * ImportKeyTest.RsaKeySizeMismatch
3728 *
3729 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3730 * correct way.
3731 */
3732TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3733 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3734 ImportKey(AuthorizationSetBuilder()
3735 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3736 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003737 .Padding(PaddingMode::NONE)
3738 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003739 KeyFormat::PKCS8, rsa_key));
3740}
3741
3742/*
3743 * ImportKeyTest.RsaPublicExponentMismatch
3744 *
3745 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3746 * fails in the correct way.
3747 */
3748TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3749 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3750 ImportKey(AuthorizationSetBuilder()
3751 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3752 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003753 .Padding(PaddingMode::NONE)
3754 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003755 KeyFormat::PKCS8, rsa_key));
3756}
3757
3758/*
David Drysdalee60248c2021-10-04 12:54:13 +01003759 * ImportKeyTest.RsaAttestMultiPurposeFail
3760 *
3761 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
3762 */
3763TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
3764 uint32_t key_size = 2048;
3765 string key = rsa_2048_key;
3766
3767 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3768 ImportKey(AuthorizationSetBuilder()
3769 .Authorization(TAG_NO_AUTH_REQUIRED)
3770 .RsaSigningKey(key_size, 65537)
3771 .AttestKey()
3772 .Digest(Digest::SHA_2_256)
3773 .Padding(PaddingMode::RSA_PSS)
3774 .SetDefaultValidity(),
3775 KeyFormat::PKCS8, key));
3776}
3777
3778/*
Selene Huang31ab4042020-04-29 04:22:39 -07003779 * ImportKeyTest.EcdsaSuccess
3780 *
3781 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3782 */
3783TEST_P(ImportKeyTest, EcdsaSuccess) {
3784 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3785 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003786 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003787 .Digest(Digest::SHA_2_256)
3788 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003789 KeyFormat::PKCS8, ec_256_key));
3790
3791 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003792 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3793 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3794
3795 CheckOrigin();
3796
3797 string message(32, 'a');
3798 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3799 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003800 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003801}
3802
3803/*
3804 * ImportKeyTest.EcdsaP256RFC5915Success
3805 *
3806 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3807 * correctly.
3808 */
3809TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3810 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3811 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003812 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003813 .Digest(Digest::SHA_2_256)
3814 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003815 KeyFormat::PKCS8, ec_256_key_rfc5915));
3816
3817 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003818 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3819 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3820
3821 CheckOrigin();
3822
3823 string message(32, 'a');
3824 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3825 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003826 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003827}
3828
3829/*
3830 * ImportKeyTest.EcdsaP256SEC1Success
3831 *
3832 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3833 */
3834TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3835 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3836 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003837 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003838 .Digest(Digest::SHA_2_256)
3839 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003840 KeyFormat::PKCS8, ec_256_key_sec1));
3841
3842 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003843 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3844 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3845
3846 CheckOrigin();
3847
3848 string message(32, 'a');
3849 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3850 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003851 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003852}
3853
3854/*
3855 * ImportKeyTest.Ecdsa521Success
3856 *
3857 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3858 */
3859TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01003860 if (SecLevel() == SecurityLevel::STRONGBOX) {
3861 GTEST_SKIP() << "Test not applicable to StrongBox device";
3862 }
Selene Huang31ab4042020-04-29 04:22:39 -07003863 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3864 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003865 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003866 .Digest(Digest::SHA_2_256)
3867 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003868 KeyFormat::PKCS8, ec_521_key));
3869
3870 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003871 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3872 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3873 CheckOrigin();
3874
3875 string message(32, 'a');
3876 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3877 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003878 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003879}
3880
3881/*
Selene Huang31ab4042020-04-29 04:22:39 -07003882 * ImportKeyTest.EcdsaCurveMismatch
3883 *
3884 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3885 * the correct way.
3886 */
3887TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3888 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3889 ImportKey(AuthorizationSetBuilder()
3890 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003891 .Digest(Digest::NONE)
3892 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003893 KeyFormat::PKCS8, ec_256_key));
3894}
3895
3896/*
David Drysdalee60248c2021-10-04 12:54:13 +01003897 * ImportKeyTest.EcdsaAttestMultiPurposeFail
3898 *
3899 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
3900 */
3901TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
3902 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3903 ImportKey(AuthorizationSetBuilder()
3904 .Authorization(TAG_NO_AUTH_REQUIRED)
3905 .EcdsaSigningKey(EcCurve::P_256)
3906 .AttestKey()
3907 .Digest(Digest::SHA_2_256)
3908 .SetDefaultValidity(),
3909 KeyFormat::PKCS8, ec_256_key));
3910}
3911
3912/*
David Drysdale42fe1892021-10-14 14:43:46 +01003913 * ImportKeyTest.Ed25519RawSuccess
3914 *
3915 * Verifies that importing and using a raw Ed25519 private key works correctly.
3916 */
3917TEST_P(ImportKeyTest, Ed25519RawSuccess) {
3918 if (!Curve25519Supported()) {
3919 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3920 }
3921
3922 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3923 .Authorization(TAG_NO_AUTH_REQUIRED)
3924 .EcdsaSigningKey(EcCurve::CURVE_25519)
3925 .Digest(Digest::NONE)
3926 .SetDefaultValidity(),
3927 KeyFormat::RAW, ed25519_key));
3928 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3929 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
3930 CheckOrigin();
3931
3932 // The returned cert should hold the correct public key.
3933 ASSERT_GT(cert_chain_.size(), 0);
3934 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
3935 ASSERT_NE(kmKeyCert, nullptr);
3936 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
3937 ASSERT_NE(kmPubKey.get(), nullptr);
3938 size_t kmPubKeySize = 32;
3939 uint8_t kmPubKeyData[32];
3940 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
3941 ASSERT_EQ(kmPubKeySize, 32);
3942 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
3943
3944 string message(32, 'a');
3945 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3946 string signature = SignMessage(message, params);
3947 LocalVerifyMessage(message, signature, params);
3948}
3949
3950/*
3951 * ImportKeyTest.Ed25519Pkcs8Success
3952 *
3953 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
3954 */
3955TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
3956 if (!Curve25519Supported()) {
3957 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3958 }
3959
3960 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3961 .Authorization(TAG_NO_AUTH_REQUIRED)
3962 .EcdsaSigningKey(EcCurve::CURVE_25519)
3963 .Digest(Digest::NONE)
3964 .SetDefaultValidity(),
3965 KeyFormat::PKCS8, ed25519_pkcs8_key));
3966 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3967 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
3968 CheckOrigin();
3969
3970 // The returned cert should hold the correct public key.
3971 ASSERT_GT(cert_chain_.size(), 0);
3972 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
3973 ASSERT_NE(kmKeyCert, nullptr);
3974 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
3975 ASSERT_NE(kmPubKey.get(), nullptr);
3976 size_t kmPubKeySize = 32;
3977 uint8_t kmPubKeyData[32];
3978 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
3979 ASSERT_EQ(kmPubKeySize, 32);
3980 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
3981
3982 string message(32, 'a');
3983 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3984 string signature = SignMessage(message, params);
3985 LocalVerifyMessage(message, signature, params);
3986}
3987
3988/*
3989 * ImportKeyTest.Ed25519CurveMismatch
3990 *
3991 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
3992 * the correct way.
3993 */
3994TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
3995 if (!Curve25519Supported()) {
3996 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3997 }
3998
3999 ASSERT_NE(ErrorCode::OK,
4000 ImportKey(AuthorizationSetBuilder()
4001 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4002 .Digest(Digest::NONE)
4003 .SetDefaultValidity(),
4004 KeyFormat::RAW, ed25519_key));
4005}
4006
4007/*
4008 * ImportKeyTest.Ed25519FormatMismatch
4009 *
4010 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4011 */
4012TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4013 if (!Curve25519Supported()) {
4014 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4015 }
4016
4017 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4018 .EcdsaSigningKey(EcCurve::CURVE_25519)
4019 .Digest(Digest::NONE)
4020 .SetDefaultValidity(),
4021 KeyFormat::PKCS8, ed25519_key));
4022 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4023 .EcdsaSigningKey(EcCurve::CURVE_25519)
4024 .Digest(Digest::NONE)
4025 .SetDefaultValidity(),
4026 KeyFormat::RAW, ed25519_pkcs8_key));
4027}
4028
4029/*
4030 * ImportKeyTest.Ed25519PurposeMismatch
4031 *
4032 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4033 */
4034TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4035 if (!Curve25519Supported()) {
4036 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4037 }
4038
4039 // Can't have both SIGN and ATTEST_KEY
4040 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4041 .EcdsaSigningKey(EcCurve::CURVE_25519)
4042 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4043 .Digest(Digest::NONE)
4044 .SetDefaultValidity(),
4045 KeyFormat::RAW, ed25519_key));
4046 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4047 // PKCS#8 format and so includes an OID).
4048 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4049 .EcdsaKey(EcCurve::CURVE_25519)
4050 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4051 .Digest(Digest::NONE)
4052 .SetDefaultValidity(),
4053 KeyFormat::PKCS8, ed25519_pkcs8_key));
4054}
4055
4056/*
4057 * ImportKeyTest.X25519RawSuccess
4058 *
4059 * Verifies that importing and using a raw X25519 private key works correctly.
4060 */
4061TEST_P(ImportKeyTest, X25519RawSuccess) {
4062 if (!Curve25519Supported()) {
4063 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4064 }
4065
4066 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4067 .Authorization(TAG_NO_AUTH_REQUIRED)
4068 .EcdsaKey(EcCurve::CURVE_25519)
4069 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4070 .SetDefaultValidity(),
4071 KeyFormat::RAW, x25519_key));
4072
4073 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4074 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4075 CheckOrigin();
4076}
4077
4078/*
4079 * ImportKeyTest.X25519Pkcs8Success
4080 *
4081 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4082 */
4083TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4084 if (!Curve25519Supported()) {
4085 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4086 }
4087
4088 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4089 .Authorization(TAG_NO_AUTH_REQUIRED)
4090 .EcdsaKey(EcCurve::CURVE_25519)
4091 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4092 .SetDefaultValidity(),
4093 KeyFormat::PKCS8, x25519_pkcs8_key));
4094
4095 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4096 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4097 CheckOrigin();
4098}
4099
4100/*
4101 * ImportKeyTest.X25519CurveMismatch
4102 *
4103 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4104 * the correct way.
4105 */
4106TEST_P(ImportKeyTest, X25519CurveMismatch) {
4107 if (!Curve25519Supported()) {
4108 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4109 }
4110
4111 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4112 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4113 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4114 .SetDefaultValidity(),
4115 KeyFormat::RAW, x25519_key));
4116}
4117
4118/*
4119 * ImportKeyTest.X25519FormatMismatch
4120 *
4121 * Verifies that importing an X25519 key with an invalid format fails.
4122 */
4123TEST_P(ImportKeyTest, X25519FormatMismatch) {
4124 if (!Curve25519Supported()) {
4125 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4126 }
4127
4128 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4129 .EcdsaKey(EcCurve::CURVE_25519)
4130 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4131 .SetDefaultValidity(),
4132 KeyFormat::PKCS8, x25519_key));
4133 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4134 .EcdsaKey(EcCurve::CURVE_25519)
4135 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4136 .SetDefaultValidity(),
4137 KeyFormat::RAW, x25519_pkcs8_key));
4138}
4139
4140/*
4141 * ImportKeyTest.X25519PurposeMismatch
4142 *
4143 * Verifies that importing an X25519 key pair with an invalid format fails.
4144 */
4145TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4146 if (!Curve25519Supported()) {
4147 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4148 }
4149
4150 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4151 .EcdsaKey(EcCurve::CURVE_25519)
4152 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4153 .SetDefaultValidity(),
4154 KeyFormat::PKCS8, x25519_pkcs8_key));
4155 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4156 .EcdsaSigningKey(EcCurve::CURVE_25519)
4157 .SetDefaultValidity(),
4158 KeyFormat::PKCS8, x25519_pkcs8_key));
4159}
4160
4161/*
Selene Huang31ab4042020-04-29 04:22:39 -07004162 * ImportKeyTest.AesSuccess
4163 *
4164 * Verifies that importing and using an AES key works.
4165 */
4166TEST_P(ImportKeyTest, AesSuccess) {
4167 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4168 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4169 .Authorization(TAG_NO_AUTH_REQUIRED)
4170 .AesEncryptionKey(key.size() * 8)
4171 .EcbMode()
4172 .Padding(PaddingMode::PKCS7),
4173 KeyFormat::RAW, key));
4174
4175 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4176 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4177 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4178 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4179 CheckOrigin();
4180
4181 string message = "Hello World!";
4182 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4183 string ciphertext = EncryptMessage(message, params);
4184 string plaintext = DecryptMessage(ciphertext, params);
4185 EXPECT_EQ(message, plaintext);
4186}
4187
4188/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004189 * ImportKeyTest.AesFailure
4190 *
4191 * Verifies that importing an invalid AES key fails.
4192 */
4193TEST_P(ImportKeyTest, AesFailure) {
4194 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4195 uint32_t bitlen = key.size() * 8;
4196 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004197 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004198 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004199 .Authorization(TAG_NO_AUTH_REQUIRED)
4200 .AesEncryptionKey(key_size)
4201 .EcbMode()
4202 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004203 KeyFormat::RAW, key);
4204 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004205 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4206 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004207 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004208
4209 // Explicit key size matches that of the provided key, but it's not a valid size.
4210 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4211 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4212 ImportKey(AuthorizationSetBuilder()
4213 .Authorization(TAG_NO_AUTH_REQUIRED)
4214 .AesEncryptionKey(long_key.size() * 8)
4215 .EcbMode()
4216 .Padding(PaddingMode::PKCS7),
4217 KeyFormat::RAW, long_key));
4218 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4219 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4220 ImportKey(AuthorizationSetBuilder()
4221 .Authorization(TAG_NO_AUTH_REQUIRED)
4222 .AesEncryptionKey(short_key.size() * 8)
4223 .EcbMode()
4224 .Padding(PaddingMode::PKCS7),
4225 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004226}
4227
4228/*
4229 * ImportKeyTest.TripleDesSuccess
4230 *
4231 * Verifies that importing and using a 3DES key works.
4232 */
4233TEST_P(ImportKeyTest, TripleDesSuccess) {
4234 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4235 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4236 .Authorization(TAG_NO_AUTH_REQUIRED)
4237 .TripleDesEncryptionKey(168)
4238 .EcbMode()
4239 .Padding(PaddingMode::PKCS7),
4240 KeyFormat::RAW, key));
4241
4242 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4243 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4244 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4245 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4246 CheckOrigin();
4247
4248 string message = "Hello World!";
4249 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4250 string ciphertext = EncryptMessage(message, params);
4251 string plaintext = DecryptMessage(ciphertext, params);
4252 EXPECT_EQ(message, plaintext);
4253}
4254
4255/*
4256 * ImportKeyTest.TripleDesFailure
4257 *
4258 * Verifies that importing an invalid 3DES key fails.
4259 */
4260TEST_P(ImportKeyTest, TripleDesFailure) {
4261 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004262 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004263 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004264 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004265 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004266 .Authorization(TAG_NO_AUTH_REQUIRED)
4267 .TripleDesEncryptionKey(key_size)
4268 .EcbMode()
4269 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004270 KeyFormat::RAW, key);
4271 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004272 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4273 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004274 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004275 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004276 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004277 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4278 ImportKey(AuthorizationSetBuilder()
4279 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004280 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004281 .EcbMode()
4282 .Padding(PaddingMode::PKCS7),
4283 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004284 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004285 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4286 ImportKey(AuthorizationSetBuilder()
4287 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004288 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004289 .EcbMode()
4290 .Padding(PaddingMode::PKCS7),
4291 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004292}
4293
4294/*
4295 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004296 *
4297 * Verifies that importing and using an HMAC key works.
4298 */
4299TEST_P(ImportKeyTest, HmacKeySuccess) {
4300 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4301 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4302 .Authorization(TAG_NO_AUTH_REQUIRED)
4303 .HmacKey(key.size() * 8)
4304 .Digest(Digest::SHA_2_256)
4305 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4306 KeyFormat::RAW, key));
4307
4308 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4309 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4310 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4311 CheckOrigin();
4312
4313 string message = "Hello World!";
4314 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4315 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4316}
4317
4318INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4319
4320auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004321 // IKeyMintDevice.aidl
4322 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4323 "020100" // INTEGER length 1 value 0x00 (version)
4324 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4325 "934bf94e2aa28a3f83c9f79297250262"
4326 "fbe3276b5a1c91159bbfa3ef8957aac8"
4327 "4b59b30b455a79c2973480823d8b3863"
4328 "c3deef4a8e243590268d80e18751a0e1"
4329 "30f67ce6a1ace9f79b95e097474febc9"
4330 "81195b1d13a69086c0863f66a7b7fdb4"
4331 "8792227b1ac5e2489febdf087ab54864"
4332 "83033a6f001ca5d1ec1e27f5c30f4cec"
4333 "2642074a39ae68aee552e196627a8e3d"
4334 "867e67a8c01b11e75f13cca0a97ab668"
4335 "b50cda07a8ecb7cd8e3dd7009c963653"
4336 "4f6f239cffe1fc8daa466f78b676c711"
4337 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4338 "99b801597d5220e307eaa5bee507fb94"
4339 "d1fa69f9e519b2de315bac92c36f2ea1"
4340 "fa1df4478c0ddedeae8c70e0233cd098"
4341 "040c" // OCTET STRING length 0x0c (initializationVector)
4342 "d796b02c370f1fa4cc0124f1"
4343 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4344 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4345 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4346 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4347 "3106" // SET length 0x06
4348 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4349 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4350 // } end SET
4351 // } end [1]
4352 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4353 "020120" // INTEGER length 1 value 0x20 (AES)
4354 // } end [2]
4355 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4356 "02020100" // INTEGER length 2 value 0x100
4357 // } end [3]
4358 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4359 "3103" // SET length 0x03 {
4360 "020101" // INTEGER length 1 value 0x01 (ECB)
4361 // } end SET
4362 // } end [4]
4363 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4364 "3103" // SET length 0x03 {
4365 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4366 // } end SET
4367 // } end [5]
4368 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4369 // (noAuthRequired)
4370 "0500" // NULL
4371 // } end [503]
4372 // } end SEQUENCE (AuthorizationList)
4373 // } end SEQUENCE (KeyDescription)
4374 "0420" // OCTET STRING length 0x20 (encryptedKey)
4375 "ccd540855f833a5e1480bfd2d36faf3a"
4376 "eee15df5beabe2691bc82dde2a7aa910"
4377 "0410" // OCTET STRING length 0x10 (tag)
4378 "64c9f689c60ff6223ab6e6999e0eb6e5"
4379 // } SEQUENCE (SecureKeyWrapper)
4380);
Selene Huang31ab4042020-04-29 04:22:39 -07004381
4382auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004383 // IKeyMintDevice.aidl
4384 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4385 "020100" // INTEGER length 1 value 0x00 (version)
4386 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4387 "aad93ed5924f283b4bb5526fbe7a1412"
4388 "f9d9749ec30db9062b29e574a8546f33"
4389 "c88732452f5b8e6a391ee76c39ed1712"
4390 "c61d8df6213dec1cffbc17a8c6d04c7b"
4391 "30893d8daa9b2015213e219468215532"
4392 "07f8f9931c4caba23ed3bee28b36947e"
4393 "47f10e0a5c3dc51c988a628daad3e5e1"
4394 "f4005e79c2d5a96c284b4b8d7e4948f3"
4395 "31e5b85dd5a236f85579f3ea1d1b8484"
4396 "87470bdb0ab4f81a12bee42c99fe0df4"
4397 "bee3759453e69ad1d68a809ce06b949f"
4398 "7694a990429b2fe81e066ff43e56a216"
4399 "02db70757922a4bcc23ab89f1e35da77"
4400 "586775f423e519c2ea394caf48a28d0c"
4401 "8020f1dcf6b3a68ec246f615ae96dae9"
4402 "a079b1f6eb959033c1af5c125fd94168"
4403 "040c" // OCTET STRING length 0x0c (initializationVector)
4404 "6d9721d08589581ab49204a3"
4405 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4406 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4407 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4408 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4409 "3106" // SET length 0x06
4410 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4411 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4412 // } end SET
4413 // } end [1]
4414 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4415 "020120" // INTEGER length 1 value 0x20 (AES)
4416 // } end [2]
4417 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4418 "02020100" // INTEGER length 2 value 0x100
4419 // } end [3]
4420 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4421 "3103" // SET length 0x03 {
4422 "020101" // INTEGER length 1 value 0x01 (ECB)
4423 // } end SET
4424 // } end [4]
4425 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4426 "3103" // SET length 0x03 {
4427 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4428 // } end SET
4429 // } end [5]
4430 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4431 // (noAuthRequired)
4432 "0500" // NULL
4433 // } end [503]
4434 // } end SEQUENCE (AuthorizationList)
4435 // } end SEQUENCE (KeyDescription)
4436 "0420" // OCTET STRING length 0x20 (encryptedKey)
4437 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4438 "c20d1f99a9a024a76f35c8e2cab9b68d"
4439 "0410" // OCTET STRING length 0x10 (tag)
4440 "2560c70109ae67c030f00b98b512a670"
4441 // } SEQUENCE (SecureKeyWrapper)
4442);
Selene Huang31ab4042020-04-29 04:22:39 -07004443
4444auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004445 // RFC 5208 s5
4446 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4447 "020100" // INTEGER length 1 value 0x00 (version)
4448 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4449 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4450 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4451 "0500" // NULL (parameters)
4452 // } SEQUENCE (AlgorithmIdentifier)
4453 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4454 // RFC 8017 A.1.2
4455 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4456 "020100" // INTEGER length 1 value 0x00 (version)
4457 "02820101" // INTEGER length 0x0101 (modulus) value...
4458 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4459 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4460 "7b06e673a837313d56b1c725150a3fef" // 0x30
4461 "86acbddc41bb759c2854eae32d35841e" // 0x40
4462 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4463 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4464 "312d7bd5921ffaea1347c157406fef71" // 0x70
4465 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4466 "f4645c11f5c1374c3886427411c44979" // 0x90
4467 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4468 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4469 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4470 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4471 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4472 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4473 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4474 "55" // 0x101
4475 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4476 "02820100" // INTEGER length 0x100 (privateExponent) value...
4477 "431447b6251908112b1ee76f99f3711a" // 0x10
4478 "52b6630960046c2de70de188d833f8b8" // 0x20
4479 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4480 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4481 "e710b630a03adc683b5d2c43080e52be" // 0x50
4482 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4483 "822bccff087d63c940ba8a45f670feb2" // 0x70
4484 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4485 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4486 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4487 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4488 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4489 "52659d5a5ba05b663737a8696281865b" // 0xd0
4490 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4491 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4492 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4493 "028181" // INTEGER length 0x81 (prime1) value...
4494 "00de392e18d682c829266cc3454e1d61" // 0x10
4495 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4496 "ff841be5bac82a164c5970007047b8c5" // 0x30
4497 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4498 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4499 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4500 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4501 "9e91346130748a6e3c124f9149d71c74" // 0x80
4502 "35"
4503 "028181" // INTEGER length 0x81 (prime2) value...
4504 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4505 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4506 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4507 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4508 "9ed39a2d934c880440aed8832f984316" // 0x50
4509 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4510 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4511 "b880677c068e1be936e81288815252a8" // 0x80
4512 "a1"
4513 "028180" // INTEGER length 0x80 (exponent1) value...
4514 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4515 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4516 "5a063212a4f105a3764743e53281988a" // 0x30
4517 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4518 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4519 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4520 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4521 "4719d6e2b9439823719cd08bcd031781" // 0x80
4522 "028181" // INTEGER length 0x81 (exponent2) value...
4523 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4524 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4525 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4526 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4527 "1254186af30b22c10582a8a43e34fe94" // 0x50
4528 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4529 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4530 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4531 "61"
4532 "028181" // INTEGER length 0x81 (coefficient) value...
4533 "00c931617c77829dfb1270502be9195c" // 0x10
4534 "8f2830885f57dba869536811e6864236" // 0x20
4535 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4536 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4537 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4538 "959356210723287b0affcc9f727044d4" // 0x60
4539 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4540 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4541 "22"
4542 // } SEQUENCE
4543 // } SEQUENCE ()
4544);
Selene Huang31ab4042020-04-29 04:22:39 -07004545
4546string zero_masking_key =
4547 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4548string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4549
4550class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4551
4552TEST_P(ImportWrappedKeyTest, Success) {
4553 auto wrapping_key_desc = AuthorizationSetBuilder()
4554 .RsaEncryptionKey(2048, 65537)
4555 .Digest(Digest::SHA_2_256)
4556 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004557 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4558 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004559
4560 ASSERT_EQ(ErrorCode::OK,
4561 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4562 AuthorizationSetBuilder()
4563 .Digest(Digest::SHA_2_256)
4564 .Padding(PaddingMode::RSA_OAEP)));
4565
4566 string message = "Hello World!";
4567 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4568 string ciphertext = EncryptMessage(message, params);
4569 string plaintext = DecryptMessage(ciphertext, params);
4570 EXPECT_EQ(message, plaintext);
4571}
4572
David Drysdaled2cc8c22021-04-15 13:29:45 +01004573/*
4574 * ImportWrappedKeyTest.SuccessSidsIgnored
4575 *
4576 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
4577 * include Tag:USER_SECURE_ID.
4578 */
4579TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
4580 auto wrapping_key_desc = AuthorizationSetBuilder()
4581 .RsaEncryptionKey(2048, 65537)
4582 .Digest(Digest::SHA_2_256)
4583 .Padding(PaddingMode::RSA_OAEP)
4584 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4585 .SetDefaultValidity();
4586
4587 int64_t password_sid = 42;
4588 int64_t biometric_sid = 24;
4589 ASSERT_EQ(ErrorCode::OK,
4590 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4591 AuthorizationSetBuilder()
4592 .Digest(Digest::SHA_2_256)
4593 .Padding(PaddingMode::RSA_OAEP),
4594 password_sid, biometric_sid));
4595
4596 string message = "Hello World!";
4597 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4598 string ciphertext = EncryptMessage(message, params);
4599 string plaintext = DecryptMessage(ciphertext, params);
4600 EXPECT_EQ(message, plaintext);
4601}
4602
Selene Huang31ab4042020-04-29 04:22:39 -07004603TEST_P(ImportWrappedKeyTest, SuccessMasked) {
4604 auto wrapping_key_desc = AuthorizationSetBuilder()
4605 .RsaEncryptionKey(2048, 65537)
4606 .Digest(Digest::SHA_2_256)
4607 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004608 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4609 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004610
4611 ASSERT_EQ(ErrorCode::OK,
4612 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
4613 AuthorizationSetBuilder()
4614 .Digest(Digest::SHA_2_256)
4615 .Padding(PaddingMode::RSA_OAEP)));
4616}
4617
4618TEST_P(ImportWrappedKeyTest, WrongMask) {
4619 auto wrapping_key_desc = AuthorizationSetBuilder()
4620 .RsaEncryptionKey(2048, 65537)
4621 .Digest(Digest::SHA_2_256)
4622 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004623 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4624 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004625
4626 ASSERT_EQ(
4627 ErrorCode::VERIFICATION_FAILED,
4628 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4629 AuthorizationSetBuilder()
4630 .Digest(Digest::SHA_2_256)
4631 .Padding(PaddingMode::RSA_OAEP)));
4632}
4633
4634TEST_P(ImportWrappedKeyTest, WrongPurpose) {
4635 auto wrapping_key_desc = AuthorizationSetBuilder()
4636 .RsaEncryptionKey(2048, 65537)
4637 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004638 .Padding(PaddingMode::RSA_OAEP)
4639 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004640
4641 ASSERT_EQ(
4642 ErrorCode::INCOMPATIBLE_PURPOSE,
4643 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4644 AuthorizationSetBuilder()
4645 .Digest(Digest::SHA_2_256)
4646 .Padding(PaddingMode::RSA_OAEP)));
4647}
4648
David Drysdaled2cc8c22021-04-15 13:29:45 +01004649TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
4650 auto wrapping_key_desc = AuthorizationSetBuilder()
4651 .RsaEncryptionKey(2048, 65537)
4652 .Digest(Digest::SHA_2_256)
4653 .Padding(PaddingMode::RSA_PSS)
4654 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4655 .SetDefaultValidity();
4656
4657 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
4658 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4659 AuthorizationSetBuilder()
4660 .Digest(Digest::SHA_2_256)
4661 .Padding(PaddingMode::RSA_OAEP)));
4662}
4663
4664TEST_P(ImportWrappedKeyTest, WrongDigest) {
4665 auto wrapping_key_desc = AuthorizationSetBuilder()
4666 .RsaEncryptionKey(2048, 65537)
4667 .Digest(Digest::SHA_2_512)
4668 .Padding(PaddingMode::RSA_OAEP)
4669 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4670 .SetDefaultValidity();
4671
4672 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
4673 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4674 AuthorizationSetBuilder()
4675 .Digest(Digest::SHA_2_256)
4676 .Padding(PaddingMode::RSA_OAEP)));
4677}
4678
Selene Huang31ab4042020-04-29 04:22:39 -07004679INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
4680
4681typedef KeyMintAidlTestBase EncryptionOperationsTest;
4682
4683/*
4684 * EncryptionOperationsTest.RsaNoPaddingSuccess
4685 *
David Drysdale59cae642021-05-12 13:52:03 +01004686 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07004687 */
4688TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00004689 for (uint64_t exponent : ValidExponents()) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01004690 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4691 .Authorization(TAG_NO_AUTH_REQUIRED)
4692 .RsaEncryptionKey(2048, exponent)
4693 .Padding(PaddingMode::NONE)
4694 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004695
David Drysdaled2cc8c22021-04-15 13:29:45 +01004696 string message = string(2048 / 8, 'a');
4697 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004698 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004699 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004700
David Drysdale59cae642021-05-12 13:52:03 +01004701 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004702 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004703
David Drysdaled2cc8c22021-04-15 13:29:45 +01004704 // Unpadded RSA is deterministic
4705 EXPECT_EQ(ciphertext1, ciphertext2);
4706
4707 CheckedDeleteKey();
4708 }
Selene Huang31ab4042020-04-29 04:22:39 -07004709}
4710
4711/*
4712 * EncryptionOperationsTest.RsaNoPaddingShortMessage
4713 *
David Drysdale59cae642021-05-12 13:52:03 +01004714 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07004715 */
4716TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
4717 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4718 .Authorization(TAG_NO_AUTH_REQUIRED)
4719 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004720 .Padding(PaddingMode::NONE)
4721 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004722
4723 string message = "1";
4724 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4725
David Drysdale59cae642021-05-12 13:52:03 +01004726 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004727 EXPECT_EQ(2048U / 8, ciphertext.size());
4728
4729 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
4730 string plaintext = DecryptMessage(ciphertext, params);
4731
4732 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07004733}
4734
4735/*
Selene Huang31ab4042020-04-29 04:22:39 -07004736 * EncryptionOperationsTest.RsaOaepSuccess
4737 *
David Drysdale59cae642021-05-12 13:52:03 +01004738 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07004739 */
4740TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
4741 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4742
4743 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01004744 ASSERT_EQ(ErrorCode::OK,
4745 GenerateKey(AuthorizationSetBuilder()
4746 .Authorization(TAG_NO_AUTH_REQUIRED)
4747 .RsaEncryptionKey(key_size, 65537)
4748 .Padding(PaddingMode::RSA_OAEP)
4749 .Digest(digests)
4750 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
4751 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004752
4753 string message = "Hello";
4754
4755 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01004756 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4757
4758 auto params = AuthorizationSetBuilder()
4759 .Digest(digest)
4760 .Padding(PaddingMode::RSA_OAEP)
4761 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
4762 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004763 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4764 EXPECT_EQ(key_size / 8, ciphertext1.size());
4765
David Drysdale59cae642021-05-12 13:52:03 +01004766 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004767 EXPECT_EQ(key_size / 8, ciphertext2.size());
4768
4769 // OAEP randomizes padding so every result should be different (with astronomically high
4770 // probability).
4771 EXPECT_NE(ciphertext1, ciphertext2);
4772
4773 string plaintext1 = DecryptMessage(ciphertext1, params);
4774 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4775 string plaintext2 = DecryptMessage(ciphertext2, params);
4776 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4777
4778 // Decrypting corrupted ciphertext should fail.
4779 size_t offset_to_corrupt = random() % ciphertext1.size();
4780 char corrupt_byte;
4781 do {
4782 corrupt_byte = static_cast<char>(random() % 256);
4783 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4784 ciphertext1[offset_to_corrupt] = corrupt_byte;
4785
4786 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4787 string result;
4788 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4789 EXPECT_EQ(0U, result.size());
4790 }
4791}
4792
4793/*
4794 * EncryptionOperationsTest.RsaOaepInvalidDigest
4795 *
David Drysdale59cae642021-05-12 13:52:03 +01004796 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07004797 * without a digest.
4798 */
4799TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
4800 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4801 .Authorization(TAG_NO_AUTH_REQUIRED)
4802 .RsaEncryptionKey(2048, 65537)
4803 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004804 .Digest(Digest::NONE)
4805 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004806
4807 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004808 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07004809}
4810
4811/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004812 * EncryptionOperationsTest.RsaOaepInvalidPadding
4813 *
David Drysdale59cae642021-05-12 13:52:03 +01004814 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01004815 * with a padding value that is only suitable for signing/verifying.
4816 */
4817TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
4818 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4819 .Authorization(TAG_NO_AUTH_REQUIRED)
4820 .RsaEncryptionKey(2048, 65537)
4821 .Padding(PaddingMode::RSA_PSS)
4822 .Digest(Digest::NONE)
4823 .SetDefaultValidity()));
4824
4825 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004826 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01004827}
4828
4829/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004830 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07004831 *
David Drysdale59cae642021-05-12 13:52:03 +01004832 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07004833 * with a different digest than was used to encrypt.
4834 */
4835TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01004836 if (SecLevel() == SecurityLevel::STRONGBOX) {
4837 GTEST_SKIP() << "Test not applicable to StrongBox device";
4838 }
Selene Huang31ab4042020-04-29 04:22:39 -07004839
4840 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4841 .Authorization(TAG_NO_AUTH_REQUIRED)
4842 .RsaEncryptionKey(1024, 65537)
4843 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004844 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
4845 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004846 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01004847 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07004848 message,
4849 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
4850
4851 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4852 .Digest(Digest::SHA_2_256)
4853 .Padding(PaddingMode::RSA_OAEP)));
4854 string result;
4855 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
4856 EXPECT_EQ(0U, result.size());
4857}
4858
4859/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004860 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
4861 *
David Drysdale59cae642021-05-12 13:52:03 +01004862 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004863 * digests.
4864 */
4865TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
4866 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4867
4868 size_t key_size = 2048; // Need largish key for SHA-512 test.
4869 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4870 .OaepMGFDigest(digests)
4871 .Authorization(TAG_NO_AUTH_REQUIRED)
4872 .RsaEncryptionKey(key_size, 65537)
4873 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004874 .Digest(Digest::SHA_2_256)
4875 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004876
4877 string message = "Hello";
4878
4879 for (auto digest : digests) {
4880 auto params = AuthorizationSetBuilder()
4881 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4882 .Digest(Digest::SHA_2_256)
4883 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01004884 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004885 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4886 EXPECT_EQ(key_size / 8, ciphertext1.size());
4887
David Drysdale59cae642021-05-12 13:52:03 +01004888 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004889 EXPECT_EQ(key_size / 8, ciphertext2.size());
4890
4891 // OAEP randomizes padding so every result should be different (with astronomically high
4892 // probability).
4893 EXPECT_NE(ciphertext1, ciphertext2);
4894
4895 string plaintext1 = DecryptMessage(ciphertext1, params);
4896 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4897 string plaintext2 = DecryptMessage(ciphertext2, params);
4898 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4899
4900 // Decrypting corrupted ciphertext should fail.
4901 size_t offset_to_corrupt = random() % ciphertext1.size();
4902 char corrupt_byte;
4903 do {
4904 corrupt_byte = static_cast<char>(random() % 256);
4905 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4906 ciphertext1[offset_to_corrupt] = corrupt_byte;
4907
4908 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4909 string result;
4910 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4911 EXPECT_EQ(0U, result.size());
4912 }
4913}
4914
4915/*
4916 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
4917 *
David Drysdale59cae642021-05-12 13:52:03 +01004918 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004919 * with incompatible MGF digest.
4920 */
4921TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4922 ASSERT_EQ(ErrorCode::OK,
4923 GenerateKey(AuthorizationSetBuilder()
4924 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4925 .Authorization(TAG_NO_AUTH_REQUIRED)
4926 .RsaEncryptionKey(2048, 65537)
4927 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004928 .Digest(Digest::SHA_2_256)
4929 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004930 string message = "Hello World!";
4931
4932 auto params = AuthorizationSetBuilder()
4933 .Padding(PaddingMode::RSA_OAEP)
4934 .Digest(Digest::SHA_2_256)
4935 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004936 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004937}
4938
4939/*
4940 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4941 *
4942 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4943 * with unsupported MGF digest.
4944 */
4945TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4946 ASSERT_EQ(ErrorCode::OK,
4947 GenerateKey(AuthorizationSetBuilder()
4948 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4949 .Authorization(TAG_NO_AUTH_REQUIRED)
4950 .RsaEncryptionKey(2048, 65537)
4951 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004952 .Digest(Digest::SHA_2_256)
4953 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004954 string message = "Hello World!";
4955
4956 auto params = AuthorizationSetBuilder()
4957 .Padding(PaddingMode::RSA_OAEP)
4958 .Digest(Digest::SHA_2_256)
4959 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004960 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004961}
4962
4963/*
Selene Huang31ab4042020-04-29 04:22:39 -07004964 * EncryptionOperationsTest.RsaPkcs1Success
4965 *
4966 * Verifies that RSA PKCS encryption/decrypts works.
4967 */
4968TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4969 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4970 .Authorization(TAG_NO_AUTH_REQUIRED)
4971 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004972 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4973 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004974
4975 string message = "Hello World!";
4976 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01004977 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004978 EXPECT_EQ(2048U / 8, ciphertext1.size());
4979
David Drysdale59cae642021-05-12 13:52:03 +01004980 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004981 EXPECT_EQ(2048U / 8, ciphertext2.size());
4982
4983 // PKCS1 v1.5 randomizes padding so every result should be different.
4984 EXPECT_NE(ciphertext1, ciphertext2);
4985
4986 string plaintext = DecryptMessage(ciphertext1, params);
4987 EXPECT_EQ(message, plaintext);
4988
4989 // Decrypting corrupted ciphertext should fail.
4990 size_t offset_to_corrupt = random() % ciphertext1.size();
4991 char corrupt_byte;
4992 do {
4993 corrupt_byte = static_cast<char>(random() % 256);
4994 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4995 ciphertext1[offset_to_corrupt] = corrupt_byte;
4996
4997 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4998 string result;
4999 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5000 EXPECT_EQ(0U, result.size());
5001}
5002
5003/*
Selene Huang31ab4042020-04-29 04:22:39 -07005004 * EncryptionOperationsTest.EcdsaEncrypt
5005 *
5006 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5007 */
5008TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5009 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5010 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005011 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005012 .Digest(Digest::NONE)
5013 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005014 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5015 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5016 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5017}
5018
5019/*
5020 * EncryptionOperationsTest.HmacEncrypt
5021 *
5022 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5023 */
5024TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5025 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5026 .Authorization(TAG_NO_AUTH_REQUIRED)
5027 .HmacKey(128)
5028 .Digest(Digest::SHA_2_256)
5029 .Padding(PaddingMode::NONE)
5030 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5031 auto params = AuthorizationSetBuilder()
5032 .Digest(Digest::SHA_2_256)
5033 .Padding(PaddingMode::NONE)
5034 .Authorization(TAG_MAC_LENGTH, 128);
5035 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5036 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5037}
5038
5039/*
5040 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5041 *
5042 * Verifies that AES ECB mode works.
5043 */
5044TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5045 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5046 .Authorization(TAG_NO_AUTH_REQUIRED)
5047 .AesEncryptionKey(128)
5048 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5049 .Padding(PaddingMode::NONE)));
5050
5051 ASSERT_GT(key_blob_.size(), 0U);
5052 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5053
5054 // Two-block message.
5055 string message = "12345678901234567890123456789012";
5056 string ciphertext1 = EncryptMessage(message, params);
5057 EXPECT_EQ(message.size(), ciphertext1.size());
5058
5059 string ciphertext2 = EncryptMessage(string(message), params);
5060 EXPECT_EQ(message.size(), ciphertext2.size());
5061
5062 // ECB is deterministic.
5063 EXPECT_EQ(ciphertext1, ciphertext2);
5064
5065 string plaintext = DecryptMessage(ciphertext1, params);
5066 EXPECT_EQ(message, plaintext);
5067}
5068
5069/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005070 * EncryptionOperationsTest.AesEcbUnknownTag
5071 *
5072 * Verifies that AES ECB operations ignore unknown tags.
5073 */
5074TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5075 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5076 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5077 KeyParameter unknown_param;
5078 unknown_param.tag = unknown_tag;
5079
5080 vector<KeyCharacteristics> key_characteristics;
5081 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5082 .Authorization(TAG_NO_AUTH_REQUIRED)
5083 .AesEncryptionKey(128)
5084 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5085 .Padding(PaddingMode::NONE)
5086 .Authorization(unknown_param),
5087 &key_blob_, &key_characteristics));
5088 ASSERT_GT(key_blob_.size(), 0U);
5089
5090 // Unknown tags should not be returned in key characteristics.
5091 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5092 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5093 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5094 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5095
5096 // Encrypt without mentioning the unknown parameter.
5097 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5098 string message = "12345678901234567890123456789012";
5099 string ciphertext = EncryptMessage(message, params);
5100 EXPECT_EQ(message.size(), ciphertext.size());
5101
5102 // Decrypt including the unknown parameter.
5103 auto decrypt_params = AuthorizationSetBuilder()
5104 .BlockMode(BlockMode::ECB)
5105 .Padding(PaddingMode::NONE)
5106 .Authorization(unknown_param);
5107 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5108 EXPECT_EQ(message, plaintext);
5109}
5110
5111/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005112 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005113 *
5114 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5115 */
5116TEST_P(EncryptionOperationsTest, AesWrongMode) {
5117 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5118 .Authorization(TAG_NO_AUTH_REQUIRED)
5119 .AesEncryptionKey(128)
5120 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5121 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005122 ASSERT_GT(key_blob_.size(), 0U);
5123
Selene Huang31ab4042020-04-29 04:22:39 -07005124 EXPECT_EQ(
5125 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5126 Begin(KeyPurpose::ENCRYPT,
5127 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5128}
5129
5130/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005131 * EncryptionOperationsTest.AesWrongPadding
5132 *
5133 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5134 */
5135TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5136 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5137 .Authorization(TAG_NO_AUTH_REQUIRED)
5138 .AesEncryptionKey(128)
5139 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5140 .Padding(PaddingMode::NONE)));
5141 ASSERT_GT(key_blob_.size(), 0U);
5142
5143 EXPECT_EQ(
5144 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5145 Begin(KeyPurpose::ENCRYPT,
5146 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5147}
5148
5149/*
5150 * EncryptionOperationsTest.AesInvalidParams
5151 *
5152 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5153 */
5154TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5155 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5156 .Authorization(TAG_NO_AUTH_REQUIRED)
5157 .AesEncryptionKey(128)
5158 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5159 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5160 .Padding(PaddingMode::NONE)
5161 .Padding(PaddingMode::PKCS7)));
5162 ASSERT_GT(key_blob_.size(), 0U);
5163
5164 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5165 .BlockMode(BlockMode::CBC)
5166 .BlockMode(BlockMode::ECB)
5167 .Padding(PaddingMode::NONE));
5168 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5169 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5170
5171 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5172 .BlockMode(BlockMode::ECB)
5173 .Padding(PaddingMode::NONE)
5174 .Padding(PaddingMode::PKCS7));
5175 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5176 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5177}
5178
5179/*
Selene Huang31ab4042020-04-29 04:22:39 -07005180 * EncryptionOperationsTest.AesWrongPurpose
5181 *
5182 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5183 * specified.
5184 */
5185TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5186 auto err = GenerateKey(AuthorizationSetBuilder()
5187 .Authorization(TAG_NO_AUTH_REQUIRED)
5188 .AesKey(128)
5189 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5190 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5191 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5192 .Padding(PaddingMode::NONE));
5193 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5194 ASSERT_GT(key_blob_.size(), 0U);
5195
5196 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5197 .BlockMode(BlockMode::GCM)
5198 .Padding(PaddingMode::NONE)
5199 .Authorization(TAG_MAC_LENGTH, 128));
5200 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5201
5202 CheckedDeleteKey();
5203
5204 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5205 .Authorization(TAG_NO_AUTH_REQUIRED)
5206 .AesKey(128)
5207 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5208 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5209 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5210 .Padding(PaddingMode::NONE)));
5211
5212 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5213 .BlockMode(BlockMode::GCM)
5214 .Padding(PaddingMode::NONE)
5215 .Authorization(TAG_MAC_LENGTH, 128));
5216 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5217}
5218
5219/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005220 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005221 *
5222 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5223 * multiple of the block size and no padding is specified.
5224 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005225TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5226 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5227 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5228 .Authorization(TAG_NO_AUTH_REQUIRED)
5229 .AesEncryptionKey(128)
5230 .Authorization(TAG_BLOCK_MODE, blockMode)
5231 .Padding(PaddingMode::NONE)));
5232 // Message is slightly shorter than two blocks.
5233 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005234
David Drysdaled2cc8c22021-04-15 13:29:45 +01005235 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5236 AuthorizationSet out_params;
5237 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5238 string ciphertext;
5239 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5240 EXPECT_EQ(0U, ciphertext.size());
5241
5242 CheckedDeleteKey();
5243 }
Selene Huang31ab4042020-04-29 04:22:39 -07005244}
5245
5246/*
5247 * EncryptionOperationsTest.AesEcbPkcs7Padding
5248 *
5249 * Verifies that AES PKCS7 padding works for any message length.
5250 */
5251TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5252 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5253 .Authorization(TAG_NO_AUTH_REQUIRED)
5254 .AesEncryptionKey(128)
5255 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5256 .Padding(PaddingMode::PKCS7)));
5257
5258 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5259
5260 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005261 for (size_t i = 0; i <= 48; i++) {
5262 SCOPED_TRACE(testing::Message() << "i = " << i);
5263 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5264 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005265 string ciphertext = EncryptMessage(message, params);
5266 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5267 string plaintext = DecryptMessage(ciphertext, params);
5268 EXPECT_EQ(message, plaintext);
5269 }
5270}
5271
5272/*
5273 * EncryptionOperationsTest.AesEcbWrongPadding
5274 *
5275 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5276 * specified.
5277 */
5278TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5279 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5280 .Authorization(TAG_NO_AUTH_REQUIRED)
5281 .AesEncryptionKey(128)
5282 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5283 .Padding(PaddingMode::NONE)));
5284
5285 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5286
5287 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005288 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005289 string message(i, 'a');
5290 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5291 }
5292}
5293
5294/*
5295 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5296 *
5297 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5298 */
5299TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5300 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5301 .Authorization(TAG_NO_AUTH_REQUIRED)
5302 .AesEncryptionKey(128)
5303 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5304 .Padding(PaddingMode::PKCS7)));
5305
5306 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5307
5308 string message = "a";
5309 string ciphertext = EncryptMessage(message, params);
5310 EXPECT_EQ(16U, ciphertext.size());
5311 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005312
Seth Moore7a55ae32021-06-23 14:28:11 -07005313 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5314 ++ciphertext[ciphertext.size() / 2];
5315
5316 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5317 string plaintext;
5318 ErrorCode error = Finish(message, &plaintext);
5319 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
5320 // This is the expected error, we can exit the test now.
5321 return;
5322 } else {
5323 // Very small chance we got valid decryption, so try again.
5324 ASSERT_EQ(error, ErrorCode::OK);
5325 }
5326 }
5327 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005328}
5329
5330vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5331 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005332 EXPECT_TRUE(iv);
5333 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005334}
5335
5336/*
5337 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5338 *
5339 * Verifies that AES CTR mode works.
5340 */
5341TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5342 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5343 .Authorization(TAG_NO_AUTH_REQUIRED)
5344 .AesEncryptionKey(128)
5345 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5346 .Padding(PaddingMode::NONE)));
5347
5348 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5349
5350 string message = "123";
5351 AuthorizationSet out_params;
5352 string ciphertext1 = EncryptMessage(message, params, &out_params);
5353 vector<uint8_t> iv1 = CopyIv(out_params);
5354 EXPECT_EQ(16U, iv1.size());
5355
5356 EXPECT_EQ(message.size(), ciphertext1.size());
5357
5358 out_params.Clear();
5359 string ciphertext2 = EncryptMessage(message, params, &out_params);
5360 vector<uint8_t> iv2 = CopyIv(out_params);
5361 EXPECT_EQ(16U, iv2.size());
5362
5363 // IVs should be random, so ciphertexts should differ.
5364 EXPECT_NE(ciphertext1, ciphertext2);
5365
5366 auto params_iv1 =
5367 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5368 auto params_iv2 =
5369 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5370
5371 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5372 EXPECT_EQ(message, plaintext);
5373 plaintext = DecryptMessage(ciphertext2, params_iv2);
5374 EXPECT_EQ(message, plaintext);
5375
5376 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5377 plaintext = DecryptMessage(ciphertext1, params_iv2);
5378 EXPECT_NE(message, plaintext);
5379 plaintext = DecryptMessage(ciphertext2, params_iv1);
5380 EXPECT_NE(message, plaintext);
5381}
5382
5383/*
5384 * EncryptionOperationsTest.AesIncremental
5385 *
5386 * Verifies that AES works, all modes, when provided data in various size increments.
5387 */
5388TEST_P(EncryptionOperationsTest, AesIncremental) {
5389 auto block_modes = {
5390 BlockMode::ECB,
5391 BlockMode::CBC,
5392 BlockMode::CTR,
5393 BlockMode::GCM,
5394 };
5395
5396 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5397 .Authorization(TAG_NO_AUTH_REQUIRED)
5398 .AesEncryptionKey(128)
5399 .BlockMode(block_modes)
5400 .Padding(PaddingMode::NONE)
5401 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5402
5403 for (int increment = 1; increment <= 240; ++increment) {
5404 for (auto block_mode : block_modes) {
5405 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07005406 auto params =
5407 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
5408 if (block_mode == BlockMode::GCM) {
5409 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
5410 }
Selene Huang31ab4042020-04-29 04:22:39 -07005411
5412 AuthorizationSet output_params;
5413 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
5414
5415 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005416 string to_send;
5417 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07005418 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005419 }
Shawn Willden92d79c02021-02-19 07:31:55 -07005420 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
5421 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07005422
5423 switch (block_mode) {
5424 case BlockMode::GCM:
5425 EXPECT_EQ(message.size() + 16, ciphertext.size());
5426 break;
5427 case BlockMode::CTR:
5428 EXPECT_EQ(message.size(), ciphertext.size());
5429 break;
5430 case BlockMode::CBC:
5431 case BlockMode::ECB:
5432 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
5433 break;
5434 }
5435
5436 auto iv = output_params.GetTagValue(TAG_NONCE);
5437 switch (block_mode) {
5438 case BlockMode::CBC:
5439 case BlockMode::GCM:
5440 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005441 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
5442 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
5443 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005444 break;
5445
5446 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005447 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07005448 break;
5449 }
5450
5451 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
5452 << "Decrypt begin() failed for block mode " << block_mode;
5453
5454 string plaintext;
5455 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07005456 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005457 }
5458 ErrorCode error = Finish(to_send, &plaintext);
5459 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
5460 << " and increment " << increment;
5461 if (error == ErrorCode::OK) {
5462 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
5463 << block_mode << " and increment " << increment;
5464 }
5465 }
5466 }
5467}
5468
5469struct AesCtrSp80038aTestVector {
5470 const char* key;
5471 const char* nonce;
5472 const char* plaintext;
5473 const char* ciphertext;
5474};
5475
5476// These test vectors are taken from
5477// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
5478static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
5479 // AES-128
5480 {
5481 "2b7e151628aed2a6abf7158809cf4f3c",
5482 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5483 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5484 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5485 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
5486 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
5487 },
5488 // AES-192
5489 {
5490 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
5491 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5492 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5493 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5494 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
5495 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
5496 },
5497 // AES-256
5498 {
5499 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
5500 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5501 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5502 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5503 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
5504 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
5505 },
5506};
5507
5508/*
5509 * EncryptionOperationsTest.AesCtrSp80038aTestVector
5510 *
5511 * Verifies AES CTR implementation against SP800-38A test vectors.
5512 */
5513TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
5514 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
5515 for (size_t i = 0; i < 3; i++) {
5516 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
5517 const string key = hex2str(test.key);
5518 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
5519 InvalidSizes.end())
5520 continue;
5521 const string nonce = hex2str(test.nonce);
5522 const string plaintext = hex2str(test.plaintext);
5523 const string ciphertext = hex2str(test.ciphertext);
5524 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
5525 }
5526}
5527
5528/*
5529 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
5530 *
5531 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
5532 */
5533TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
5534 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5535 .Authorization(TAG_NO_AUTH_REQUIRED)
5536 .AesEncryptionKey(128)
5537 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5538 .Padding(PaddingMode::PKCS7)));
5539 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5540 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5541}
5542
5543/*
5544 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
5545 *
5546 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5547 */
5548TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
5549 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5550 .Authorization(TAG_NO_AUTH_REQUIRED)
5551 .AesEncryptionKey(128)
5552 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5553 .Authorization(TAG_CALLER_NONCE)
5554 .Padding(PaddingMode::NONE)));
5555
5556 auto params = AuthorizationSetBuilder()
5557 .BlockMode(BlockMode::CTR)
5558 .Padding(PaddingMode::NONE)
5559 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
5560 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5561
5562 params = AuthorizationSetBuilder()
5563 .BlockMode(BlockMode::CTR)
5564 .Padding(PaddingMode::NONE)
5565 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
5566 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5567
5568 params = AuthorizationSetBuilder()
5569 .BlockMode(BlockMode::CTR)
5570 .Padding(PaddingMode::NONE)
5571 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
5572 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5573}
5574
5575/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005576 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07005577 *
5578 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5579 */
5580TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
5581 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5582 .Authorization(TAG_NO_AUTH_REQUIRED)
5583 .AesEncryptionKey(128)
5584 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5585 .Padding(PaddingMode::NONE)));
5586 // Two-block message.
5587 string message = "12345678901234567890123456789012";
5588 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5589 AuthorizationSet out_params;
5590 string ciphertext1 = EncryptMessage(message, params, &out_params);
5591 vector<uint8_t> iv1 = CopyIv(out_params);
5592 EXPECT_EQ(message.size(), ciphertext1.size());
5593
5594 out_params.Clear();
5595
5596 string ciphertext2 = EncryptMessage(message, params, &out_params);
5597 vector<uint8_t> iv2 = CopyIv(out_params);
5598 EXPECT_EQ(message.size(), ciphertext2.size());
5599
5600 // IVs should be random, so ciphertexts should differ.
5601 EXPECT_NE(ciphertext1, ciphertext2);
5602
5603 params.push_back(TAG_NONCE, iv1);
5604 string plaintext = DecryptMessage(ciphertext1, params);
5605 EXPECT_EQ(message, plaintext);
5606}
5607
5608/*
5609 * EncryptionOperationsTest.AesCallerNonce
5610 *
5611 * Verifies that AES caller-provided nonces work correctly.
5612 */
5613TEST_P(EncryptionOperationsTest, AesCallerNonce) {
5614 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5615 .Authorization(TAG_NO_AUTH_REQUIRED)
5616 .AesEncryptionKey(128)
5617 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5618 .Authorization(TAG_CALLER_NONCE)
5619 .Padding(PaddingMode::NONE)));
5620
5621 string message = "12345678901234567890123456789012";
5622
5623 // Don't specify nonce, should get a random one.
5624 AuthorizationSetBuilder params =
5625 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5626 AuthorizationSet out_params;
5627 string ciphertext = EncryptMessage(message, params, &out_params);
5628 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005629 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005630
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005631 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005632 string plaintext = DecryptMessage(ciphertext, params);
5633 EXPECT_EQ(message, plaintext);
5634
5635 // Now specify a nonce, should also work.
5636 params = AuthorizationSetBuilder()
5637 .BlockMode(BlockMode::CBC)
5638 .Padding(PaddingMode::NONE)
5639 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5640 out_params.Clear();
5641 ciphertext = EncryptMessage(message, params, &out_params);
5642
5643 // Decrypt with correct nonce.
5644 plaintext = DecryptMessage(ciphertext, params);
5645 EXPECT_EQ(message, plaintext);
5646
5647 // Try with wrong nonce.
5648 params = AuthorizationSetBuilder()
5649 .BlockMode(BlockMode::CBC)
5650 .Padding(PaddingMode::NONE)
5651 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
5652 plaintext = DecryptMessage(ciphertext, params);
5653 EXPECT_NE(message, plaintext);
5654}
5655
5656/*
5657 * EncryptionOperationsTest.AesCallerNonceProhibited
5658 *
5659 * Verifies that caller-provided nonces are not permitted when not specified in the key
5660 * authorizations.
5661 */
5662TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
5663 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5664 .Authorization(TAG_NO_AUTH_REQUIRED)
5665 .AesEncryptionKey(128)
5666 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5667 .Padding(PaddingMode::NONE)));
5668
5669 string message = "12345678901234567890123456789012";
5670
5671 // Don't specify nonce, should get a random one.
5672 AuthorizationSetBuilder params =
5673 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5674 AuthorizationSet out_params;
5675 string ciphertext = EncryptMessage(message, params, &out_params);
5676 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005677 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005678
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005679 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005680 string plaintext = DecryptMessage(ciphertext, params);
5681 EXPECT_EQ(message, plaintext);
5682
5683 // Now specify a nonce, should fail
5684 params = AuthorizationSetBuilder()
5685 .BlockMode(BlockMode::CBC)
5686 .Padding(PaddingMode::NONE)
5687 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5688 out_params.Clear();
5689 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5690}
5691
5692/*
5693 * EncryptionOperationsTest.AesGcmRoundTripSuccess
5694 *
5695 * Verifies that AES GCM mode works.
5696 */
5697TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
5698 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5699 .Authorization(TAG_NO_AUTH_REQUIRED)
5700 .AesEncryptionKey(128)
5701 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5702 .Padding(PaddingMode::NONE)
5703 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5704
5705 string aad = "foobar";
5706 string message = "123456789012345678901234567890123456";
5707
5708 auto begin_params = AuthorizationSetBuilder()
5709 .BlockMode(BlockMode::GCM)
5710 .Padding(PaddingMode::NONE)
5711 .Authorization(TAG_MAC_LENGTH, 128);
5712
Selene Huang31ab4042020-04-29 04:22:39 -07005713 // Encrypt
5714 AuthorizationSet begin_out_params;
5715 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5716 << "Begin encrypt";
5717 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005718 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5719 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005720 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5721
5722 // Grab nonce
5723 begin_params.push_back(begin_out_params);
5724
5725 // Decrypt.
5726 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07005727 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005728 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005729 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005730 EXPECT_EQ(message.length(), plaintext.length());
5731 EXPECT_EQ(message, plaintext);
5732}
5733
5734/*
5735 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
5736 *
5737 * Verifies that AES GCM mode works, even when there's a long delay
5738 * between operations.
5739 */
5740TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
5741 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5742 .Authorization(TAG_NO_AUTH_REQUIRED)
5743 .AesEncryptionKey(128)
5744 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5745 .Padding(PaddingMode::NONE)
5746 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5747
5748 string aad = "foobar";
5749 string message = "123456789012345678901234567890123456";
5750
5751 auto begin_params = AuthorizationSetBuilder()
5752 .BlockMode(BlockMode::GCM)
5753 .Padding(PaddingMode::NONE)
5754 .Authorization(TAG_MAC_LENGTH, 128);
5755
Selene Huang31ab4042020-04-29 04:22:39 -07005756 // Encrypt
5757 AuthorizationSet begin_out_params;
5758 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5759 << "Begin encrypt";
5760 string ciphertext;
5761 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005762 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005763 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005764 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005765
5766 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5767
5768 // Grab nonce
5769 begin_params.push_back(begin_out_params);
5770
5771 // Decrypt.
5772 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
5773 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005774 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005775 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005776 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005777 sleep(5);
5778 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
5779 EXPECT_EQ(message.length(), plaintext.length());
5780 EXPECT_EQ(message, plaintext);
5781}
5782
5783/*
5784 * EncryptionOperationsTest.AesGcmDifferentNonces
5785 *
5786 * Verifies that encrypting the same data with different nonces produces different outputs.
5787 */
5788TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
5789 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5790 .Authorization(TAG_NO_AUTH_REQUIRED)
5791 .AesEncryptionKey(128)
5792 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5793 .Padding(PaddingMode::NONE)
5794 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5795 .Authorization(TAG_CALLER_NONCE)));
5796
5797 string aad = "foobar";
5798 string message = "123456789012345678901234567890123456";
5799 string nonce1 = "000000000000";
5800 string nonce2 = "111111111111";
5801 string nonce3 = "222222222222";
5802
5803 string ciphertext1 =
5804 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
5805 string ciphertext2 =
5806 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
5807 string ciphertext3 =
5808 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
5809
5810 ASSERT_NE(ciphertext1, ciphertext2);
5811 ASSERT_NE(ciphertext1, ciphertext3);
5812 ASSERT_NE(ciphertext2, ciphertext3);
5813}
5814
5815/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005816 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
5817 *
5818 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
5819 */
5820TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
5821 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5822 .Authorization(TAG_NO_AUTH_REQUIRED)
5823 .AesEncryptionKey(128)
5824 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5825 .Padding(PaddingMode::NONE)
5826 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5827
5828 string aad = "foobar";
5829 string message = "123456789012345678901234567890123456";
5830
5831 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5832 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5833 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5834
5835 ASSERT_NE(ciphertext1, ciphertext2);
5836 ASSERT_NE(ciphertext1, ciphertext3);
5837 ASSERT_NE(ciphertext2, ciphertext3);
5838}
5839
5840/*
Selene Huang31ab4042020-04-29 04:22:39 -07005841 * EncryptionOperationsTest.AesGcmTooShortTag
5842 *
5843 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
5844 */
5845TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
5846 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5847 .Authorization(TAG_NO_AUTH_REQUIRED)
5848 .AesEncryptionKey(128)
5849 .BlockMode(BlockMode::GCM)
5850 .Padding(PaddingMode::NONE)
5851 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5852 string message = "123456789012345678901234567890123456";
5853 auto params = AuthorizationSetBuilder()
5854 .BlockMode(BlockMode::GCM)
5855 .Padding(PaddingMode::NONE)
5856 .Authorization(TAG_MAC_LENGTH, 96);
5857
5858 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
5859}
5860
5861/*
5862 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
5863 *
5864 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
5865 */
5866TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
5867 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5868 .Authorization(TAG_NO_AUTH_REQUIRED)
5869 .AesEncryptionKey(128)
5870 .BlockMode(BlockMode::GCM)
5871 .Padding(PaddingMode::NONE)
5872 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5873 string aad = "foobar";
5874 string message = "123456789012345678901234567890123456";
5875 auto params = AuthorizationSetBuilder()
5876 .BlockMode(BlockMode::GCM)
5877 .Padding(PaddingMode::NONE)
5878 .Authorization(TAG_MAC_LENGTH, 128);
5879
Selene Huang31ab4042020-04-29 04:22:39 -07005880 // Encrypt
5881 AuthorizationSet begin_out_params;
5882 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5883 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005884 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005885
5886 AuthorizationSet finish_out_params;
5887 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005888 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5889 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005890
5891 params = AuthorizationSetBuilder()
5892 .Authorizations(begin_out_params)
5893 .BlockMode(BlockMode::GCM)
5894 .Padding(PaddingMode::NONE)
5895 .Authorization(TAG_MAC_LENGTH, 96);
5896
5897 // Decrypt.
5898 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
5899}
5900
5901/*
5902 * EncryptionOperationsTest.AesGcmCorruptKey
5903 *
5904 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
5905 */
5906TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
5907 const uint8_t nonce_bytes[] = {
5908 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
5909 };
5910 string nonce = make_string(nonce_bytes);
5911 const uint8_t ciphertext_bytes[] = {
5912 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
5913 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
5914 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
5915 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5916 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5917 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5918 };
5919 string ciphertext = make_string(ciphertext_bytes);
5920
5921 auto params = AuthorizationSetBuilder()
5922 .BlockMode(BlockMode::GCM)
5923 .Padding(PaddingMode::NONE)
5924 .Authorization(TAG_MAC_LENGTH, 128)
5925 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5926
5927 auto import_params = AuthorizationSetBuilder()
5928 .Authorization(TAG_NO_AUTH_REQUIRED)
5929 .AesEncryptionKey(128)
5930 .BlockMode(BlockMode::GCM)
5931 .Padding(PaddingMode::NONE)
5932 .Authorization(TAG_CALLER_NONCE)
5933 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5934
5935 // Import correct key and decrypt
5936 const uint8_t key_bytes[] = {
5937 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5938 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5939 };
5940 string key = make_string(key_bytes);
5941 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5942 string plaintext = DecryptMessage(ciphertext, params);
5943 CheckedDeleteKey();
5944
5945 // Corrupt key and attempt to decrypt
5946 key[0] = 0;
5947 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5948 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5949 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5950 CheckedDeleteKey();
5951}
5952
5953/*
5954 * EncryptionOperationsTest.AesGcmAadNoData
5955 *
5956 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5957 * encrypt.
5958 */
5959TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5960 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5961 .Authorization(TAG_NO_AUTH_REQUIRED)
5962 .AesEncryptionKey(128)
5963 .BlockMode(BlockMode::GCM)
5964 .Padding(PaddingMode::NONE)
5965 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5966
5967 string aad = "1234567890123456";
5968 auto params = AuthorizationSetBuilder()
5969 .BlockMode(BlockMode::GCM)
5970 .Padding(PaddingMode::NONE)
5971 .Authorization(TAG_MAC_LENGTH, 128);
5972
Selene Huang31ab4042020-04-29 04:22:39 -07005973 // Encrypt
5974 AuthorizationSet begin_out_params;
5975 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5976 string ciphertext;
5977 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005978 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5979 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005980 EXPECT_TRUE(finish_out_params.empty());
5981
5982 // Grab nonce
5983 params.push_back(begin_out_params);
5984
5985 // Decrypt.
5986 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005987 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005988 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005989 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005990
5991 EXPECT_TRUE(finish_out_params.empty());
5992
5993 EXPECT_EQ("", plaintext);
5994}
5995
5996/*
5997 * EncryptionOperationsTest.AesGcmMultiPartAad
5998 *
5999 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6000 * chunks.
6001 */
6002TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6003 const size_t tag_bits = 128;
6004 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6005 .Authorization(TAG_NO_AUTH_REQUIRED)
6006 .AesEncryptionKey(128)
6007 .BlockMode(BlockMode::GCM)
6008 .Padding(PaddingMode::NONE)
6009 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6010
6011 string message = "123456789012345678901234567890123456";
6012 auto begin_params = AuthorizationSetBuilder()
6013 .BlockMode(BlockMode::GCM)
6014 .Padding(PaddingMode::NONE)
6015 .Authorization(TAG_MAC_LENGTH, tag_bits);
6016 AuthorizationSet begin_out_params;
6017
Selene Huang31ab4042020-04-29 04:22:39 -07006018 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
6019
6020 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006021 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6022 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006023 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006024 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6025 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006026
Selene Huang31ab4042020-04-29 04:22:39 -07006027 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006028 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006029
6030 // Grab nonce.
6031 begin_params.push_back(begin_out_params);
6032
6033 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07006034 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006035 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006036 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006037 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006038 EXPECT_EQ(message, plaintext);
6039}
6040
6041/*
6042 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6043 *
6044 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6045 */
6046TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6047 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6048 .Authorization(TAG_NO_AUTH_REQUIRED)
6049 .AesEncryptionKey(128)
6050 .BlockMode(BlockMode::GCM)
6051 .Padding(PaddingMode::NONE)
6052 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6053
6054 string message = "123456789012345678901234567890123456";
6055 auto begin_params = AuthorizationSetBuilder()
6056 .BlockMode(BlockMode::GCM)
6057 .Padding(PaddingMode::NONE)
6058 .Authorization(TAG_MAC_LENGTH, 128);
6059 AuthorizationSet begin_out_params;
6060
Selene Huang31ab4042020-04-29 04:22:39 -07006061 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
6062
Shawn Willden92d79c02021-02-19 07:31:55 -07006063 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006064 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006065 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6066 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006067
David Drysdaled2cc8c22021-04-15 13:29:45 +01006068 // The failure should have already cancelled the operation.
6069 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6070
Shawn Willden92d79c02021-02-19 07:31:55 -07006071 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006072}
6073
6074/*
6075 * EncryptionOperationsTest.AesGcmBadAad
6076 *
6077 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6078 */
6079TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6080 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6081 .Authorization(TAG_NO_AUTH_REQUIRED)
6082 .AesEncryptionKey(128)
6083 .BlockMode(BlockMode::GCM)
6084 .Padding(PaddingMode::NONE)
6085 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6086
6087 string message = "12345678901234567890123456789012";
6088 auto begin_params = AuthorizationSetBuilder()
6089 .BlockMode(BlockMode::GCM)
6090 .Padding(PaddingMode::NONE)
6091 .Authorization(TAG_MAC_LENGTH, 128);
6092
Selene Huang31ab4042020-04-29 04:22:39 -07006093 // Encrypt
6094 AuthorizationSet begin_out_params;
6095 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006096 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006097 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006098 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006099
6100 // Grab nonce
6101 begin_params.push_back(begin_out_params);
6102
Selene Huang31ab4042020-04-29 04:22:39 -07006103 // Decrypt.
6104 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006105 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006106 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006107 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006108}
6109
6110/*
6111 * EncryptionOperationsTest.AesGcmWrongNonce
6112 *
6113 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6114 */
6115TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6116 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6117 .Authorization(TAG_NO_AUTH_REQUIRED)
6118 .AesEncryptionKey(128)
6119 .BlockMode(BlockMode::GCM)
6120 .Padding(PaddingMode::NONE)
6121 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6122
6123 string message = "12345678901234567890123456789012";
6124 auto begin_params = AuthorizationSetBuilder()
6125 .BlockMode(BlockMode::GCM)
6126 .Padding(PaddingMode::NONE)
6127 .Authorization(TAG_MAC_LENGTH, 128);
6128
Selene Huang31ab4042020-04-29 04:22:39 -07006129 // Encrypt
6130 AuthorizationSet begin_out_params;
6131 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006132 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006133 string ciphertext;
6134 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006135 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006136
6137 // Wrong nonce
6138 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6139
6140 // Decrypt.
6141 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006142 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006143 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006144 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006145
6146 // With wrong nonce, should have gotten garbage plaintext (or none).
6147 EXPECT_NE(message, plaintext);
6148}
6149
6150/*
6151 * EncryptionOperationsTest.AesGcmCorruptTag
6152 *
6153 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6154 */
6155TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6156 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6157 .Authorization(TAG_NO_AUTH_REQUIRED)
6158 .AesEncryptionKey(128)
6159 .BlockMode(BlockMode::GCM)
6160 .Padding(PaddingMode::NONE)
6161 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6162
6163 string aad = "1234567890123456";
6164 string message = "123456789012345678901234567890123456";
6165
6166 auto params = AuthorizationSetBuilder()
6167 .BlockMode(BlockMode::GCM)
6168 .Padding(PaddingMode::NONE)
6169 .Authorization(TAG_MAC_LENGTH, 128);
6170
Selene Huang31ab4042020-04-29 04:22:39 -07006171 // Encrypt
6172 AuthorizationSet begin_out_params;
6173 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006174 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006175 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006176 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006177
6178 // Corrupt tag
6179 ++(*ciphertext.rbegin());
6180
6181 // Grab nonce
6182 params.push_back(begin_out_params);
6183
6184 // Decrypt.
6185 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006186 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006187 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006188 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006189}
6190
6191/*
6192 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
6193 *
6194 * Verifies that 3DES is basically functional.
6195 */
6196TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
6197 auto auths = AuthorizationSetBuilder()
6198 .TripleDesEncryptionKey(168)
6199 .BlockMode(BlockMode::ECB)
6200 .Authorization(TAG_NO_AUTH_REQUIRED)
6201 .Padding(PaddingMode::NONE);
6202
6203 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
6204 // Two-block message.
6205 string message = "1234567890123456";
6206 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6207 string ciphertext1 = EncryptMessage(message, inParams);
6208 EXPECT_EQ(message.size(), ciphertext1.size());
6209
6210 string ciphertext2 = EncryptMessage(string(message), inParams);
6211 EXPECT_EQ(message.size(), ciphertext2.size());
6212
6213 // ECB is deterministic.
6214 EXPECT_EQ(ciphertext1, ciphertext2);
6215
6216 string plaintext = DecryptMessage(ciphertext1, inParams);
6217 EXPECT_EQ(message, plaintext);
6218}
6219
6220/*
6221 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
6222 *
6223 * Verifies that CBC keys reject ECB usage.
6224 */
6225TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
6226 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6227 .TripleDesEncryptionKey(168)
6228 .BlockMode(BlockMode::CBC)
6229 .Authorization(TAG_NO_AUTH_REQUIRED)
6230 .Padding(PaddingMode::NONE)));
6231
6232 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6233 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
6234}
6235
6236/*
6237 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
6238 *
6239 * Tests ECB mode with PKCS#7 padding, various message sizes.
6240 */
6241TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
6242 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6243 .TripleDesEncryptionKey(168)
6244 .BlockMode(BlockMode::ECB)
6245 .Authorization(TAG_NO_AUTH_REQUIRED)
6246 .Padding(PaddingMode::PKCS7)));
6247
6248 for (size_t i = 0; i < 32; ++i) {
6249 string message(i, 'a');
6250 auto inParams =
6251 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6252 string ciphertext = EncryptMessage(message, inParams);
6253 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6254 string plaintext = DecryptMessage(ciphertext, inParams);
6255 EXPECT_EQ(message, plaintext);
6256 }
6257}
6258
6259/*
6260 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
6261 *
6262 * Verifies that keys configured for no padding reject PKCS7 padding
6263 */
6264TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
6265 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6266 .TripleDesEncryptionKey(168)
6267 .BlockMode(BlockMode::ECB)
6268 .Authorization(TAG_NO_AUTH_REQUIRED)
6269 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00006270 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6271 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07006272}
6273
6274/*
6275 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
6276 *
6277 * Verifies that corrupted padding is detected.
6278 */
6279TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
6280 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6281 .TripleDesEncryptionKey(168)
6282 .BlockMode(BlockMode::ECB)
6283 .Authorization(TAG_NO_AUTH_REQUIRED)
6284 .Padding(PaddingMode::PKCS7)));
6285
6286 string message = "a";
6287 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
6288 EXPECT_EQ(8U, ciphertext.size());
6289 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006290
6291 AuthorizationSetBuilder begin_params;
6292 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
6293 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07006294
6295 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
6296 ++ciphertext[ciphertext.size() / 2];
6297
6298 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
6299 string plaintext;
6300 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6301 ErrorCode error = Finish(&plaintext);
6302 if (error == ErrorCode::INVALID_ARGUMENT) {
6303 // This is the expected error, we can exit the test now.
6304 return;
6305 } else {
6306 // Very small chance we got valid decryption, so try again.
6307 ASSERT_EQ(error, ErrorCode::OK);
6308 }
6309 }
6310 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006311}
6312
6313struct TripleDesTestVector {
6314 const char* name;
6315 const KeyPurpose purpose;
6316 const BlockMode block_mode;
6317 const PaddingMode padding_mode;
6318 const char* key;
6319 const char* iv;
6320 const char* input;
6321 const char* output;
6322};
6323
6324// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
6325// of the NIST vectors are multiples of the block size.
6326static const TripleDesTestVector kTripleDesTestVectors[] = {
6327 {
6328 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6329 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
6330 "", // IV
6331 "329d86bdf1bc5af4", // input
6332 "d946c2756d78633f", // output
6333 },
6334 {
6335 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6336 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
6337 "", // IV
6338 "6b1540781b01ce1997adae102dbf3c5b", // input
6339 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
6340 },
6341 {
6342 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6343 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
6344 "", // IV
6345 "6daad94ce08acfe7", // input
6346 "660e7d32dcc90e79", // output
6347 },
6348 {
6349 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6350 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
6351 "", // IV
6352 "e9653a0a1f05d31b9acd12d73aa9879d", // input
6353 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
6354 },
6355 {
6356 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6357 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
6358 "43f791134c5647ba", // IV
6359 "dcc153cef81d6f24", // input
6360 "92538bd8af18d3ba", // output
6361 },
6362 {
6363 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6364 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6365 "c2e999cb6249023c", // IV
6366 "c689aee38a301bb316da75db36f110b5", // input
6367 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
6368 },
6369 {
6370 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
6371 PaddingMode::PKCS7,
6372 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6373 "c2e999cb6249023c", // IV
6374 "c689aee38a301bb316da75db36f110b500", // input
6375 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
6376 },
6377 {
6378 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
6379 PaddingMode::PKCS7,
6380 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6381 "c2e999cb6249023c", // IV
6382 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
6383 "c689aee38a301bb316da75db36f110b500", // output
6384 },
6385 {
6386 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6387 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
6388 "41746c7e442d3681", // IV
6389 "c53a7b0ec40600fe", // input
6390 "d4f00eb455de1034", // output
6391 },
6392 {
6393 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6394 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
6395 "3982bc02c3727d45", // IV
6396 "6006f10adef52991fcc777a1238bbb65", // input
6397 "edae09288e9e3bc05746d872b48e3b29", // output
6398 },
6399};
6400
6401/*
6402 * EncryptionOperationsTest.TripleDesTestVector
6403 *
6404 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
6405 */
6406TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
6407 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
6408 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
6409 SCOPED_TRACE(test->name);
6410 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
6411 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
6412 hex2str(test->output));
6413 }
6414}
6415
6416/*
6417 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
6418 *
6419 * Validates CBC mode functionality.
6420 */
6421TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
6422 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6423 .TripleDesEncryptionKey(168)
6424 .BlockMode(BlockMode::CBC)
6425 .Authorization(TAG_NO_AUTH_REQUIRED)
6426 .Padding(PaddingMode::NONE)));
6427
6428 ASSERT_GT(key_blob_.size(), 0U);
6429
Brian J Murray734c8412022-01-13 14:55:30 -08006430 // Four-block message.
6431 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07006432 vector<uint8_t> iv1;
6433 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
6434 EXPECT_EQ(message.size(), ciphertext1.size());
6435
6436 vector<uint8_t> iv2;
6437 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
6438 EXPECT_EQ(message.size(), ciphertext2.size());
6439
6440 // IVs should be random, so ciphertexts should differ.
6441 EXPECT_NE(iv1, iv2);
6442 EXPECT_NE(ciphertext1, ciphertext2);
6443
6444 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
6445 EXPECT_EQ(message, plaintext);
6446}
6447
6448/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006449 * EncryptionOperationsTest.TripleDesInvalidCallerIv
6450 *
6451 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
6452 */
6453TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
6454 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6455 .TripleDesEncryptionKey(168)
6456 .BlockMode(BlockMode::CBC)
6457 .Authorization(TAG_NO_AUTH_REQUIRED)
6458 .Authorization(TAG_CALLER_NONCE)
6459 .Padding(PaddingMode::NONE)));
6460 auto params = AuthorizationSetBuilder()
6461 .BlockMode(BlockMode::CBC)
6462 .Padding(PaddingMode::NONE)
6463 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
6464 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6465}
6466
6467/*
Selene Huang31ab4042020-04-29 04:22:39 -07006468 * EncryptionOperationsTest.TripleDesCallerIv
6469 *
6470 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
6471 */
6472TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
6473 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6474 .TripleDesEncryptionKey(168)
6475 .BlockMode(BlockMode::CBC)
6476 .Authorization(TAG_NO_AUTH_REQUIRED)
6477 .Authorization(TAG_CALLER_NONCE)
6478 .Padding(PaddingMode::NONE)));
6479 string message = "1234567890123456";
6480 vector<uint8_t> iv;
6481 // Don't specify IV, should get a random one.
6482 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6483 EXPECT_EQ(message.size(), ciphertext1.size());
6484 EXPECT_EQ(8U, iv.size());
6485
6486 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6487 EXPECT_EQ(message, plaintext);
6488
6489 // Now specify an IV, should also work.
6490 iv = AidlBuf("abcdefgh");
6491 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
6492
6493 // Decrypt with correct IV.
6494 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
6495 EXPECT_EQ(message, plaintext);
6496
6497 // Now try with wrong IV.
6498 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
6499 EXPECT_NE(message, plaintext);
6500}
6501
6502/*
6503 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
6504 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01006505 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07006506 */
6507TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
6508 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6509 .TripleDesEncryptionKey(168)
6510 .BlockMode(BlockMode::CBC)
6511 .Authorization(TAG_NO_AUTH_REQUIRED)
6512 .Padding(PaddingMode::NONE)));
6513
6514 string message = "12345678901234567890123456789012";
6515 vector<uint8_t> iv;
6516 // Don't specify nonce, should get a random one.
6517 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6518 EXPECT_EQ(message.size(), ciphertext1.size());
6519 EXPECT_EQ(8U, iv.size());
6520
6521 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6522 EXPECT_EQ(message, plaintext);
6523
6524 // Now specify a nonce, should fail.
6525 auto input_params = AuthorizationSetBuilder()
6526 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
6527 .BlockMode(BlockMode::CBC)
6528 .Padding(PaddingMode::NONE);
6529 AuthorizationSet output_params;
6530 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
6531 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6532}
6533
6534/*
6535 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
6536 *
6537 * Verifies that 3DES ECB-only keys do not allow CBC usage.
6538 */
6539TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
6540 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6541 .TripleDesEncryptionKey(168)
6542 .BlockMode(BlockMode::ECB)
6543 .Authorization(TAG_NO_AUTH_REQUIRED)
6544 .Padding(PaddingMode::NONE)));
6545 // Two-block message.
6546 string message = "1234567890123456";
6547 auto begin_params =
6548 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6549 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6550}
6551
6552/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006553 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07006554 *
6555 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
6556 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01006557TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
6558 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
6559 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6560 .TripleDesEncryptionKey(168)
6561 .BlockMode(blockMode)
6562 .Authorization(TAG_NO_AUTH_REQUIRED)
6563 .Padding(PaddingMode::NONE)));
6564 // Message is slightly shorter than two blocks.
6565 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07006566
David Drysdaled2cc8c22021-04-15 13:29:45 +01006567 auto begin_params =
6568 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
6569 AuthorizationSet output_params;
6570 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
6571 string ciphertext;
6572 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
6573
6574 CheckedDeleteKey();
6575 }
Selene Huang31ab4042020-04-29 04:22:39 -07006576}
6577
6578/*
6579 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
6580 *
6581 * Verifies that PKCS7 padding works correctly in CBC mode.
6582 */
6583TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
6584 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6585 .TripleDesEncryptionKey(168)
6586 .BlockMode(BlockMode::CBC)
6587 .Authorization(TAG_NO_AUTH_REQUIRED)
6588 .Padding(PaddingMode::PKCS7)));
6589
6590 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08006591 for (size_t i = 0; i <= 32; i++) {
6592 SCOPED_TRACE(testing::Message() << "i = " << i);
6593 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
6594 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07006595 vector<uint8_t> iv;
6596 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6597 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6598 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
6599 EXPECT_EQ(message, plaintext);
6600 }
6601}
6602
6603/*
6604 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
6605 *
6606 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
6607 */
6608TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
6609 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6610 .TripleDesEncryptionKey(168)
6611 .BlockMode(BlockMode::CBC)
6612 .Authorization(TAG_NO_AUTH_REQUIRED)
6613 .Padding(PaddingMode::NONE)));
6614
6615 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08006616 for (size_t i = 0; i <= 32; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07006617 auto begin_params =
6618 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
6619 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6620 }
6621}
6622
6623/*
6624 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
6625 *
6626 * Verifies that corrupted PKCS7 padding is rejected during decryption.
6627 */
6628TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
6629 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6630 .TripleDesEncryptionKey(168)
6631 .BlockMode(BlockMode::CBC)
6632 .Authorization(TAG_NO_AUTH_REQUIRED)
6633 .Padding(PaddingMode::PKCS7)));
6634
6635 string message = "a";
6636 vector<uint8_t> iv;
6637 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6638 EXPECT_EQ(8U, ciphertext.size());
6639 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006640
6641 auto begin_params = AuthorizationSetBuilder()
6642 .BlockMode(BlockMode::CBC)
6643 .Padding(PaddingMode::PKCS7)
6644 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07006645
6646 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08006647 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07006648 ++ciphertext[ciphertext.size() / 2];
6649 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
6650 string plaintext;
6651 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6652 ErrorCode error = Finish(&plaintext);
6653 if (error == ErrorCode::INVALID_ARGUMENT) {
6654 // This is the expected error, we can exit the test now.
6655 return;
6656 } else {
6657 // Very small chance we got valid decryption, so try again.
6658 ASSERT_EQ(error, ErrorCode::OK);
6659 }
6660 }
6661 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006662}
6663
6664/*
6665 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
6666 *
6667 * Verifies that 3DES CBC works with many different input sizes.
6668 */
6669TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
6670 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6671 .TripleDesEncryptionKey(168)
6672 .BlockMode(BlockMode::CBC)
6673 .Authorization(TAG_NO_AUTH_REQUIRED)
6674 .Padding(PaddingMode::NONE)));
6675
6676 int increment = 7;
6677 string message(240, 'a');
6678 AuthorizationSet input_params =
6679 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6680 AuthorizationSet output_params;
6681 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6682
6683 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07006684 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006685 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006686 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
6687 EXPECT_EQ(message.size(), ciphertext.size());
6688
6689 // Move TAG_NONCE into input_params
6690 input_params = output_params;
6691 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
6692 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
6693 output_params.Clear();
6694
6695 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
6696 string plaintext;
6697 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006698 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006699 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
6700 EXPECT_EQ(ciphertext.size(), plaintext.size());
6701 EXPECT_EQ(message, plaintext);
6702}
6703
6704INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
6705
6706typedef KeyMintAidlTestBase MaxOperationsTest;
6707
6708/*
6709 * MaxOperationsTest.TestLimitAes
6710 *
6711 * Verifies that the max uses per boot tag works correctly with AES keys.
6712 */
6713TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006714 if (SecLevel() == SecurityLevel::STRONGBOX) {
6715 GTEST_SKIP() << "Test not applicable to StrongBox device";
6716 }
Selene Huang31ab4042020-04-29 04:22:39 -07006717
6718 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6719 .Authorization(TAG_NO_AUTH_REQUIRED)
6720 .AesEncryptionKey(128)
6721 .EcbMode()
6722 .Padding(PaddingMode::NONE)
6723 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
6724
6725 string message = "1234567890123456";
6726
6727 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6728
6729 EncryptMessage(message, params);
6730 EncryptMessage(message, params);
6731 EncryptMessage(message, params);
6732
6733 // Fourth time should fail.
6734 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
6735}
6736
6737/*
Qi Wud22ec842020-11-26 13:27:53 +08006738 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07006739 *
6740 * Verifies that the max uses per boot tag works correctly with RSA keys.
6741 */
6742TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006743 if (SecLevel() == SecurityLevel::STRONGBOX) {
6744 GTEST_SKIP() << "Test not applicable to StrongBox device";
6745 }
Selene Huang31ab4042020-04-29 04:22:39 -07006746
6747 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6748 .Authorization(TAG_NO_AUTH_REQUIRED)
6749 .RsaSigningKey(1024, 65537)
6750 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006751 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
6752 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006753
6754 string message = "1234567890123456";
6755
6756 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6757
6758 SignMessage(message, params);
6759 SignMessage(message, params);
6760 SignMessage(message, params);
6761
6762 // Fourth time should fail.
6763 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
6764}
6765
6766INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
6767
Qi Wud22ec842020-11-26 13:27:53 +08006768typedef KeyMintAidlTestBase UsageCountLimitTest;
6769
6770/*
Qi Wubeefae42021-01-28 23:16:37 +08006771 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006772 *
Qi Wubeefae42021-01-28 23:16:37 +08006773 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006774 */
Qi Wubeefae42021-01-28 23:16:37 +08006775TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006776 if (SecLevel() == SecurityLevel::STRONGBOX) {
6777 GTEST_SKIP() << "Test not applicable to StrongBox device";
6778 }
Qi Wud22ec842020-11-26 13:27:53 +08006779
6780 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6781 .Authorization(TAG_NO_AUTH_REQUIRED)
6782 .AesEncryptionKey(128)
6783 .EcbMode()
6784 .Padding(PaddingMode::NONE)
6785 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
6786
6787 // Check the usage count limit tag appears in the authorizations.
6788 AuthorizationSet auths;
6789 for (auto& entry : key_characteristics_) {
6790 auths.push_back(AuthorizationSet(entry.authorizations));
6791 }
6792 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6793 << "key usage count limit " << 1U << " missing";
6794
6795 string message = "1234567890123456";
6796 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6797
Qi Wubeefae42021-01-28 23:16:37 +08006798 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6799 AuthorizationSet keystore_auths =
6800 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6801
Qi Wud22ec842020-11-26 13:27:53 +08006802 // First usage of AES key should work.
6803 EncryptMessage(message, params);
6804
Qi Wud22ec842020-11-26 13:27:53 +08006805 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6806 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6807 // must be invalidated from secure storage (such as RPMB partition).
6808 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6809 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006810 // Usage count limit tag is enforced by keystore, keymint does nothing.
6811 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08006812 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6813 }
6814}
6815
6816/*
Qi Wubeefae42021-01-28 23:16:37 +08006817 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006818 *
Qi Wubeefae42021-01-28 23:16:37 +08006819 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006820 */
Qi Wubeefae42021-01-28 23:16:37 +08006821TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006822 if (SecLevel() == SecurityLevel::STRONGBOX) {
6823 GTEST_SKIP() << "Test not applicable to StrongBox device";
6824 }
Qi Wubeefae42021-01-28 23:16:37 +08006825
6826 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6827 .Authorization(TAG_NO_AUTH_REQUIRED)
6828 .AesEncryptionKey(128)
6829 .EcbMode()
6830 .Padding(PaddingMode::NONE)
6831 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
6832
6833 // Check the usage count limit tag appears in the authorizations.
6834 AuthorizationSet auths;
6835 for (auto& entry : key_characteristics_) {
6836 auths.push_back(AuthorizationSet(entry.authorizations));
6837 }
6838 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6839 << "key usage count limit " << 3U << " missing";
6840
6841 string message = "1234567890123456";
6842 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6843
6844 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6845 AuthorizationSet keystore_auths =
6846 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6847
6848 EncryptMessage(message, params);
6849 EncryptMessage(message, params);
6850 EncryptMessage(message, params);
6851
6852 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6853 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6854 // must be invalidated from secure storage (such as RPMB partition).
6855 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6856 } else {
6857 // Usage count limit tag is enforced by keystore, keymint does nothing.
6858 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
6859 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6860 }
6861}
6862
6863/*
6864 * UsageCountLimitTest.TestSingleUseRsa
6865 *
6866 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
6867 */
6868TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006869 if (SecLevel() == SecurityLevel::STRONGBOX) {
6870 GTEST_SKIP() << "Test not applicable to StrongBox device";
6871 }
Qi Wud22ec842020-11-26 13:27:53 +08006872
6873 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6874 .Authorization(TAG_NO_AUTH_REQUIRED)
6875 .RsaSigningKey(1024, 65537)
6876 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006877 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6878 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08006879
6880 // Check the usage count limit tag appears in the authorizations.
6881 AuthorizationSet auths;
6882 for (auto& entry : key_characteristics_) {
6883 auths.push_back(AuthorizationSet(entry.authorizations));
6884 }
6885 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6886 << "key usage count limit " << 1U << " missing";
6887
6888 string message = "1234567890123456";
6889 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6890
Qi Wubeefae42021-01-28 23:16:37 +08006891 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6892 AuthorizationSet keystore_auths =
6893 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6894
Qi Wud22ec842020-11-26 13:27:53 +08006895 // First usage of RSA key should work.
6896 SignMessage(message, params);
6897
Qi Wud22ec842020-11-26 13:27:53 +08006898 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6899 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6900 // must be invalidated from secure storage (such as RPMB partition).
6901 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6902 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006903 // Usage count limit tag is enforced by keystore, keymint does nothing.
6904 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
6905 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6906 }
6907}
6908
6909/*
6910 * UsageCountLimitTest.TestLimitUseRsa
6911 *
6912 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
6913 */
6914TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006915 if (SecLevel() == SecurityLevel::STRONGBOX) {
6916 GTEST_SKIP() << "Test not applicable to StrongBox device";
6917 }
Qi Wubeefae42021-01-28 23:16:37 +08006918
6919 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6920 .Authorization(TAG_NO_AUTH_REQUIRED)
6921 .RsaSigningKey(1024, 65537)
6922 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006923 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
6924 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08006925
6926 // Check the usage count limit tag appears in the authorizations.
6927 AuthorizationSet auths;
6928 for (auto& entry : key_characteristics_) {
6929 auths.push_back(AuthorizationSet(entry.authorizations));
6930 }
6931 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6932 << "key usage count limit " << 3U << " missing";
6933
6934 string message = "1234567890123456";
6935 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6936
6937 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6938 AuthorizationSet keystore_auths =
6939 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6940
6941 SignMessage(message, params);
6942 SignMessage(message, params);
6943 SignMessage(message, params);
6944
6945 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6946 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6947 // must be invalidated from secure storage (such as RPMB partition).
6948 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6949 } else {
6950 // Usage count limit tag is enforced by keystore, keymint does nothing.
6951 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006952 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6953 }
6954}
6955
Qi Wu8e727f72021-02-11 02:49:33 +08006956/*
6957 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6958 *
6959 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6960 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6961 * in hardware.
6962 */
6963TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01006964 if (SecLevel() == SecurityLevel::STRONGBOX) {
6965 GTEST_SKIP() << "Test not applicable to StrongBox device";
6966 }
Qi Wu8e727f72021-02-11 02:49:33 +08006967
6968 auto error = GenerateKey(AuthorizationSetBuilder()
6969 .RsaSigningKey(2048, 65537)
6970 .Digest(Digest::NONE)
6971 .Padding(PaddingMode::NONE)
6972 .Authorization(TAG_NO_AUTH_REQUIRED)
6973 .Authorization(TAG_ROLLBACK_RESISTANCE)
6974 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006975 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6976 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08006977 }
David Drysdale513bf122021-10-06 11:53:13 +01006978
6979 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6980 ASSERT_EQ(ErrorCode::OK, error);
6981 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6982 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6983 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6984
6985 // The KeyMint should also enforce single use key in hardware when it supports rollback
6986 // resistance.
6987 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6988 .Authorization(TAG_NO_AUTH_REQUIRED)
6989 .RsaSigningKey(1024, 65537)
6990 .NoDigestOrPadding()
6991 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6992 .SetDefaultValidity()));
6993
6994 // Check the usage count limit tag appears in the hardware authorizations.
6995 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6996 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6997 << "key usage count limit " << 1U << " missing";
6998
6999 string message = "1234567890123456";
7000 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7001
7002 // First usage of RSA key should work.
7003 SignMessage(message, params);
7004
7005 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7006 // must be invalidated from secure storage (such as RPMB partition).
7007 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007008}
7009
Qi Wud22ec842020-11-26 13:27:53 +08007010INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7011
David Drysdale7de9feb2021-03-05 14:56:19 +00007012typedef KeyMintAidlTestBase GetHardwareInfoTest;
7013
7014TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7015 // Retrieving hardware info should give the same result each time.
7016 KeyMintHardwareInfo info;
7017 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7018 KeyMintHardwareInfo info2;
7019 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7020 EXPECT_EQ(info, info2);
7021}
7022
7023INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7024
Selene Huang31ab4042020-04-29 04:22:39 -07007025typedef KeyMintAidlTestBase AddEntropyTest;
7026
7027/*
7028 * AddEntropyTest.AddEntropy
7029 *
7030 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7031 * is actually added.
7032 */
7033TEST_P(AddEntropyTest, AddEntropy) {
7034 string data = "foo";
7035 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7036}
7037
7038/*
7039 * AddEntropyTest.AddEmptyEntropy
7040 *
7041 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7042 */
7043TEST_P(AddEntropyTest, AddEmptyEntropy) {
7044 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7045}
7046
7047/*
7048 * AddEntropyTest.AddLargeEntropy
7049 *
7050 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7051 */
7052TEST_P(AddEntropyTest, AddLargeEntropy) {
7053 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7054}
7055
David Drysdalebb3d85e2021-04-13 11:15:51 +01007056/*
7057 * AddEntropyTest.AddTooLargeEntropy
7058 *
7059 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7060 */
7061TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7062 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7063 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7064}
7065
Selene Huang31ab4042020-04-29 04:22:39 -07007066INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7067
Selene Huang31ab4042020-04-29 04:22:39 -07007068typedef KeyMintAidlTestBase KeyDeletionTest;
7069
7070/**
7071 * KeyDeletionTest.DeleteKey
7072 *
7073 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7074 * valid key blob.
7075 */
7076TEST_P(KeyDeletionTest, DeleteKey) {
7077 auto error = GenerateKey(AuthorizationSetBuilder()
7078 .RsaSigningKey(2048, 65537)
7079 .Digest(Digest::NONE)
7080 .Padding(PaddingMode::NONE)
7081 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007082 .Authorization(TAG_ROLLBACK_RESISTANCE)
7083 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007084 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7085 GTEST_SKIP() << "Rollback resistance not supported";
7086 }
Selene Huang31ab4042020-04-29 04:22:39 -07007087
7088 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007089 ASSERT_EQ(ErrorCode::OK, error);
7090 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7091 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007092
David Drysdale513bf122021-10-06 11:53:13 +01007093 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007094
David Drysdale513bf122021-10-06 11:53:13 +01007095 string message = "12345678901234567890123456789012";
7096 AuthorizationSet begin_out_params;
7097 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7098 Begin(KeyPurpose::SIGN, key_blob_,
7099 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7100 &begin_out_params));
7101 AbortIfNeeded();
7102 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007103}
7104
7105/**
7106 * KeyDeletionTest.DeleteInvalidKey
7107 *
7108 * This test checks that the HAL excepts invalid key blobs..
7109 */
7110TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7111 // Generate key just to check if rollback protection is implemented
7112 auto error = GenerateKey(AuthorizationSetBuilder()
7113 .RsaSigningKey(2048, 65537)
7114 .Digest(Digest::NONE)
7115 .Padding(PaddingMode::NONE)
7116 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007117 .Authorization(TAG_ROLLBACK_RESISTANCE)
7118 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007119 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7120 GTEST_SKIP() << "Rollback resistance not supported";
7121 }
Selene Huang31ab4042020-04-29 04:22:39 -07007122
7123 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007124 ASSERT_EQ(ErrorCode::OK, error);
7125 AuthorizationSet enforced(SecLevelAuthorizations());
7126 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007127
David Drysdale513bf122021-10-06 11:53:13 +01007128 // Delete the key we don't care about the result at this point.
7129 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007130
David Drysdale513bf122021-10-06 11:53:13 +01007131 // Now create an invalid key blob and delete it.
7132 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007133
David Drysdale513bf122021-10-06 11:53:13 +01007134 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007135}
7136
7137/**
7138 * KeyDeletionTest.DeleteAllKeys
7139 *
7140 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7141 *
7142 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7143 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7144 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7145 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7146 * credentials stored in Keystore/Keymint.
7147 */
7148TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007149 if (!arm_deleteAllKeys) {
7150 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7151 return;
7152 }
Selene Huang31ab4042020-04-29 04:22:39 -07007153 auto error = GenerateKey(AuthorizationSetBuilder()
7154 .RsaSigningKey(2048, 65537)
7155 .Digest(Digest::NONE)
7156 .Padding(PaddingMode::NONE)
7157 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007158 .Authorization(TAG_ROLLBACK_RESISTANCE)
7159 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007160 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7161 GTEST_SKIP() << "Rollback resistance not supported";
7162 }
Selene Huang31ab4042020-04-29 04:22:39 -07007163
7164 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007165 ASSERT_EQ(ErrorCode::OK, error);
7166 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7167 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007168
David Drysdale513bf122021-10-06 11:53:13 +01007169 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007170
David Drysdale513bf122021-10-06 11:53:13 +01007171 string message = "12345678901234567890123456789012";
7172 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07007173
David Drysdale513bf122021-10-06 11:53:13 +01007174 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7175 Begin(KeyPurpose::SIGN, key_blob_,
7176 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7177 &begin_out_params));
7178 AbortIfNeeded();
7179 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007180}
7181
7182INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
7183
David Drysdaled2cc8c22021-04-15 13:29:45 +01007184typedef KeyMintAidlTestBase KeyUpgradeTest;
7185
7186/**
7187 * KeyUpgradeTest.UpgradeInvalidKey
7188 *
7189 * This test checks that the HAL excepts invalid key blobs..
7190 */
7191TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
7192 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
7193
7194 std::vector<uint8_t> new_blob;
7195 Status result = keymint_->upgradeKey(key_blob,
7196 AuthorizationSetBuilder()
7197 .Authorization(TAG_APPLICATION_ID, "clientid")
7198 .Authorization(TAG_APPLICATION_DATA, "appdata")
7199 .vector_data(),
7200 &new_blob);
7201 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
7202}
7203
7204INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
7205
Selene Huang31ab4042020-04-29 04:22:39 -07007206using UpgradeKeyTest = KeyMintAidlTestBase;
7207
7208/*
7209 * UpgradeKeyTest.UpgradeKey
7210 *
7211 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
7212 */
7213TEST_P(UpgradeKeyTest, UpgradeKey) {
7214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7215 .AesEncryptionKey(128)
7216 .Padding(PaddingMode::NONE)
7217 .Authorization(TAG_NO_AUTH_REQUIRED)));
7218
7219 auto result = UpgradeKey(key_blob_);
7220
7221 // Key doesn't need upgrading. Should get okay, but no new key blob.
7222 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
7223}
7224
7225INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
7226
7227using ClearOperationsTest = KeyMintAidlTestBase;
7228
7229/*
7230 * ClearSlotsTest.TooManyOperations
7231 *
7232 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
7233 * operations are started without being finished or aborted. Also verifies
7234 * that aborting the operations clears the operations.
7235 *
7236 */
7237TEST_P(ClearOperationsTest, TooManyOperations) {
7238 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7239 .Authorization(TAG_NO_AUTH_REQUIRED)
7240 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08007241 .Padding(PaddingMode::NONE)
7242 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007243
7244 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
7245 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08007246 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07007247 AuthorizationSet out_params;
7248 ErrorCode result;
7249 size_t i;
7250
7251 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00007252 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07007253 if (ErrorCode::OK != result) {
7254 break;
7255 }
7256 }
7257 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
7258 // Try again just in case there's a weird overflow bug
7259 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00007260 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007261 for (size_t j = 0; j < i; j++) {
7262 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
7263 << "Aboort failed for i = " << j << std::endl;
7264 }
subrahmanyaman05642492022-02-05 07:10:56 +00007265 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007266 AbortIfNeeded();
7267}
7268
7269INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
7270
7271typedef KeyMintAidlTestBase TransportLimitTest;
7272
7273/*
David Drysdale7de9feb2021-03-05 14:56:19 +00007274 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07007275 *
7276 * Verifies that passing input data to finish succeeds as expected.
7277 */
7278TEST_P(TransportLimitTest, LargeFinishInput) {
7279 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7280 .Authorization(TAG_NO_AUTH_REQUIRED)
7281 .AesEncryptionKey(128)
7282 .BlockMode(BlockMode::ECB)
7283 .Padding(PaddingMode::NONE)));
7284
7285 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
7286 auto cipher_params =
7287 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7288
7289 AuthorizationSet out_params;
7290 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
7291
7292 string plain_message = std::string(1 << msg_size, 'x');
7293 string encrypted_message;
7294 auto rc = Finish(plain_message, &encrypted_message);
7295
7296 EXPECT_EQ(ErrorCode::OK, rc);
7297 EXPECT_EQ(plain_message.size(), encrypted_message.size())
7298 << "Encrypt finish returned OK, but did not consume all of the given input";
7299 cipher_params.push_back(out_params);
7300
7301 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
7302
7303 string decrypted_message;
7304 rc = Finish(encrypted_message, &decrypted_message);
7305 EXPECT_EQ(ErrorCode::OK, rc);
7306 EXPECT_EQ(plain_message.size(), decrypted_message.size())
7307 << "Decrypt finish returned OK, did not consume all of the given input";
7308 }
7309}
7310
7311INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
7312
Seth Moored79a0ec2021-12-13 20:03:33 +00007313static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05007314 switch (curve) {
7315 case EcCurve::P_224:
7316 return NID_secp224r1;
7317 case EcCurve::P_256:
7318 return NID_X9_62_prime256v1;
7319 case EcCurve::P_384:
7320 return NID_secp384r1;
7321 case EcCurve::P_521:
7322 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00007323 case EcCurve::CURVE_25519:
7324 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05007325 }
7326}
7327
David Drysdale42fe1892021-10-14 14:43:46 +01007328class KeyAgreementTest : public KeyMintAidlTestBase {
7329 protected:
7330 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
7331 std::vector<uint8_t>* localPublicKey) {
7332 // Generate EC key locally (with access to private key material)
7333 if (localCurve == EcCurve::CURVE_25519) {
7334 uint8_t privKeyData[32];
7335 uint8_t pubKeyData[32];
7336 X25519_keypair(pubKeyData, privKeyData);
7337 *localPublicKey = vector<uint8_t>(pubKeyData, pubKeyData + 32);
7338 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
7339 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
7340 } else {
7341 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
7342 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
7343 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
7344 ASSERT_NE(group, nullptr);
7345 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
7346 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
7347 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
7348 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
7349
7350 // Get encoded form of the public part of the locally generated key...
7351 unsigned char* p = nullptr;
7352 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
7353 ASSERT_GT(localPublicKeySize, 0);
7354 *localPublicKey =
7355 vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
7356 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
7357 OPENSSL_free(p);
7358 }
7359 }
7360
7361 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
7362 vector<uint8_t> challenge = {0x41, 0x42};
7363 ErrorCode result =
7364 GenerateKey(AuthorizationSetBuilder()
7365 .Authorization(TAG_NO_AUTH_REQUIRED)
7366 .Authorization(TAG_EC_CURVE, curve)
7367 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7368 .Authorization(TAG_ALGORITHM, Algorithm::EC)
7369 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
7370 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
7371 .SetDefaultValidity());
7372 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
7373 ASSERT_GT(cert_chain_.size(), 0);
7374 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7375 ASSERT_NE(kmKeyCert, nullptr);
7376 // Check that keyAgreement (bit 4) is set in KeyUsage
7377 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
7378 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
7379 ASSERT_NE(*kmPubKey, nullptr);
7380 if (dump_Attestations) {
7381 for (size_t n = 0; n < cert_chain_.size(); n++) {
7382 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
7383 }
7384 }
7385 }
7386
7387 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
7388 const std::vector<uint8_t>& localPublicKey) {
7389 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7390 string ZabFromKeyMintStr;
7391 ASSERT_EQ(ErrorCode::OK,
7392 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
7393 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
7394 vector<uint8_t> ZabFromTest;
7395
7396 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
7397 size_t kmPubKeySize = 32;
7398 uint8_t kmPubKeyData[32];
7399 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7400 ASSERT_EQ(kmPubKeySize, 32);
7401
7402 uint8_t localPrivKeyData[32];
7403 size_t localPrivKeySize = 32;
7404 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
7405 &localPrivKeySize));
7406 ASSERT_EQ(localPrivKeySize, 32);
7407
7408 uint8_t sharedKey[32];
7409 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
7410 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
7411 } else {
7412 // Perform local ECDH between the two keys so we can check if we get the same Zab..
7413 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
7414 ASSERT_NE(ctx, nullptr);
7415 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
7416 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
7417 size_t ZabFromTestLen = 0;
7418 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
7419 ZabFromTest.resize(ZabFromTestLen);
7420 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
7421 }
7422 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
7423 }
7424};
7425
David Zeuthene0c40892021-01-08 12:54:11 -05007426/*
7427 * KeyAgreementTest.Ecdh
7428 *
David Drysdale42fe1892021-10-14 14:43:46 +01007429 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05007430 */
7431TEST_P(KeyAgreementTest, Ecdh) {
7432 // Because it's possible to use this API with keys on different curves, we
7433 // check all N^2 combinations where N is the number of supported
7434 // curves.
7435 //
7436 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
7437 // lot more curves we can be smart about things and just pick |otherCurve| so
7438 // it's not |curve| and that way we end up with only 2*N runs
7439 //
7440 for (auto curve : ValidCurves()) {
7441 for (auto localCurve : ValidCurves()) {
7442 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007443 EVP_PKEY_Ptr localPrivKey;
7444 vector<uint8_t> localPublicKey;
7445 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007446
7447 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007448 EVP_PKEY_Ptr kmPubKey;
7449 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007450
7451 // Now that we have the two keys, we ask KeyMint to perform ECDH...
7452 if (curve != localCurve) {
7453 // If the keys are using different curves KeyMint should fail with
7454 // ErrorCode:INVALID_ARGUMENT. Check that.
7455 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7456 string ZabFromKeyMintStr;
7457 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01007458 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05007459 &ZabFromKeyMintStr));
7460
7461 } else {
7462 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01007463 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007464 }
7465
7466 CheckedDeleteKey();
7467 }
7468 }
7469}
7470
David Drysdale42fe1892021-10-14 14:43:46 +01007471/*
7472 * KeyAgreementTest.EcdhCurve25519
7473 *
7474 * Verifies that ECDH works for curve25519. This is also covered by the general
7475 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
7476 * KeyMint 1.0.
7477 */
7478TEST_P(KeyAgreementTest, EcdhCurve25519) {
7479 if (!Curve25519Supported()) {
7480 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7481 }
7482
7483 // Generate EC key in KeyMint (only access to public key material)
7484 EcCurve curve = EcCurve::CURVE_25519;
7485 EVP_PKEY_Ptr kmPubKey = nullptr;
7486 GenerateKeyMintEcKey(curve, &kmPubKey);
7487
7488 // Generate EC key on same curve locally (with access to private key material).
7489 EVP_PKEY_Ptr privKey;
7490 vector<uint8_t> encodedPublicKey;
7491 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7492
7493 // Agree on a key between local and KeyMint and check it.
7494 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7495
7496 CheckedDeleteKey();
7497}
7498
7499/*
7500 * KeyAgreementTest.EcdhCurve25519Imported
7501 *
7502 * Verifies that ECDH works for an imported curve25519 key.
7503 */
7504TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
7505 if (!Curve25519Supported()) {
7506 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7507 }
7508
7509 // Import x25519 key into KeyMint.
7510 EcCurve curve = EcCurve::CURVE_25519;
7511 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
7512 .Authorization(TAG_NO_AUTH_REQUIRED)
7513 .EcdsaKey(EcCurve::CURVE_25519)
7514 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7515 .SetDefaultValidity(),
7516 KeyFormat::PKCS8, x25519_pkcs8_key));
7517 ASSERT_GT(cert_chain_.size(), 0);
7518 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7519 ASSERT_NE(kmKeyCert, nullptr);
7520 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
7521 ASSERT_NE(kmPubKey.get(), nullptr);
7522
7523 // Expect the import to emit corresponding public key data.
7524 size_t kmPubKeySize = 32;
7525 uint8_t kmPubKeyData[32];
7526 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7527 ASSERT_EQ(kmPubKeySize, 32);
7528 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
7529 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
7530
7531 // Generate EC key on same curve locally (with access to private key material).
7532 EVP_PKEY_Ptr privKey;
7533 vector<uint8_t> encodedPublicKey;
7534 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7535
7536 // Agree on a key between local and KeyMint and check it.
7537 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7538
7539 CheckedDeleteKey();
7540}
7541
7542/*
7543 * KeyAgreementTest.EcdhCurve25519InvalidSize
7544 *
7545 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
7546 */
7547TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
7548 if (!Curve25519Supported()) {
7549 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7550 }
7551
7552 // Generate EC key in KeyMint (only access to public key material)
7553 EcCurve curve = EcCurve::CURVE_25519;
7554 EVP_PKEY_Ptr kmPubKey = nullptr;
7555 GenerateKeyMintEcKey(curve, &kmPubKey);
7556
7557 // Generate EC key on same curve locally (with access to private key material).
7558 EVP_PKEY_Ptr privKey;
7559 vector<uint8_t> encodedPublicKey;
7560 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7561
7562 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7563 string ZabFromKeyMintStr;
7564 // Send in an incomplete public key.
7565 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
7566 &ZabFromKeyMintStr));
7567
7568 CheckedDeleteKey();
7569}
7570
7571/*
7572 * KeyAgreementTest.EcdhCurve25519Mismatch
7573 *
7574 * Verifies that ECDH fails between curve25519 and other curves.
7575 */
7576TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
7577 if (!Curve25519Supported()) {
7578 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7579 }
7580
7581 // Generate EC key in KeyMint (only access to public key material)
7582 EcCurve curve = EcCurve::CURVE_25519;
7583 EVP_PKEY_Ptr kmPubKey = nullptr;
7584 GenerateKeyMintEcKey(curve, &kmPubKey);
7585
7586 for (auto localCurve : ValidCurves()) {
7587 if (localCurve == curve) {
7588 continue;
7589 }
7590 // Generate EC key on a different curve locally (with access to private key material).
7591 EVP_PKEY_Ptr privKey;
7592 vector<uint8_t> encodedPublicKey;
7593 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
7594
7595 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7596 string ZabFromKeyMintStr;
7597 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
7598 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
7599 &ZabFromKeyMintStr));
7600 }
7601
7602 CheckedDeleteKey();
7603}
7604
David Zeuthene0c40892021-01-08 12:54:11 -05007605INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
7606
David Drysdaled2cc8c22021-04-15 13:29:45 +01007607using DestroyAttestationIdsTest = KeyMintAidlTestBase;
7608
7609// This is a problematic test, as it can render the device under test permanently unusable.
7610// Re-enable and run at your own risk.
7611TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
7612 auto result = DestroyAttestationIds();
7613 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
7614}
7615
7616INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
7617
Shawn Willdend659c7c2021-02-19 14:51:51 -07007618using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007619
David Drysdaledb0dcf52021-05-18 11:43:31 +01007620/*
7621 * EarlyBootKeyTest.CreateEarlyBootKeys
7622 *
7623 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
7624 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007625TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01007626 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007627 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7628 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7629
David Drysdaleadfe6112021-05-27 12:00:53 +01007630 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
7631 ASSERT_GT(keyData.blob.size(), 0U);
7632 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7633 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7634 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007635 CheckedDeleteKey(&aesKeyData.blob);
7636 CheckedDeleteKey(&hmacKeyData.blob);
7637 CheckedDeleteKey(&rsaKeyData.blob);
7638 CheckedDeleteKey(&ecdsaKeyData.blob);
7639}
7640
David Drysdaledb0dcf52021-05-18 11:43:31 +01007641/*
David Drysdaleadfe6112021-05-27 12:00:53 +01007642 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
7643 *
7644 * Verifies that creating an early boot key with attestation succeeds.
7645 */
7646TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
7647 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
7648 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
7649 builder->AttestationChallenge("challenge");
7650 builder->AttestationApplicationId("app_id");
7651 });
7652
7653 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00007654 // Strongbox may not support factory attestation. Key creation might fail with
7655 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
7656 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
7657 continue;
7658 }
David Drysdaleadfe6112021-05-27 12:00:53 +01007659 ASSERT_GT(keyData.blob.size(), 0U);
7660 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7661 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7662 }
7663 CheckedDeleteKey(&aesKeyData.blob);
7664 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00007665 if (rsaKeyData.blob.size() != 0U) {
7666 CheckedDeleteKey(&rsaKeyData.blob);
7667 }
7668 if (ecdsaKeyData.blob.size() != 0U) {
7669 CheckedDeleteKey(&ecdsaKeyData.blob);
7670 }
David Drysdaleadfe6112021-05-27 12:00:53 +01007671}
7672
7673/*
7674 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01007675 *
7676 * Verifies that using early boot keys at a later stage fails.
7677 */
7678TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
7679 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7680 .Authorization(TAG_NO_AUTH_REQUIRED)
7681 .Authorization(TAG_EARLY_BOOT_ONLY)
7682 .HmacKey(128)
7683 .Digest(Digest::SHA_2_256)
7684 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
7685 AuthorizationSet output_params;
7686 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
7687 AuthorizationSetBuilder()
7688 .Digest(Digest::SHA_2_256)
7689 .Authorization(TAG_MAC_LENGTH, 256),
7690 &output_params));
7691}
7692
7693/*
7694 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
7695 *
7696 * Verifies that importing early boot keys fails.
7697 */
7698TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
7699 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
7700 .Authorization(TAG_NO_AUTH_REQUIRED)
7701 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01007702 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01007703 .Digest(Digest::SHA_2_256)
7704 .SetDefaultValidity(),
7705 KeyFormat::PKCS8, ec_256_key));
7706}
7707
David Drysdaled2cc8c22021-04-15 13:29:45 +01007708// 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 +00007709// boot stage, which no proper Android device is by the time we can run VTS. To use this,
7710// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
7711// early boot, so you'll have to reboot between runs.
7712TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
7713 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7714 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7715 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
7716 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7717 EXPECT_TRUE(
7718 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7719 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7720 EXPECT_TRUE(
7721 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7722
7723 // Should be able to use keys, since early boot has not ended
7724 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7725 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
7726 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
7727 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
7728
7729 // End early boot
7730 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
7731 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
7732
7733 // Should not be able to use already-created keys.
7734 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
7735 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
7736 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
7737 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
7738
7739 CheckedDeleteKey(&aesKeyData.blob);
7740 CheckedDeleteKey(&hmacKeyData.blob);
7741 CheckedDeleteKey(&rsaKeyData.blob);
7742 CheckedDeleteKey(&ecdsaKeyData.blob);
7743
7744 // Should not be able to create new keys
7745 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
7746 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
7747
7748 CheckedDeleteKey(&aesKeyData.blob);
7749 CheckedDeleteKey(&hmacKeyData.blob);
7750 CheckedDeleteKey(&rsaKeyData.blob);
7751 CheckedDeleteKey(&ecdsaKeyData.blob);
7752}
Shawn Willdend659c7c2021-02-19 14:51:51 -07007753
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007754INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
7755
Shawn Willdend659c7c2021-02-19 14:51:51 -07007756using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007757
7758// This may be a problematic test. It can't be run repeatedly without unlocking the device in
7759// between runs... and on most test devices there are no enrolled credentials so it can't be
7760// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
7761// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
7762// a manual test process, which includes unlocking between runs, which is why it's included here.
7763// Well, that and the fact that it's the only test we can do without also making calls into the
7764// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
7765// implications might be, so that may or may not be a solution.
7766TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
7767 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7768 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
7769
7770 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7771 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
7772 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
7773 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
7774
7775 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01007776 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007777 ASSERT_EQ(ErrorCode::OK, rc);
7778 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
7779 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
7780 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
7781 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
7782
7783 CheckedDeleteKey(&aesKeyData.blob);
7784 CheckedDeleteKey(&hmacKeyData.blob);
7785 CheckedDeleteKey(&rsaKeyData.blob);
7786 CheckedDeleteKey(&ecdsaKeyData.blob);
7787}
Shawn Willdend659c7c2021-02-19 14:51:51 -07007788
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007789INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
7790
Janis Danisevskis24c04702020-12-16 18:28:39 -08007791} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07007792
7793int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07007794 std::cout << "Testing ";
7795 auto halInstances =
7796 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
7797 std::cout << "HAL instances:\n";
7798 for (auto& entry : halInstances) {
7799 std::cout << " " << entry << '\n';
7800 }
7801
Selene Huang31ab4042020-04-29 04:22:39 -07007802 ::testing::InitGoogleTest(&argc, argv);
7803 for (int i = 1; i < argc; ++i) {
7804 if (argv[i][0] == '-') {
7805 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07007806 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
7807 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07007808 }
7809 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07007810 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
7811 dump_Attestations = true;
7812 } else {
7813 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07007814 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00007815 if (std::string(argv[i]) == "--skip_boot_pl_check") {
7816 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
7817 // be run in emulated environments that don't have the normal bootloader
7818 // interactions.
7819 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
7820 }
Selene Huang31ab4042020-04-29 04:22:39 -07007821 }
7822 }
Shawn Willden08a7e432020-12-11 13:05:27 +00007823 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07007824}