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