blob: 3930074b472e9bb20939df47df98c6e56b179a5b [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) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000616 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
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) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000625 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
David Drysdale7de9feb2021-03-05 14:56:19 +0000626 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
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000632 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics,
633 const KeyOrigin expectedKeyOrigin) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000634 // TODO(swillden): Distinguish which params should be in which auth list.
635 AuthorizationSet auths;
636 for (auto& entry : keyCharacteristics) {
637 auths.push_back(AuthorizationSet(entry.authorizations));
638 }
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000639 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, expectedKeyOrigin));
David Drysdale7de9feb2021-03-05 14:56:19 +0000640
641 // Verify that App data, ROT and auth timeout are NOT included.
642 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
643 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700644 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
645
David Drysdaled2cc8c22021-04-15 13:29:45 +0100646 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
647 // never adds it.
648 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
649
David Drysdale7de9feb2021-03-05 14:56:19 +0000650 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700651 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000652 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700653 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700654 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000655 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700656 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000657
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000658 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100659 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
660 EXPECT_TRUE(vendor_pl);
661 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000662
663 // Should include boot patchlevel (but there are some test scenarios where this is not
664 // possible).
665 if (check_boot_pl) {
666 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
667 EXPECT_TRUE(boot_pl);
668 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100669
David Drysdale7de9feb2021-03-05 14:56:19 +0000670 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700671 }
672};
673
674/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000675 * NewKeyGenerationTest.Aes
676 *
677 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
678 * have correct characteristics.
679 */
680TEST_P(NewKeyGenerationTest, Aes) {
681 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
682 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
683 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
684 SCOPED_TRACE(testing::Message()
685 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
686 vector<uint8_t> key_blob;
687 vector<KeyCharacteristics> key_characteristics;
688 auto builder = AuthorizationSetBuilder()
689 .AesEncryptionKey(key_size)
690 .BlockMode(block_mode)
691 .Padding(padding_mode)
692 .SetDefaultValidity();
693 if (block_mode == BlockMode::GCM) {
694 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
695 }
696 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
697
698 EXPECT_GT(key_blob.size(), 0U);
699 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100700 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000701
702 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
703
704 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
705 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
706 << "Key size " << key_size << "missing";
707
708 CheckedDeleteKey(&key_blob);
709 }
710 }
711 }
712}
713
714/*
715 * NewKeyGenerationTest.AesInvalidSize
716 *
717 * Verifies that specifying an invalid key size for AES key generation returns
718 * UNSUPPORTED_KEY_SIZE.
719 */
720TEST_P(NewKeyGenerationTest, AesInvalidSize) {
721 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
722 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
723 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
724 SCOPED_TRACE(testing::Message()
725 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
726 vector<uint8_t> key_blob;
727 vector<KeyCharacteristics> key_characteristics;
728 auto builder = AuthorizationSetBuilder()
729 .AesEncryptionKey(key_size)
730 .BlockMode(block_mode)
731 .Padding(padding_mode)
732 .SetDefaultValidity();
733 if (block_mode == BlockMode::GCM) {
734 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
735 }
736 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
737 GenerateKey(builder, &key_blob, &key_characteristics));
738 }
739 }
740 }
741
742 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
743 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
744 vector<uint8_t> key_blob;
745 vector<KeyCharacteristics> key_characteristics;
746 // No key size specified
747 auto builder = AuthorizationSetBuilder()
748 .Authorization(TAG_ALGORITHM, Algorithm::AES)
749 .BlockMode(block_mode)
750 .Padding(padding_mode)
751 .SetDefaultValidity();
752 if (block_mode == BlockMode::GCM) {
753 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
754 }
755 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
756 GenerateKey(builder, &key_blob, &key_characteristics));
757 }
758 }
759}
760
761/*
762 * NewKeyGenerationTest.AesInvalidPadding
763 *
764 * Verifies that specifying an invalid padding on AES keys gives a failure
765 * somewhere along the way.
766 */
767TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
768 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
769 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
770 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
771 SCOPED_TRACE(testing::Message()
772 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000773 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800774 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000775 .AesEncryptionKey(key_size)
776 .BlockMode(block_mode)
777 .Padding(padding_mode)
778 .SetDefaultValidity();
779 if (block_mode == BlockMode::GCM) {
780 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
781 }
782
Tommy Chiu3950b452021-05-03 22:01:46 +0800783 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000784 if (result == ErrorCode::OK) {
785 // Key creation was OK but has generated a key that cannot be used.
786 auto params =
787 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800788 if (block_mode == BlockMode::GCM) {
789 params.Authorization(TAG_MAC_LENGTH, 128);
790 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000791 auto result = Begin(KeyPurpose::ENCRYPT, params);
792 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100793 result == ErrorCode::INVALID_KEY_BLOB)
794 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000795 } else {
796 // The KeyMint implementation detected that the generated key
797 // is unusable.
798 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
799 }
800 }
801 }
802 }
803}
804
805/*
806 * NewKeyGenerationTest.AesGcmMissingMinMac
807 *
808 * Verifies that specifying an invalid key size for AES key generation returns
809 * UNSUPPORTED_KEY_SIZE.
810 */
811TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
812 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
813 BlockMode block_mode = BlockMode::GCM;
814 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
815 SCOPED_TRACE(testing::Message()
816 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
817 vector<uint8_t> key_blob;
818 vector<KeyCharacteristics> key_characteristics;
819 // No MIN_MAC_LENGTH provided.
820 auto builder = AuthorizationSetBuilder()
821 .AesEncryptionKey(key_size)
822 .BlockMode(block_mode)
823 .Padding(padding_mode)
824 .SetDefaultValidity();
825 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
826 GenerateKey(builder, &key_blob, &key_characteristics));
827 }
828 }
829}
830
831/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100832 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
833 *
834 * Verifies that specifying an invalid min MAC size for AES key generation returns
835 * UNSUPPORTED_MIN_MAC_LENGTH.
836 */
837TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
838 for (size_t min_mac_len : {88, 136}) {
839 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
840 BlockMode block_mode = BlockMode::GCM;
841 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
842 SCOPED_TRACE(testing::Message()
843 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
844 vector<uint8_t> key_blob;
845 vector<KeyCharacteristics> key_characteristics;
846 auto builder = AuthorizationSetBuilder()
847 .AesEncryptionKey(key_size)
848 .BlockMode(block_mode)
849 .Padding(padding_mode)
850 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
851 .SetDefaultValidity();
852 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
853 GenerateKey(builder, &key_blob, &key_characteristics));
854 }
855 }
856 }
857}
858
859/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000860 * NewKeyGenerationTest.TripleDes
861 *
862 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
863 * have correct characteristics.
864 */
865TEST_P(NewKeyGenerationTest, TripleDes) {
866 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
867 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
868 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
869 SCOPED_TRACE(testing::Message()
870 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
871 vector<uint8_t> key_blob;
872 vector<KeyCharacteristics> key_characteristics;
873 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
874 .TripleDesEncryptionKey(key_size)
875 .BlockMode(block_mode)
876 .Padding(padding_mode)
877 .Authorization(TAG_NO_AUTH_REQUIRED)
878 .SetDefaultValidity(),
879 &key_blob, &key_characteristics));
880
881 EXPECT_GT(key_blob.size(), 0U);
882 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100883 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000884
885 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
886
887 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
888 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
889 << "Key size " << key_size << "missing";
890
891 CheckedDeleteKey(&key_blob);
892 }
893 }
894 }
895}
896
897/*
898 * NewKeyGenerationTest.TripleDesWithAttestation
899 *
900 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
901 * have correct characteristics.
902 *
903 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
904 * put in a certificate) but which isn't an error.
905 */
906TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
907 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
908 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
909 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
910 SCOPED_TRACE(testing::Message()
911 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
912
913 auto challenge = "hello";
914 auto app_id = "foo";
915
916 vector<uint8_t> key_blob;
917 vector<KeyCharacteristics> key_characteristics;
918 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
919 .TripleDesEncryptionKey(key_size)
920 .BlockMode(block_mode)
921 .Padding(padding_mode)
922 .Authorization(TAG_NO_AUTH_REQUIRED)
923 .AttestationChallenge(challenge)
924 .AttestationApplicationId(app_id)
925 .SetDefaultValidity(),
926 &key_blob, &key_characteristics));
927
928 EXPECT_GT(key_blob.size(), 0U);
929 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100930 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000931
932 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
933
934 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
935 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
936 << "Key size " << key_size << "missing";
937
938 CheckedDeleteKey(&key_blob);
939 }
940 }
941 }
942}
943
944/*
945 * NewKeyGenerationTest.TripleDesInvalidSize
946 *
947 * Verifies that specifying an invalid key size for 3-DES key generation returns
948 * UNSUPPORTED_KEY_SIZE.
949 */
950TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
951 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
952 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
953 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
954 SCOPED_TRACE(testing::Message()
955 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
956 vector<uint8_t> key_blob;
957 vector<KeyCharacteristics> key_characteristics;
958 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
959 GenerateKey(AuthorizationSetBuilder()
960 .TripleDesEncryptionKey(key_size)
961 .BlockMode(block_mode)
962 .Padding(padding_mode)
963 .Authorization(TAG_NO_AUTH_REQUIRED)
964 .SetDefaultValidity(),
965 &key_blob, &key_characteristics));
966 }
967 }
968 }
969
970 // Omitting the key size fails.
971 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
972 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
973 SCOPED_TRACE(testing::Message()
974 << "3DES-default-" << block_mode << "-" << padding_mode);
975 vector<uint8_t> key_blob;
976 vector<KeyCharacteristics> key_characteristics;
977 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
978 GenerateKey(AuthorizationSetBuilder()
979 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
980 .BlockMode(block_mode)
981 .Padding(padding_mode)
982 .Authorization(TAG_NO_AUTH_REQUIRED)
983 .SetDefaultValidity(),
984 &key_blob, &key_characteristics));
985 }
986 }
987}
988
989/*
Selene Huang31ab4042020-04-29 04:22:39 -0700990 * NewKeyGenerationTest.Rsa
991 *
992 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
993 * have correct characteristics.
994 */
995TEST_P(NewKeyGenerationTest, Rsa) {
996 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
997 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700998 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700999 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1000 .RsaSigningKey(key_size, 65537)
1001 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001002 .Padding(PaddingMode::NONE)
1003 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001004 &key_blob, &key_characteristics));
1005
1006 ASSERT_GT(key_blob.size(), 0U);
1007 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001008 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001009
Shawn Willden7f424372021-01-10 18:06:50 -07001010 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001011
1012 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1013 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1014 << "Key size " << key_size << "missing";
1015 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1016
1017 CheckedDeleteKey(&key_blob);
1018 }
1019}
1020
1021/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001022 * NewKeyGenerationTest.RsaWithMissingValidity
1023 *
1024 * Verifies that keymint returns an error while generating asymmetric key
1025 * without providing NOT_BEFORE and NOT_AFTER parameters.
1026 */
1027TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
1028 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1029 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1030 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1031
1032 vector<uint8_t> key_blob;
1033 vector<KeyCharacteristics> key_characteristics;
1034 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1035 GenerateKey(AuthorizationSetBuilder()
1036 .RsaSigningKey(2048, 65537)
1037 .Digest(Digest::NONE)
1038 .Padding(PaddingMode::NONE)
1039 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1040 kUndefinedExpirationDateTime),
1041 &key_blob, &key_characteristics));
1042
1043 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1044 GenerateKey(AuthorizationSetBuilder()
1045 .RsaSigningKey(2048, 65537)
1046 .Digest(Digest::NONE)
1047 .Padding(PaddingMode::NONE)
1048 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1049 &key_blob, &key_characteristics));
1050}
1051
1052/*
Qi Wud22ec842020-11-26 13:27:53 +08001053 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001054 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001055 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1056 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001057 */
1058TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001059 auto challenge = "hello";
1060 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001061
Selene Huang6e46f142021-04-20 19:20:11 -07001062 auto subject = "cert subj 2";
1063 vector<uint8_t> subject_der(make_name_from_str(subject));
1064
1065 uint64_t serial_int = 66;
1066 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1067
Selene Huang4f64c222021-04-13 19:54:36 -07001068 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001069 vector<uint8_t> key_blob;
1070 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001071 auto builder = AuthorizationSetBuilder()
1072 .RsaSigningKey(key_size, 65537)
1073 .Digest(Digest::NONE)
1074 .Padding(PaddingMode::NONE)
1075 .AttestationChallenge(challenge)
1076 .AttestationApplicationId(app_id)
1077 .Authorization(TAG_NO_AUTH_REQUIRED)
1078 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1079 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1080 .SetDefaultValidity();
1081
1082 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001083 // Strongbox may not support factory provisioned attestation key.
1084 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001085 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1086 result = GenerateKeyWithSelfSignedAttestKey(
1087 AuthorizationSetBuilder()
1088 .RsaKey(key_size, 65537)
1089 .AttestKey()
1090 .SetDefaultValidity(), /* attest key params */
1091 builder, &key_blob, &key_characteristics);
1092 }
subrahmanyaman05642492022-02-05 07:10:56 +00001093 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001094 ASSERT_EQ(ErrorCode::OK, result);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001095 ASSERT_GT(key_blob.size(), 0U);
1096 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001097 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001098
1099 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1100
1101 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1102 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1103 << "Key size " << key_size << "missing";
1104 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1105
David Drysdalea8a888e2022-06-08 12:43:56 +01001106 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001107 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001108 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001109
1110 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1111 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001112 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001113 sw_enforced, hw_enforced, SecLevel(),
1114 cert_chain_[0].encodedCertificate));
1115
1116 CheckedDeleteKey(&key_blob);
1117 }
1118}
1119
1120/*
David Drysdale4dc01072021-04-01 12:17:35 +01001121 * NewKeyGenerationTest.RsaWithRpkAttestation
1122 *
1123 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
1124 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale0fce69d2021-04-13 17:22:13 +01001125 *
1126 * This test is disabled because the KeyMint specification does not require that implementations
1127 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
1128 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +01001129 */
David Drysdale0fce69d2021-04-13 17:22:13 +01001130TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +01001131 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
1132 // instance.
1133 std::shared_ptr<IRemotelyProvisionedComponent> rp;
1134 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
1135 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
1136
1137 // Generate a P-256 keypair to use as an attestation key.
1138 MacedPublicKey macedPubKey;
1139 std::vector<uint8_t> privateKeyBlob;
1140 auto status =
1141 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1142 ASSERT_TRUE(status.isOk());
1143 vector<uint8_t> coseKeyData;
1144 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1145
1146 AttestationKey attestation_key;
1147 attestation_key.keyBlob = std::move(privateKeyBlob);
1148 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1149
1150 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1151 auto challenge = "hello";
1152 auto app_id = "foo";
1153
1154 vector<uint8_t> key_blob;
1155 vector<KeyCharacteristics> key_characteristics;
1156 ASSERT_EQ(ErrorCode::OK,
1157 GenerateKey(AuthorizationSetBuilder()
1158 .RsaSigningKey(key_size, 65537)
1159 .Digest(Digest::NONE)
1160 .Padding(PaddingMode::NONE)
1161 .AttestationChallenge(challenge)
1162 .AttestationApplicationId(app_id)
1163 .Authorization(TAG_NO_AUTH_REQUIRED)
1164 .SetDefaultValidity(),
1165 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1166
1167 ASSERT_GT(key_blob.size(), 0U);
1168 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001169 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001170
1171 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1172
1173 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1174 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1175 << "Key size " << key_size << "missing";
1176 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1177
1178 // Attestation by itself is not valid (last entry is not self-signed).
1179 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1180
1181 // The signature over the attested key should correspond to the P256 public key.
David Drysdalea8a888e2022-06-08 12:43:56 +01001182 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale4dc01072021-04-01 12:17:35 +01001183 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1184 ASSERT_TRUE(key_cert.get());
1185 EVP_PKEY_Ptr signing_pubkey;
1186 p256_pub_key(coseKeyData, &signing_pubkey);
1187 ASSERT_TRUE(signing_pubkey.get());
1188
1189 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1190 << "Verification of attested certificate failed "
1191 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1192
1193 CheckedDeleteKey(&key_blob);
1194 }
1195}
1196
1197/*
Selene Huang4f64c222021-04-13 19:54:36 -07001198 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1199 *
1200 * Verifies that keymint attestation for RSA encryption keys with challenge and
1201 * app id is also successful.
1202 */
1203TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1204 auto key_size = 2048;
1205 auto challenge = "hello";
1206 auto app_id = "foo";
1207
Selene Huang6e46f142021-04-20 19:20:11 -07001208 auto subject = "subj 2";
1209 vector<uint8_t> subject_der(make_name_from_str(subject));
1210
1211 uint64_t serial_int = 111166;
1212 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1213
Selene Huang4f64c222021-04-13 19:54:36 -07001214 vector<uint8_t> key_blob;
1215 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001216 auto builder = AuthorizationSetBuilder()
1217 .RsaEncryptionKey(key_size, 65537)
1218 .Padding(PaddingMode::NONE)
1219 .AttestationChallenge(challenge)
1220 .AttestationApplicationId(app_id)
1221 .Authorization(TAG_NO_AUTH_REQUIRED)
1222 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1223 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1224 .SetDefaultValidity();
1225
1226 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001227 // Strongbox may not support factory provisioned attestation key.
1228 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001229 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1230 result = GenerateKeyWithSelfSignedAttestKey(
1231 AuthorizationSetBuilder()
1232 .RsaKey(key_size, 65537)
1233 .AttestKey()
1234 .SetDefaultValidity(), /* attest key params */
1235 builder, &key_blob, &key_characteristics);
1236 }
subrahmanyaman05642492022-02-05 07:10:56 +00001237 }
1238 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001239
1240 ASSERT_GT(key_blob.size(), 0U);
1241 AuthorizationSet auths;
1242 for (auto& entry : key_characteristics) {
1243 auths.push_back(AuthorizationSet(entry.authorizations));
1244 }
1245
1246 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1247 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1248
1249 // Verify that App data and ROT are NOT included.
1250 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1251 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1252
1253 // Check that some unexpected tags/values are NOT present.
1254 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1255 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1256
1257 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1258
1259 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1260 ASSERT_TRUE(os_ver);
1261 EXPECT_EQ(*os_ver, os_version());
1262
1263 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1264
1265 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1266 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1267 << "Key size " << key_size << "missing";
1268 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1269
David Drysdalea8a888e2022-06-08 12:43:56 +01001270 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001271 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001272 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001273
1274 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1275 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001276 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001277 sw_enforced, hw_enforced, SecLevel(),
1278 cert_chain_[0].encodedCertificate));
1279
1280 CheckedDeleteKey(&key_blob);
1281}
1282
1283/*
1284 * NewKeyGenerationTest.RsaWithSelfSign
1285 *
1286 * Verifies that attesting to RSA key generation is successful, and returns
1287 * self signed certificate if no challenge is provided. And signing etc
1288 * works as expected.
1289 */
1290TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001291 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1292 vector<uint8_t> subject_der(make_name_from_str(subject));
1293
1294 uint64_t serial_int = 0;
1295 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1296
Selene Huang4f64c222021-04-13 19:54:36 -07001297 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1298 vector<uint8_t> key_blob;
1299 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001300 ASSERT_EQ(ErrorCode::OK,
1301 GenerateKey(AuthorizationSetBuilder()
1302 .RsaSigningKey(key_size, 65537)
1303 .Digest(Digest::NONE)
1304 .Padding(PaddingMode::NONE)
1305 .Authorization(TAG_NO_AUTH_REQUIRED)
1306 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1307 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1308 .SetDefaultValidity(),
1309 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001310
1311 ASSERT_GT(key_blob.size(), 0U);
1312 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001313 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001314
1315 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1316
1317 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1318 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1319 << "Key size " << key_size << "missing";
1320 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1321
David Drysdalea8a888e2022-06-08 12:43:56 +01001322 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang6e46f142021-04-20 19:20:11 -07001323 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001324 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001325
1326 CheckedDeleteKey(&key_blob);
1327 }
1328}
1329
1330/*
1331 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1332 *
1333 * Verifies that attesting to RSA checks for missing app ID.
1334 */
1335TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1336 auto challenge = "hello";
1337 vector<uint8_t> key_blob;
1338 vector<KeyCharacteristics> key_characteristics;
1339
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001340 auto builder = AuthorizationSetBuilder()
1341 .RsaSigningKey(2048, 65537)
1342 .Digest(Digest::NONE)
1343 .Padding(PaddingMode::NONE)
1344 .AttestationChallenge(challenge)
1345 .Authorization(TAG_NO_AUTH_REQUIRED)
1346 .SetDefaultValidity();
1347
1348 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001349 // Strongbox may not support factory provisioned attestation key.
1350 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001351 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1352 result = GenerateKeyWithSelfSignedAttestKey(
1353 AuthorizationSetBuilder()
1354 .RsaKey(2048, 65537)
1355 .AttestKey()
1356 .SetDefaultValidity(), /* attest key params */
1357 builder, &key_blob, &key_characteristics);
1358 }
subrahmanyaman05642492022-02-05 07:10:56 +00001359 }
1360 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001361}
1362
1363/*
1364 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1365 *
1366 * Verifies that attesting to RSA ignores app id if challenge is missing.
1367 */
1368TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1369 auto key_size = 2048;
1370 auto app_id = "foo";
1371
Selene Huang6e46f142021-04-20 19:20:11 -07001372 auto subject = "cert subj 2";
1373 vector<uint8_t> subject_der(make_name_from_str(subject));
1374
1375 uint64_t serial_int = 1;
1376 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1377
Selene Huang4f64c222021-04-13 19:54:36 -07001378 vector<uint8_t> key_blob;
1379 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001380 ASSERT_EQ(ErrorCode::OK,
1381 GenerateKey(AuthorizationSetBuilder()
1382 .RsaSigningKey(key_size, 65537)
1383 .Digest(Digest::NONE)
1384 .Padding(PaddingMode::NONE)
1385 .AttestationApplicationId(app_id)
1386 .Authorization(TAG_NO_AUTH_REQUIRED)
1387 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1388 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1389 .SetDefaultValidity(),
1390 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001391
1392 ASSERT_GT(key_blob.size(), 0U);
1393 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001394 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001395
1396 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1397
1398 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1399 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1400 << "Key size " << key_size << "missing";
1401 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1402
David Drysdalea8a888e2022-06-08 12:43:56 +01001403 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001404 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001405 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1406 ASSERT_EQ(cert_chain_.size(), 1);
1407
1408 CheckedDeleteKey(&key_blob);
1409}
1410
1411/*
Qi Wud22ec842020-11-26 13:27:53 +08001412 * NewKeyGenerationTest.LimitedUsageRsa
1413 *
1414 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1415 * resulting keys have correct characteristics.
1416 */
1417TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1418 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1419 vector<uint8_t> key_blob;
1420 vector<KeyCharacteristics> key_characteristics;
1421 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1422 .RsaSigningKey(key_size, 65537)
1423 .Digest(Digest::NONE)
1424 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001425 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1426 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001427 &key_blob, &key_characteristics));
1428
1429 ASSERT_GT(key_blob.size(), 0U);
1430 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001431 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001432
1433 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1434
1435 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1436 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1437 << "Key size " << key_size << "missing";
1438 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1439
1440 // Check the usage count limit tag appears in the authorizations.
1441 AuthorizationSet auths;
1442 for (auto& entry : key_characteristics) {
1443 auths.push_back(AuthorizationSet(entry.authorizations));
1444 }
1445 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1446 << "key usage count limit " << 1U << " missing";
1447
1448 CheckedDeleteKey(&key_blob);
1449 }
1450}
1451
1452/*
Qi Wubeefae42021-01-28 23:16:37 +08001453 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1454 *
1455 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1456 * resulting keys have correct characteristics and attestation.
1457 */
1458TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001459 auto challenge = "hello";
1460 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001461
Selene Huang6e46f142021-04-20 19:20:11 -07001462 auto subject = "cert subj 2";
1463 vector<uint8_t> subject_der(make_name_from_str(subject));
1464
1465 uint64_t serial_int = 66;
1466 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1467
Selene Huang4f64c222021-04-13 19:54:36 -07001468 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001469 vector<uint8_t> key_blob;
1470 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001471 auto builder = AuthorizationSetBuilder()
1472 .RsaSigningKey(key_size, 65537)
1473 .Digest(Digest::NONE)
1474 .Padding(PaddingMode::NONE)
1475 .AttestationChallenge(challenge)
1476 .AttestationApplicationId(app_id)
1477 .Authorization(TAG_NO_AUTH_REQUIRED)
1478 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1479 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1480 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1481 .SetDefaultValidity();
1482
1483 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001484 // Strongbox may not support factory provisioned attestation key.
1485 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001486 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1487 result = GenerateKeyWithSelfSignedAttestKey(
1488 AuthorizationSetBuilder()
1489 .RsaKey(key_size, 65537)
1490 .AttestKey()
1491 .SetDefaultValidity(), /* attest key params */
1492 builder, &key_blob, &key_characteristics);
1493 }
subrahmanyaman05642492022-02-05 07:10:56 +00001494 }
1495 ASSERT_EQ(ErrorCode::OK, result);
Qi Wubeefae42021-01-28 23:16:37 +08001496
1497 ASSERT_GT(key_blob.size(), 0U);
1498 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001499 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001500
1501 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1502
1503 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1504 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1505 << "Key size " << key_size << "missing";
1506 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1507
1508 // Check the usage count limit tag appears in the authorizations.
1509 AuthorizationSet auths;
1510 for (auto& entry : key_characteristics) {
1511 auths.push_back(AuthorizationSet(entry.authorizations));
1512 }
1513 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1514 << "key usage count limit " << 1U << " missing";
1515
1516 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001517 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001518 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001519 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001520
1521 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1522 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001523 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001524 sw_enforced, hw_enforced, SecLevel(),
1525 cert_chain_[0].encodedCertificate));
1526
1527 CheckedDeleteKey(&key_blob);
1528 }
1529}
1530
1531/*
Selene Huang31ab4042020-04-29 04:22:39 -07001532 * NewKeyGenerationTest.NoInvalidRsaSizes
1533 *
1534 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1535 */
1536TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1537 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1538 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001539 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001540 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1541 GenerateKey(AuthorizationSetBuilder()
1542 .RsaSigningKey(key_size, 65537)
1543 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001544 .Padding(PaddingMode::NONE)
1545 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001546 &key_blob, &key_characteristics));
1547 }
1548}
1549
1550/*
1551 * NewKeyGenerationTest.RsaNoDefaultSize
1552 *
1553 * Verifies that failing to specify a key size for RSA key generation returns
1554 * UNSUPPORTED_KEY_SIZE.
1555 */
1556TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1557 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1558 GenerateKey(AuthorizationSetBuilder()
1559 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1560 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001561 .SigningKey()
1562 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001563}
1564
1565/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001566 * NewKeyGenerationTest.RsaMissingParams
1567 *
1568 * Verifies that omitting optional tags works.
1569 */
1570TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1571 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1572 ASSERT_EQ(ErrorCode::OK,
1573 GenerateKey(
1574 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1575 CheckedDeleteKey();
1576 }
1577}
1578
1579/*
Selene Huang31ab4042020-04-29 04:22:39 -07001580 * NewKeyGenerationTest.Ecdsa
1581 *
David Drysdale42fe1892021-10-14 14:43:46 +01001582 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001583 * have correct characteristics.
1584 */
1585TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001586 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001587 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001588 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001589 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001590 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001591 .Digest(Digest::NONE)
1592 .SetDefaultValidity(),
1593 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001594 ASSERT_GT(key_blob.size(), 0U);
1595 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001596 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001597
Shawn Willden7f424372021-01-10 18:06:50 -07001598 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001599
1600 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001601 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001602
1603 CheckedDeleteKey(&key_blob);
1604 }
1605}
1606
1607/*
David Drysdale42fe1892021-10-14 14:43:46 +01001608 * NewKeyGenerationTest.EcdsaCurve25519
1609 *
1610 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1611 * has correct characteristics.
1612 */
1613TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1614 if (!Curve25519Supported()) {
1615 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1616 }
1617
1618 EcCurve curve = EcCurve::CURVE_25519;
1619 vector<uint8_t> key_blob;
1620 vector<KeyCharacteristics> key_characteristics;
1621 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1622 .EcdsaSigningKey(curve)
1623 .Digest(Digest::NONE)
1624 .SetDefaultValidity(),
1625 &key_blob, &key_characteristics);
1626 ASSERT_EQ(result, ErrorCode::OK);
1627 ASSERT_GT(key_blob.size(), 0U);
1628
1629 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1630 ASSERT_GT(cert_chain_.size(), 0);
1631
1632 CheckBaseParams(key_characteristics);
1633 CheckCharacteristics(key_blob, key_characteristics);
1634
1635 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1636
1637 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1638 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1639
1640 CheckedDeleteKey(&key_blob);
1641}
1642
1643/*
1644 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1645 *
1646 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1647 * SIGN and AGREE_KEY.
1648 */
1649TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1650 if (!Curve25519Supported()) {
1651 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1652 }
1653
1654 EcCurve curve = EcCurve::CURVE_25519;
1655 vector<uint8_t> key_blob;
1656 vector<KeyCharacteristics> key_characteristics;
1657 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1658 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1659 .EcdsaSigningKey(curve)
1660 .Digest(Digest::NONE)
1661 .SetDefaultValidity(),
1662 &key_blob, &key_characteristics);
1663 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1664}
1665
1666/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001667 * NewKeyGenerationTest.EcdsaWithMissingValidity
1668 *
1669 * Verifies that keymint returns an error while generating asymmetric key
1670 * without providing NOT_BEFORE and NOT_AFTER parameters.
1671 */
1672TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
1673 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1674 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1675 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1676
1677 vector<uint8_t> key_blob;
1678 vector<KeyCharacteristics> key_characteristics;
1679 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1680 GenerateKey(AuthorizationSetBuilder()
1681 .EcdsaSigningKey(EcCurve::P_256)
1682 .Digest(Digest::NONE)
1683 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1684 kUndefinedExpirationDateTime),
1685 &key_blob, &key_characteristics));
1686
1687 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1688 GenerateKey(AuthorizationSetBuilder()
1689 .EcdsaSigningKey(EcCurve::P_256)
1690 .Digest(Digest::NONE)
1691 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1692 &key_blob, &key_characteristics));
1693}
1694
1695/*
Selene Huang4f64c222021-04-13 19:54:36 -07001696 * NewKeyGenerationTest.EcdsaAttestation
1697 *
1698 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1699 * an attestation will be generated.
1700 */
1701TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1702 auto challenge = "hello";
1703 auto app_id = "foo";
1704
Selene Huang6e46f142021-04-20 19:20:11 -07001705 auto subject = "cert subj 2";
1706 vector<uint8_t> subject_der(make_name_from_str(subject));
1707
1708 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1709 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1710
David Drysdaledf09e542021-06-08 15:46:11 +01001711 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001712 vector<uint8_t> key_blob;
1713 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001714 auto builder = AuthorizationSetBuilder()
1715 .Authorization(TAG_NO_AUTH_REQUIRED)
1716 .EcdsaSigningKey(curve)
1717 .Digest(Digest::NONE)
1718 .AttestationChallenge(challenge)
1719 .AttestationApplicationId(app_id)
1720 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1721 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1722 .SetDefaultValidity();
1723
1724 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001725 // Strongbox may not support factory provisioned attestation key.
1726 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001727 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1728 result = GenerateKeyWithSelfSignedAttestKey(
1729 AuthorizationSetBuilder()
1730 .EcdsaKey(curve)
1731 .AttestKey()
1732 .SetDefaultValidity(), /* attest key params */
1733 builder, &key_blob, &key_characteristics);
1734 }
subrahmanyaman05642492022-02-05 07:10:56 +00001735 }
1736 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001737 ASSERT_GT(key_blob.size(), 0U);
1738 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001739 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001740
1741 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1742
1743 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001744 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001745
1746 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1747 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001748 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001749
1750 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1751 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001752 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001753 sw_enforced, hw_enforced, SecLevel(),
1754 cert_chain_[0].encodedCertificate));
1755
1756 CheckedDeleteKey(&key_blob);
1757 }
1758}
1759
1760/*
David Drysdale42fe1892021-10-14 14:43:46 +01001761 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1762 *
1763 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1764 * an attestation will be generated.
1765 */
1766TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1767 if (!Curve25519Supported()) {
1768 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1769 }
1770
1771 EcCurve curve = EcCurve::CURVE_25519;
1772 auto challenge = "hello";
1773 auto app_id = "foo";
1774
1775 auto subject = "cert subj 2";
1776 vector<uint8_t> subject_der(make_name_from_str(subject));
1777
1778 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1779 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1780
1781 vector<uint8_t> key_blob;
1782 vector<KeyCharacteristics> key_characteristics;
1783 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1784 .Authorization(TAG_NO_AUTH_REQUIRED)
1785 .EcdsaSigningKey(curve)
1786 .Digest(Digest::NONE)
1787 .AttestationChallenge(challenge)
1788 .AttestationApplicationId(app_id)
1789 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1790 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1791 .SetDefaultValidity(),
1792 &key_blob, &key_characteristics);
1793 ASSERT_EQ(ErrorCode::OK, result);
1794 ASSERT_GT(key_blob.size(), 0U);
1795 CheckBaseParams(key_characteristics);
1796 CheckCharacteristics(key_blob, key_characteristics);
1797
1798 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1799
1800 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1801 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1802
1803 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1804 ASSERT_GT(cert_chain_.size(), 0);
1805 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1806
1807 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1808 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1809 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1810 sw_enforced, hw_enforced, SecLevel(),
1811 cert_chain_[0].encodedCertificate));
1812
1813 CheckedDeleteKey(&key_blob);
1814}
1815
1816/*
David Drysdale37af4b32021-05-14 16:46:59 +01001817 * NewKeyGenerationTest.EcdsaAttestationTags
1818 *
1819 * Verifies that creation of an attested ECDSA key includes various tags in the
1820 * attestation extension.
1821 */
1822TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1823 auto challenge = "hello";
1824 auto app_id = "foo";
1825 auto subject = "cert subj 2";
1826 vector<uint8_t> subject_der(make_name_from_str(subject));
1827 uint64_t serial_int = 0x1010;
1828 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1829 const AuthorizationSetBuilder base_builder =
1830 AuthorizationSetBuilder()
1831 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001832 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001833 .Digest(Digest::NONE)
1834 .AttestationChallenge(challenge)
1835 .AttestationApplicationId(app_id)
1836 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1837 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1838 .SetDefaultValidity();
1839
1840 // Various tags that map to fields in the attestation extension ASN.1 schema.
1841 auto extra_tags = AuthorizationSetBuilder()
1842 .Authorization(TAG_ROLLBACK_RESISTANCE)
1843 .Authorization(TAG_EARLY_BOOT_ONLY)
1844 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1845 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1846 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1847 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1848 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1849 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1850 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1851 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1852 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1853 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001854
David Drysdale37af4b32021-05-14 16:46:59 +01001855 for (const KeyParameter& tag : extra_tags) {
1856 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1857 vector<uint8_t> key_blob;
1858 vector<KeyCharacteristics> key_characteristics;
1859 AuthorizationSetBuilder builder = base_builder;
1860 builder.push_back(tag);
1861 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1862 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1863 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1864 continue;
1865 }
Seth Mooreb393b082021-07-12 14:18:28 -07001866 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1867 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001868 continue;
1869 }
subrahmanyaman05642492022-02-05 07:10:56 +00001870 // Strongbox may not support factory provisioned attestation key.
1871 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001872 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1873 result = GenerateKeyWithSelfSignedAttestKey(
1874 AuthorizationSetBuilder()
1875 .EcdsaKey(EcCurve::P_256)
1876 .AttestKey()
1877 .SetDefaultValidity(), /* attest key params */
1878 builder, &key_blob, &key_characteristics);
1879 }
subrahmanyaman05642492022-02-05 07:10:56 +00001880 }
David Drysdale37af4b32021-05-14 16:46:59 +01001881 ASSERT_EQ(result, ErrorCode::OK);
1882 ASSERT_GT(key_blob.size(), 0U);
1883
1884 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1885 ASSERT_GT(cert_chain_.size(), 0);
1886 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1887
1888 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1889 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001890 // Some tags are optional, so don't require them to be in the enforcements.
1891 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001892 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1893 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1894 }
1895
1896 // Verifying the attestation record will check for the specific tag because
1897 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001898 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1899 hw_enforced, SecLevel(),
1900 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01001901
1902 CheckedDeleteKey(&key_blob);
1903 }
1904
David Drysdalec53b7d92021-10-11 12:35:58 +01001905 // Collection of invalid attestation ID tags.
1906 auto invalid_tags =
1907 AuthorizationSetBuilder()
1908 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1909 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1910 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1911 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1912 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
1913 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
1914 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
1915 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01001916 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01001917 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01001918 vector<uint8_t> key_blob;
1919 vector<KeyCharacteristics> key_characteristics;
1920 AuthorizationSetBuilder builder =
1921 AuthorizationSetBuilder()
1922 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001923 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001924 .Digest(Digest::NONE)
1925 .AttestationChallenge(challenge)
1926 .AttestationApplicationId(app_id)
1927 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1928 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1929 .SetDefaultValidity();
1930 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001931
1932 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
1933 // Strongbox may not support factory provisioned attestation key.
1934 if (SecLevel() == SecurityLevel::STRONGBOX) {
1935 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1936 error = GenerateKeyWithSelfSignedAttestKey(
1937 AuthorizationSetBuilder()
1938 .EcdsaKey(EcCurve::P_256)
1939 .AttestKey()
1940 .SetDefaultValidity(), /* attest key params */
1941 builder, &key_blob, &key_characteristics);
1942 }
1943 }
1944 ASSERT_EQ(error, ErrorCode::CANNOT_ATTEST_IDS);
David Drysdale37af4b32021-05-14 16:46:59 +01001945 }
1946}
1947
1948/*
David Drysdalec53b7d92021-10-11 12:35:58 +01001949 * NewKeyGenerationTest.EcdsaAttestationIdTags
1950 *
1951 * Verifies that creation of an attested ECDSA key includes various ID tags in the
1952 * attestation extension.
1953 */
1954TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
David Drysdale555ba002022-05-03 18:48:57 +01001955 if (is_gsi_image()) {
1956 // GSI sets up a standard set of device identifiers that may not match
1957 // the device identifiers held by the device.
1958 GTEST_SKIP() << "Test not applicable under GSI";
1959 }
David Drysdalec53b7d92021-10-11 12:35:58 +01001960 auto challenge = "hello";
1961 auto app_id = "foo";
1962 auto subject = "cert subj 2";
1963 vector<uint8_t> subject_der(make_name_from_str(subject));
1964 uint64_t serial_int = 0x1010;
1965 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1966 const AuthorizationSetBuilder base_builder =
1967 AuthorizationSetBuilder()
1968 .Authorization(TAG_NO_AUTH_REQUIRED)
1969 .EcdsaSigningKey(EcCurve::P_256)
1970 .Digest(Digest::NONE)
1971 .AttestationChallenge(challenge)
1972 .AttestationApplicationId(app_id)
1973 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1974 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1975 .SetDefaultValidity();
1976
1977 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
1978 auto extra_tags = AuthorizationSetBuilder();
1979 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
1980 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
1981 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
1982 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
1983 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
1984 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
1985
1986 for (const KeyParameter& tag : extra_tags) {
1987 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1988 vector<uint8_t> key_blob;
1989 vector<KeyCharacteristics> key_characteristics;
1990 AuthorizationSetBuilder builder = base_builder;
1991 builder.push_back(tag);
1992 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001993 // Strongbox may not support factory provisioned attestation key.
1994 if (SecLevel() == SecurityLevel::STRONGBOX) {
1995 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1996 }
Prashant Patil88ad1892022-03-15 16:31:02 +00001997 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
1998 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01001999 continue;
2000 }
2001 ASSERT_EQ(result, ErrorCode::OK);
2002 ASSERT_GT(key_blob.size(), 0U);
2003
2004 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2005 ASSERT_GT(cert_chain_.size(), 0);
2006 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2007
2008 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2009 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2010
2011 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2012 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2013 // attestation extension should contain them, so make sure the extra tag is added.
2014 hw_enforced.push_back(tag);
2015
2016 // Verifying the attestation record will check for the specific tag because
2017 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002018 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2019 hw_enforced, SecLevel(),
2020 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002021
2022 CheckedDeleteKey(&key_blob);
2023 }
2024}
2025
2026/*
David Drysdale565ccc72021-10-11 12:49:50 +01002027 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2028 *
2029 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2030 */
2031TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2032 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002033 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002034 auto challenge = "hello";
2035 auto subject = "cert subj 2";
2036 vector<uint8_t> subject_der(make_name_from_str(subject));
2037 uint64_t serial_int = 0x1010;
2038 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002039 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002040 AuthorizationSetBuilder()
2041 .Authorization(TAG_NO_AUTH_REQUIRED)
2042 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2043 .EcdsaSigningKey(EcCurve::P_256)
2044 .Digest(Digest::NONE)
2045 .AttestationChallenge(challenge)
2046 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2047 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2048 .AttestationApplicationId(app_id)
2049 .Authorization(TAG_CREATION_DATETIME, datetime)
2050 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002051 if (reset) {
2052 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2053 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002054 auto result = GenerateKey(builder);
2055 if (SecLevel() == SecurityLevel::STRONGBOX) {
2056 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2057 result = GenerateKeyWithSelfSignedAttestKey(
2058 AuthorizationSetBuilder()
2059 .EcdsaKey(EcCurve::P_256)
2060 .AttestKey()
2061 .SetDefaultValidity(), /* attest key params */
2062 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2063 }
2064 }
2065 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002066 ASSERT_GT(key_blob_.size(), 0U);
2067
2068 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2069 ASSERT_GT(cert_chain_.size(), 0);
2070 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2071
2072 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2073 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2074
2075 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002076 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2077 hw_enforced, SecLevel(),
2078 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002079 EXPECT_GT(unique_id->size(), 0);
2080 CheckedDeleteKey();
2081 };
2082
2083 // Generate unique ID
2084 auto app_id = "foo";
2085 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2086 vector<uint8_t> unique_id;
2087 get_unique_id(app_id, cert_date, &unique_id);
2088
2089 // Generating a new key with the same parameters should give the same unique ID.
2090 vector<uint8_t> unique_id2;
2091 get_unique_id(app_id, cert_date, &unique_id2);
2092 EXPECT_EQ(unique_id, unique_id2);
2093
2094 // Generating a new key with a slightly different date should give the same unique ID.
2095 uint64_t rounded_date = cert_date / 2592000000LLU;
2096 uint64_t min_date = rounded_date * 2592000000LLU;
2097 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2098
2099 vector<uint8_t> unique_id3;
2100 get_unique_id(app_id, min_date, &unique_id3);
2101 EXPECT_EQ(unique_id, unique_id3);
2102
2103 vector<uint8_t> unique_id4;
2104 get_unique_id(app_id, max_date, &unique_id4);
2105 EXPECT_EQ(unique_id, unique_id4);
2106
2107 // A different attestation application ID should yield a different unique ID.
2108 auto app_id2 = "different_foo";
2109 vector<uint8_t> unique_id5;
2110 get_unique_id(app_id2, cert_date, &unique_id5);
2111 EXPECT_NE(unique_id, unique_id5);
2112
2113 // A radically different date should yield a different unique ID.
2114 vector<uint8_t> unique_id6;
2115 get_unique_id(app_id, 1611621648000, &unique_id6);
2116 EXPECT_NE(unique_id, unique_id6);
2117
2118 vector<uint8_t> unique_id7;
2119 get_unique_id(app_id, max_date + 1, &unique_id7);
2120 EXPECT_NE(unique_id, unique_id7);
2121
2122 vector<uint8_t> unique_id8;
2123 get_unique_id(app_id, min_date - 1, &unique_id8);
2124 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002125
2126 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2127 vector<uint8_t> unique_id9;
2128 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2129 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002130}
2131
2132/*
David Drysdale37af4b32021-05-14 16:46:59 +01002133 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2134 *
2135 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2136 */
2137TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2138 auto challenge = "hello";
2139 auto attest_app_id = "foo";
2140 auto subject = "cert subj 2";
2141 vector<uint8_t> subject_der(make_name_from_str(subject));
2142 uint64_t serial_int = 0x1010;
2143 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2144
2145 // Earlier versions of the attestation extension schema included a slot:
2146 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2147 // This should never have been included, and should never be filled in.
2148 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2149 // to confirm that this field never makes it into the attestation extension.
2150 vector<uint8_t> key_blob;
2151 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002152 auto builder = AuthorizationSetBuilder()
2153 .Authorization(TAG_NO_AUTH_REQUIRED)
2154 .EcdsaSigningKey(EcCurve::P_256)
2155 .Digest(Digest::NONE)
2156 .AttestationChallenge(challenge)
2157 .AttestationApplicationId(attest_app_id)
2158 .Authorization(TAG_APPLICATION_ID, "client_id")
2159 .Authorization(TAG_APPLICATION_DATA, "appdata")
2160 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2161 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2162 .SetDefaultValidity();
2163
2164 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002165 // Strongbox may not support factory provisioned attestation key.
2166 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002167 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2168 result = GenerateKeyWithSelfSignedAttestKey(
2169 AuthorizationSetBuilder()
2170 .EcdsaKey(EcCurve::P_256)
2171 .AttestKey()
2172 .SetDefaultValidity(), /* attest key params */
2173 builder, &key_blob, &key_characteristics);
2174 }
subrahmanyaman05642492022-02-05 07:10:56 +00002175 }
David Drysdale37af4b32021-05-14 16:46:59 +01002176 ASSERT_EQ(result, ErrorCode::OK);
2177 ASSERT_GT(key_blob.size(), 0U);
2178
2179 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2180 ASSERT_GT(cert_chain_.size(), 0);
2181 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2182
2183 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2184 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002185 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2186 hw_enforced, SecLevel(),
2187 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002188
2189 // Check that the app id is not in the cert.
2190 string app_id = "clientid";
2191 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2192 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2193 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2194 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2195 cert_chain_[0].encodedCertificate.end());
2196
2197 CheckedDeleteKey(&key_blob);
2198}
2199
2200/*
Selene Huang4f64c222021-04-13 19:54:36 -07002201 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2202 *
2203 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2204 * the key will generate a self signed attestation.
2205 */
2206TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002207 auto subject = "cert subj 2";
2208 vector<uint8_t> subject_der(make_name_from_str(subject));
2209
2210 uint64_t serial_int = 0x123456FFF1234;
2211 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2212
David Drysdaledf09e542021-06-08 15:46:11 +01002213 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002214 vector<uint8_t> key_blob;
2215 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002216 ASSERT_EQ(ErrorCode::OK,
2217 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002218 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002219 .Digest(Digest::NONE)
2220 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2221 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2222 .SetDefaultValidity(),
2223 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002224 ASSERT_GT(key_blob.size(), 0U);
2225 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002226 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002227
2228 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2229
2230 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002231 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002232
2233 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2234 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002235 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002236
2237 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2238 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2239
2240 CheckedDeleteKey(&key_blob);
2241 }
2242}
2243
2244/*
2245 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2246 *
2247 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2248 * app id must also be provided or else it will fail.
2249 */
2250TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2251 auto challenge = "hello";
2252 vector<uint8_t> key_blob;
2253 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002254 auto builder = AuthorizationSetBuilder()
2255 .EcdsaSigningKey(EcCurve::P_256)
2256 .Digest(Digest::NONE)
2257 .AttestationChallenge(challenge)
2258 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002259
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002260 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002261 // Strongbox may not support factory provisioned attestation key.
2262 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002263 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2264 result = GenerateKeyWithSelfSignedAttestKey(
2265 AuthorizationSetBuilder()
2266 .EcdsaKey(EcCurve::P_256)
2267 .AttestKey()
2268 .SetDefaultValidity(), /* attest key params */
2269 builder, &key_blob, &key_characteristics);
2270 }
subrahmanyaman05642492022-02-05 07:10:56 +00002271 }
2272 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002273}
2274
2275/*
2276 * NewKeyGenerationTest.EcdsaIgnoreAppId
2277 *
2278 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2279 * any appid will be ignored, and keymint will generate a self sign certificate.
2280 */
2281TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2282 auto app_id = "foo";
2283
David Drysdaledf09e542021-06-08 15:46:11 +01002284 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002285 vector<uint8_t> key_blob;
2286 vector<KeyCharacteristics> key_characteristics;
2287 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002288 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002289 .Digest(Digest::NONE)
2290 .AttestationApplicationId(app_id)
2291 .SetDefaultValidity(),
2292 &key_blob, &key_characteristics));
2293
2294 ASSERT_GT(key_blob.size(), 0U);
2295 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002296 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002297
2298 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2299
2300 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002301 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002302
2303 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2304 ASSERT_EQ(cert_chain_.size(), 1);
2305
2306 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2307 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2308
2309 CheckedDeleteKey(&key_blob);
2310 }
2311}
2312
2313/*
2314 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2315 *
2316 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2317 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2318 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2319 * to specify how many following bytes will be used to encode the length.
2320 */
2321TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2322 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002323 std::vector<uint32_t> app_id_lengths{143, 258};
2324
2325 for (uint32_t length : app_id_lengths) {
2326 const string app_id(length, 'a');
2327 vector<uint8_t> key_blob;
2328 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002329 auto builder = AuthorizationSetBuilder()
2330 .Authorization(TAG_NO_AUTH_REQUIRED)
2331 .EcdsaSigningKey(EcCurve::P_256)
2332 .Digest(Digest::NONE)
2333 .AttestationChallenge(challenge)
2334 .AttestationApplicationId(app_id)
2335 .SetDefaultValidity();
2336
2337 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002338 // Strongbox may not support factory provisioned attestation key.
2339 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002340 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2341 result = GenerateKeyWithSelfSignedAttestKey(
2342 AuthorizationSetBuilder()
2343 .EcdsaKey(EcCurve::P_256)
2344 .AttestKey()
2345 .SetDefaultValidity(), /* attest key params */
2346 builder, &key_blob, &key_characteristics);
2347 }
subrahmanyaman05642492022-02-05 07:10:56 +00002348 }
2349 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002350 ASSERT_GT(key_blob.size(), 0U);
2351 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002352 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002353
2354 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2355
2356 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002357 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002358
2359 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2360 ASSERT_GT(cert_chain_.size(), 0);
2361
2362 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2363 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002364 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002365 sw_enforced, hw_enforced, SecLevel(),
2366 cert_chain_[0].encodedCertificate));
2367
2368 CheckedDeleteKey(&key_blob);
2369 }
2370}
2371
2372/*
Qi Wud22ec842020-11-26 13:27:53 +08002373 * NewKeyGenerationTest.LimitedUsageEcdsa
2374 *
2375 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2376 * resulting keys have correct characteristics.
2377 */
2378TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002379 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08002380 vector<uint8_t> key_blob;
2381 vector<KeyCharacteristics> key_characteristics;
2382 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002383 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002384 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002385 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2386 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002387 &key_blob, &key_characteristics));
2388
2389 ASSERT_GT(key_blob.size(), 0U);
2390 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002391 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002392
2393 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2394
2395 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002396 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002397
2398 // Check the usage count limit tag appears in the authorizations.
2399 AuthorizationSet auths;
2400 for (auto& entry : key_characteristics) {
2401 auths.push_back(AuthorizationSet(entry.authorizations));
2402 }
2403 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2404 << "key usage count limit " << 1U << " missing";
2405
2406 CheckedDeleteKey(&key_blob);
2407 }
2408}
2409
2410/*
Selene Huang31ab4042020-04-29 04:22:39 -07002411 * NewKeyGenerationTest.EcdsaDefaultSize
2412 *
David Drysdaledf09e542021-06-08 15:46:11 +01002413 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002414 * UNSUPPORTED_KEY_SIZE.
2415 */
2416TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2417 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2418 GenerateKey(AuthorizationSetBuilder()
2419 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2420 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002421 .Digest(Digest::NONE)
2422 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002423}
2424
2425/*
David Drysdale42fe1892021-10-14 14:43:46 +01002426 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002427 *
David Drysdale42fe1892021-10-14 14:43:46 +01002428 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002429 * UNSUPPORTED_KEY_SIZE.
2430 */
David Drysdale42fe1892021-10-14 14:43:46 +01002431TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002432 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07002433 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002434 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002435 auto result = GenerateKey(AuthorizationSetBuilder()
2436 .EcdsaSigningKey(curve)
2437 .Digest(Digest::NONE)
2438 .SetDefaultValidity(),
2439 &key_blob, &key_characteristics);
2440 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2441 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002442 }
2443
David Drysdaledf09e542021-06-08 15:46:11 +01002444 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2445 GenerateKey(AuthorizationSetBuilder()
2446 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2447 .Authorization(TAG_KEY_SIZE, 190)
2448 .SigningKey()
2449 .Digest(Digest::NONE)
2450 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002451}
2452
2453/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002454 * NewKeyGenerationTest.EcdsaMissingCurve
2455 *
2456 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
2457 */
2458TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2459 if (AidlVersion() < 2) {
2460 /*
2461 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2462 * However, this was not checked at the time so we can only be strict about checking this
2463 * for implementations of KeyMint version 2 and above.
2464 */
2465 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
2466 }
2467 /* If EC_CURVE not provided, generateKey
2468 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2469 */
2470 auto result = GenerateKey(
2471 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2472 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2473 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2474}
2475
2476/*
Selene Huang31ab4042020-04-29 04:22:39 -07002477 * NewKeyGenerationTest.EcdsaMismatchKeySize
2478 *
2479 * Verifies that specifying mismatched key size and curve for EC key generation returns
2480 * INVALID_ARGUMENT.
2481 */
2482TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002483 if (SecLevel() == SecurityLevel::STRONGBOX) {
2484 GTEST_SKIP() << "Test not applicable to StrongBox device";
2485 }
Selene Huang31ab4042020-04-29 04:22:39 -07002486
David Drysdaledf09e542021-06-08 15:46:11 +01002487 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002488 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002489 .Authorization(TAG_KEY_SIZE, 224)
2490 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002491 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002492 .Digest(Digest::NONE)
2493 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002494 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002495}
2496
2497/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002498 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002499 *
2500 * Verifies that keymint does not support any curve designated as unsupported.
2501 */
2502TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2503 Digest digest;
2504 if (SecLevel() == SecurityLevel::STRONGBOX) {
2505 digest = Digest::SHA_2_256;
2506 } else {
2507 digest = Digest::SHA_2_512;
2508 }
2509 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08002510 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2511 .EcdsaSigningKey(curve)
2512 .Digest(digest)
2513 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002514 << "Failed to generate key on curve: " << curve;
2515 CheckedDeleteKey();
2516 }
2517}
2518
2519/*
2520 * NewKeyGenerationTest.Hmac
2521 *
2522 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2523 * characteristics.
2524 */
2525TEST_P(NewKeyGenerationTest, Hmac) {
2526 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2527 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002528 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002529 constexpr size_t key_size = 128;
2530 ASSERT_EQ(ErrorCode::OK,
2531 GenerateKey(
2532 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2533 TAG_MIN_MAC_LENGTH, 128),
2534 &key_blob, &key_characteristics));
2535
2536 ASSERT_GT(key_blob.size(), 0U);
2537 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002538 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002539
Shawn Willden7f424372021-01-10 18:06:50 -07002540 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2541 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2542 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2543 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002544
2545 CheckedDeleteKey(&key_blob);
2546 }
2547}
2548
2549/*
Selene Huang4f64c222021-04-13 19:54:36 -07002550 * NewKeyGenerationTest.HmacNoAttestation
2551 *
2552 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2553 * and app id are provided.
2554 */
2555TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2556 auto challenge = "hello";
2557 auto app_id = "foo";
2558
2559 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2560 vector<uint8_t> key_blob;
2561 vector<KeyCharacteristics> key_characteristics;
2562 constexpr size_t key_size = 128;
2563 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2564 .HmacKey(key_size)
2565 .Digest(digest)
2566 .AttestationChallenge(challenge)
2567 .AttestationApplicationId(app_id)
2568 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2569 &key_blob, &key_characteristics));
2570
2571 ASSERT_GT(key_blob.size(), 0U);
2572 ASSERT_EQ(cert_chain_.size(), 0);
2573 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002574 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002575
2576 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2577 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2578 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2579 << "Key size " << key_size << "missing";
2580
2581 CheckedDeleteKey(&key_blob);
2582 }
2583}
2584
2585/*
Qi Wud22ec842020-11-26 13:27:53 +08002586 * NewKeyGenerationTest.LimitedUsageHmac
2587 *
2588 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2589 * resulting keys have correct characteristics.
2590 */
2591TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2592 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2593 vector<uint8_t> key_blob;
2594 vector<KeyCharacteristics> key_characteristics;
2595 constexpr size_t key_size = 128;
2596 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2597 .HmacKey(key_size)
2598 .Digest(digest)
2599 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2600 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2601 &key_blob, &key_characteristics));
2602
2603 ASSERT_GT(key_blob.size(), 0U);
2604 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002605 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002606
2607 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2608 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2609 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2610 << "Key size " << key_size << "missing";
2611
2612 // Check the usage count limit tag appears in the authorizations.
2613 AuthorizationSet auths;
2614 for (auto& entry : key_characteristics) {
2615 auths.push_back(AuthorizationSet(entry.authorizations));
2616 }
2617 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2618 << "key usage count limit " << 1U << " missing";
2619
2620 CheckedDeleteKey(&key_blob);
2621 }
2622}
2623
2624/*
Selene Huang31ab4042020-04-29 04:22:39 -07002625 * NewKeyGenerationTest.HmacCheckKeySizes
2626 *
2627 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2628 */
2629TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2630 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2631 if (key_size < 64 || key_size % 8 != 0) {
2632 // To keep this test from being very slow, we only test a random fraction of
2633 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2634 // them, we expect to run ~40 of them in each run.
2635 if (key_size % 8 == 0 || random() % 10 == 0) {
2636 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2637 GenerateKey(AuthorizationSetBuilder()
2638 .HmacKey(key_size)
2639 .Digest(Digest::SHA_2_256)
2640 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2641 << "HMAC key size " << key_size << " invalid";
2642 }
2643 } else {
2644 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2645 .HmacKey(key_size)
2646 .Digest(Digest::SHA_2_256)
2647 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2648 << "Failed to generate HMAC key of size " << key_size;
2649 CheckedDeleteKey();
2650 }
2651 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002652 if (SecLevel() == SecurityLevel::STRONGBOX) {
2653 // STRONGBOX devices must not support keys larger than 512 bits.
2654 size_t key_size = 520;
2655 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2656 GenerateKey(AuthorizationSetBuilder()
2657 .HmacKey(key_size)
2658 .Digest(Digest::SHA_2_256)
2659 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2660 << "HMAC key size " << key_size << " unexpectedly valid";
2661 }
Selene Huang31ab4042020-04-29 04:22:39 -07002662}
2663
2664/*
2665 * NewKeyGenerationTest.HmacCheckMinMacLengths
2666 *
2667 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2668 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2669 * specific MAC length that failed, so reproducing a failed run will be easy.
2670 */
2671TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2672 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2673 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2674 // To keep this test from being very long, we only test a random fraction of
2675 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2676 // we expect to run ~17 of them in each run.
2677 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2678 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2679 GenerateKey(AuthorizationSetBuilder()
2680 .HmacKey(128)
2681 .Digest(Digest::SHA_2_256)
2682 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2683 << "HMAC min mac length " << min_mac_length << " invalid.";
2684 }
2685 } else {
2686 EXPECT_EQ(ErrorCode::OK,
2687 GenerateKey(AuthorizationSetBuilder()
2688 .HmacKey(128)
2689 .Digest(Digest::SHA_2_256)
2690 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2691 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2692 CheckedDeleteKey();
2693 }
2694 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002695
2696 // Minimum MAC length must be no more than 512 bits.
2697 size_t min_mac_length = 520;
2698 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2699 GenerateKey(AuthorizationSetBuilder()
2700 .HmacKey(128)
2701 .Digest(Digest::SHA_2_256)
2702 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2703 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002704}
2705
2706/*
2707 * NewKeyGenerationTest.HmacMultipleDigests
2708 *
2709 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2710 */
2711TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002712 if (SecLevel() == SecurityLevel::STRONGBOX) {
2713 GTEST_SKIP() << "Test not applicable to StrongBox device";
2714 }
Selene Huang31ab4042020-04-29 04:22:39 -07002715
2716 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2717 GenerateKey(AuthorizationSetBuilder()
2718 .HmacKey(128)
2719 .Digest(Digest::SHA1)
2720 .Digest(Digest::SHA_2_256)
2721 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2722}
2723
2724/*
2725 * NewKeyGenerationTest.HmacDigestNone
2726 *
2727 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2728 */
2729TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2730 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2731 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2732 128)));
2733
2734 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2735 GenerateKey(AuthorizationSetBuilder()
2736 .HmacKey(128)
2737 .Digest(Digest::NONE)
2738 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2739}
2740
Selene Huang4f64c222021-04-13 19:54:36 -07002741/*
2742 * NewKeyGenerationTest.AesNoAttestation
2743 *
2744 * Verifies that attestation parameters to AES keys are ignored and generateKey
2745 * will succeed.
2746 */
2747TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2748 auto challenge = "hello";
2749 auto app_id = "foo";
2750
2751 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2752 .Authorization(TAG_NO_AUTH_REQUIRED)
2753 .AesEncryptionKey(128)
2754 .EcbMode()
2755 .Padding(PaddingMode::PKCS7)
2756 .AttestationChallenge(challenge)
2757 .AttestationApplicationId(app_id)));
2758
2759 ASSERT_EQ(cert_chain_.size(), 0);
2760}
2761
2762/*
2763 * NewKeyGenerationTest.TripleDesNoAttestation
2764 *
2765 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2766 * will be successful. No attestation should be generated.
2767 */
2768TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2769 auto challenge = "hello";
2770 auto app_id = "foo";
2771
2772 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2773 .TripleDesEncryptionKey(168)
2774 .BlockMode(BlockMode::ECB)
2775 .Authorization(TAG_NO_AUTH_REQUIRED)
2776 .Padding(PaddingMode::NONE)
2777 .AttestationChallenge(challenge)
2778 .AttestationApplicationId(app_id)));
2779 ASSERT_EQ(cert_chain_.size(), 0);
2780}
2781
Selene Huang31ab4042020-04-29 04:22:39 -07002782INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2783
2784typedef KeyMintAidlTestBase SigningOperationsTest;
2785
2786/*
2787 * SigningOperationsTest.RsaSuccess
2788 *
2789 * Verifies that raw RSA signature operations succeed.
2790 */
2791TEST_P(SigningOperationsTest, RsaSuccess) {
2792 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2793 .RsaSigningKey(2048, 65537)
2794 .Digest(Digest::NONE)
2795 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002796 .Authorization(TAG_NO_AUTH_REQUIRED)
2797 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002798 string message = "12345678901234567890123456789012";
2799 string signature = SignMessage(
2800 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002801 LocalVerifyMessage(message, signature,
2802 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2803}
2804
2805/*
2806 * SigningOperationsTest.RsaAllPaddingsAndDigests
2807 *
2808 * Verifies RSA signature/verification for all padding modes and digests.
2809 */
2810TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2811 auto authorizations = AuthorizationSetBuilder()
2812 .Authorization(TAG_NO_AUTH_REQUIRED)
2813 .RsaSigningKey(2048, 65537)
2814 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2815 .Padding(PaddingMode::NONE)
2816 .Padding(PaddingMode::RSA_PSS)
2817 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2818 .SetDefaultValidity();
2819
2820 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2821
2822 string message(128, 'a');
2823 string corrupt_message(message);
2824 ++corrupt_message[corrupt_message.size() / 2];
2825
2826 for (auto padding :
2827 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2828 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2829 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2830 // Digesting only makes sense with padding.
2831 continue;
2832 }
2833
2834 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2835 // PSS requires digesting.
2836 continue;
2837 }
2838
2839 string signature =
2840 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2841 LocalVerifyMessage(message, signature,
2842 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2843 }
2844 }
Selene Huang31ab4042020-04-29 04:22:39 -07002845}
2846
2847/*
2848 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2849 *
Shawn Willden7f424372021-01-10 18:06:50 -07002850 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002851 */
2852TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2853 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2854 .Authorization(TAG_NO_AUTH_REQUIRED)
2855 .RsaSigningKey(2048, 65537)
2856 .Digest(Digest::NONE)
2857 .Padding(PaddingMode::NONE)
2858 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002859 .Authorization(TAG_APPLICATION_DATA, "appdata")
2860 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002861
2862 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2863
Selene Huang31ab4042020-04-29 04:22:39 -07002864 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2865 Begin(KeyPurpose::SIGN,
2866 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2867 AbortIfNeeded();
2868 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2869 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2870 .Digest(Digest::NONE)
2871 .Padding(PaddingMode::NONE)
2872 .Authorization(TAG_APPLICATION_ID, "clientid")));
2873 AbortIfNeeded();
2874 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2875 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2876 .Digest(Digest::NONE)
2877 .Padding(PaddingMode::NONE)
2878 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2879 AbortIfNeeded();
2880 EXPECT_EQ(ErrorCode::OK,
2881 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2882 .Digest(Digest::NONE)
2883 .Padding(PaddingMode::NONE)
2884 .Authorization(TAG_APPLICATION_DATA, "appdata")
2885 .Authorization(TAG_APPLICATION_ID, "clientid")));
2886 AbortIfNeeded();
2887}
2888
2889/*
2890 * SigningOperationsTest.RsaPssSha256Success
2891 *
2892 * Verifies that RSA-PSS signature operations succeed.
2893 */
2894TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2895 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2896 .RsaSigningKey(2048, 65537)
2897 .Digest(Digest::SHA_2_256)
2898 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002899 .Authorization(TAG_NO_AUTH_REQUIRED)
2900 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002901 // Use large message, which won't work without digesting.
2902 string message(1024, 'a');
2903 string signature = SignMessage(
2904 message,
2905 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2906}
2907
2908/*
2909 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2910 *
2911 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2912 * supports only unpadded operations.
2913 */
2914TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2915 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2916 .RsaSigningKey(2048, 65537)
2917 .Digest(Digest::NONE)
2918 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002919 .Padding(PaddingMode::NONE)
2920 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002921 string message = "12345678901234567890123456789012";
2922 string signature;
2923
2924 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2925 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2926 .Digest(Digest::NONE)
2927 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2928}
2929
2930/*
2931 * SigningOperationsTest.NoUserConfirmation
2932 *
2933 * Verifies that keymint rejects signing operations for keys with
2934 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2935 * presented.
2936 */
2937TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002938 if (SecLevel() == SecurityLevel::STRONGBOX) {
2939 GTEST_SKIP() << "Test not applicable to StrongBox device";
2940 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002941 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2942 .RsaSigningKey(1024, 65537)
2943 .Digest(Digest::NONE)
2944 .Padding(PaddingMode::NONE)
2945 .Authorization(TAG_NO_AUTH_REQUIRED)
2946 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2947 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002948
2949 const string message = "12345678901234567890123456789012";
2950 EXPECT_EQ(ErrorCode::OK,
2951 Begin(KeyPurpose::SIGN,
2952 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2953 string signature;
2954 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2955}
2956
2957/*
2958 * SigningOperationsTest.RsaPkcs1Sha256Success
2959 *
2960 * Verifies that digested RSA-PKCS1 signature operations succeed.
2961 */
2962TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2963 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2964 .RsaSigningKey(2048, 65537)
2965 .Digest(Digest::SHA_2_256)
2966 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002967 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2968 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002969 string message(1024, 'a');
2970 string signature = SignMessage(message, AuthorizationSetBuilder()
2971 .Digest(Digest::SHA_2_256)
2972 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2973}
2974
2975/*
2976 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2977 *
2978 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2979 */
2980TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2981 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2982 .RsaSigningKey(2048, 65537)
2983 .Digest(Digest::NONE)
2984 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002985 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2986 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002987 string message(53, 'a');
2988 string signature = SignMessage(message, AuthorizationSetBuilder()
2989 .Digest(Digest::NONE)
2990 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2991}
2992
2993/*
2994 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2995 *
2996 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2997 * given a too-long message.
2998 */
2999TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3000 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3001 .RsaSigningKey(2048, 65537)
3002 .Digest(Digest::NONE)
3003 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003004 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3005 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003006 string message(257, 'a');
3007
3008 EXPECT_EQ(ErrorCode::OK,
3009 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3010 .Digest(Digest::NONE)
3011 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3012 string signature;
3013 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3014}
3015
3016/*
3017 * SigningOperationsTest.RsaPssSha512TooSmallKey
3018 *
3019 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3020 * used with a key that is too small for the message.
3021 *
3022 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3023 * keymint specification requires that salt_size == digest_size, so the message will be
3024 * digest_size * 2 +
3025 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3026 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3027 * for a 1024-bit key.
3028 */
3029TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003030 if (SecLevel() == SecurityLevel::STRONGBOX) {
3031 GTEST_SKIP() << "Test not applicable to StrongBox device";
3032 }
Selene Huang31ab4042020-04-29 04:22:39 -07003033 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3034 .RsaSigningKey(1024, 65537)
3035 .Digest(Digest::SHA_2_512)
3036 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003037 .Padding(PaddingMode::RSA_PSS)
3038 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003039 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3040 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3041 .Digest(Digest::SHA_2_512)
3042 .Padding(PaddingMode::RSA_PSS)));
3043}
3044
3045/*
3046 * SigningOperationsTest.RsaNoPaddingTooLong
3047 *
3048 * Verifies that raw RSA signature operations fail with the correct error code when
3049 * given a too-long message.
3050 */
3051TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3052 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3053 .RsaSigningKey(2048, 65537)
3054 .Digest(Digest::NONE)
3055 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003056 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3057 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003058 // One byte too long
3059 string message(2048 / 8 + 1, 'a');
3060 ASSERT_EQ(ErrorCode::OK,
3061 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3062 .Digest(Digest::NONE)
3063 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3064 string result;
3065 ErrorCode finish_error_code = Finish(message, &result);
3066 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3067 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3068
3069 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3070 message = string(128 * 1024, 'a');
3071 ASSERT_EQ(ErrorCode::OK,
3072 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3073 .Digest(Digest::NONE)
3074 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3075 finish_error_code = Finish(message, &result);
3076 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3077 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3078}
3079
3080/*
3081 * SigningOperationsTest.RsaAbort
3082 *
3083 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3084 * test, but the behavior should be algorithm and purpose-independent.
3085 */
3086TEST_P(SigningOperationsTest, RsaAbort) {
3087 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3088 .RsaSigningKey(2048, 65537)
3089 .Digest(Digest::NONE)
3090 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003091 .Padding(PaddingMode::NONE)
3092 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003093
3094 ASSERT_EQ(ErrorCode::OK,
3095 Begin(KeyPurpose::SIGN,
3096 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3097 EXPECT_EQ(ErrorCode::OK, Abort());
3098
3099 // Another abort should fail
3100 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3101
3102 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003103 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003104}
3105
3106/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003107 * SigningOperationsTest.RsaNonUniqueParams
3108 *
3109 * Verifies that an operation with multiple padding modes is rejected.
3110 */
3111TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3112 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3113 .RsaSigningKey(2048, 65537)
3114 .Digest(Digest::NONE)
3115 .Digest(Digest::SHA1)
3116 .Authorization(TAG_NO_AUTH_REQUIRED)
3117 .Padding(PaddingMode::NONE)
3118 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3119 .SetDefaultValidity()));
3120
3121 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3122 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3123 .Digest(Digest::NONE)
3124 .Padding(PaddingMode::NONE)
3125 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3126
Tommy Chiuc93c4392021-05-11 18:36:50 +08003127 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3128 .Digest(Digest::NONE)
3129 .Digest(Digest::SHA1)
3130 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3131 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003132
3133 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3134 Begin(KeyPurpose::SIGN,
3135 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3136}
3137
3138/*
Selene Huang31ab4042020-04-29 04:22:39 -07003139 * SigningOperationsTest.RsaUnsupportedPadding
3140 *
3141 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3142 * with a padding mode inappropriate for RSA.
3143 */
3144TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3145 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3146 .RsaSigningKey(2048, 65537)
3147 .Authorization(TAG_NO_AUTH_REQUIRED)
3148 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003149 .Padding(PaddingMode::PKCS7)
3150 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003151 ASSERT_EQ(
3152 ErrorCode::UNSUPPORTED_PADDING_MODE,
3153 Begin(KeyPurpose::SIGN,
3154 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003155 CheckedDeleteKey();
3156
3157 ASSERT_EQ(ErrorCode::OK,
3158 GenerateKey(
3159 AuthorizationSetBuilder()
3160 .RsaSigningKey(2048, 65537)
3161 .Authorization(TAG_NO_AUTH_REQUIRED)
3162 .Digest(Digest::SHA_2_256 /* supported digest */)
3163 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3164 .SetDefaultValidity()));
3165 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3166 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3167 .Digest(Digest::SHA_2_256)
3168 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003169}
3170
3171/*
3172 * SigningOperationsTest.RsaPssNoDigest
3173 *
3174 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3175 */
3176TEST_P(SigningOperationsTest, RsaNoDigest) {
3177 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3178 .RsaSigningKey(2048, 65537)
3179 .Authorization(TAG_NO_AUTH_REQUIRED)
3180 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003181 .Padding(PaddingMode::RSA_PSS)
3182 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003183 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3184 Begin(KeyPurpose::SIGN,
3185 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3186
3187 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3188 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3189}
3190
3191/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003192 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003193 *
3194 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3195 * supported in some cases (as validated in other tests), but a mode must be specified.
3196 */
3197TEST_P(SigningOperationsTest, RsaNoPadding) {
3198 // Padding must be specified
3199 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3200 .RsaKey(2048, 65537)
3201 .Authorization(TAG_NO_AUTH_REQUIRED)
3202 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003203 .Digest(Digest::NONE)
3204 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003205 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3206 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3207}
3208
3209/*
3210 * SigningOperationsTest.RsaShortMessage
3211 *
3212 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3213 */
3214TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3215 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3216 .Authorization(TAG_NO_AUTH_REQUIRED)
3217 .RsaSigningKey(2048, 65537)
3218 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003219 .Padding(PaddingMode::NONE)
3220 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003221
3222 // Barely shorter
3223 string message(2048 / 8 - 1, 'a');
3224 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3225
3226 // Much shorter
3227 message = "a";
3228 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3229}
3230
3231/*
3232 * SigningOperationsTest.RsaSignWithEncryptionKey
3233 *
3234 * Verifies that RSA encryption keys cannot be used to sign.
3235 */
3236TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3237 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3238 .Authorization(TAG_NO_AUTH_REQUIRED)
3239 .RsaEncryptionKey(2048, 65537)
3240 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003241 .Padding(PaddingMode::NONE)
3242 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003243 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3244 Begin(KeyPurpose::SIGN,
3245 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3246}
3247
3248/*
3249 * SigningOperationsTest.RsaSignTooLargeMessage
3250 *
3251 * Verifies that attempting a raw signature of a message which is the same length as the key,
3252 * but numerically larger than the public modulus, fails with the correct error.
3253 */
3254TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3255 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3256 .Authorization(TAG_NO_AUTH_REQUIRED)
3257 .RsaSigningKey(2048, 65537)
3258 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003259 .Padding(PaddingMode::NONE)
3260 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003261
3262 // Largest possible message will always be larger than the public modulus.
3263 string message(2048 / 8, static_cast<char>(0xff));
3264 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3265 .Authorization(TAG_NO_AUTH_REQUIRED)
3266 .Digest(Digest::NONE)
3267 .Padding(PaddingMode::NONE)));
3268 string signature;
3269 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3270}
3271
3272/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003273 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3274 *
David Drysdale42fe1892021-10-14 14:43:46 +01003275 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003276 */
3277TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003278
3279 string message = "1234567890";
3280 string corrupt_message = "2234567890";
3281 for (auto curve : ValidCurves()) {
3282 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003283 // Ed25519 only allows Digest::NONE.
3284 auto digests = (curve == EcCurve::CURVE_25519)
3285 ? std::vector<Digest>(1, Digest::NONE)
3286 : ValidDigests(true /* withNone */, false /* withMD5 */);
3287
David Drysdaledf8f52e2021-05-06 08:10:58 +01003288 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3289 .Authorization(TAG_NO_AUTH_REQUIRED)
3290 .EcdsaSigningKey(curve)
3291 .Digest(digests)
3292 .SetDefaultValidity());
3293 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3294 if (error != ErrorCode::OK) {
3295 continue;
3296 }
3297
3298 for (auto digest : digests) {
3299 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3300 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3301 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3302 }
3303
3304 auto rc = DeleteKey();
3305 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3306 }
3307}
3308
3309/*
Selene Huang31ab4042020-04-29 04:22:39 -07003310 * SigningOperationsTest.EcdsaAllCurves
3311 *
David Drysdale42fe1892021-10-14 14:43:46 +01003312 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003313 */
3314TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3315 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003316 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3317 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003318 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3319 .Authorization(TAG_NO_AUTH_REQUIRED)
3320 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003321 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003322 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003323 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3324 if (error != ErrorCode::OK) continue;
3325
3326 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003327 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003328 CheckedDeleteKey();
3329 }
3330}
3331
3332/*
David Drysdale42fe1892021-10-14 14:43:46 +01003333 * SigningOperationsTest.EcdsaCurve25519
3334 *
3335 * Verifies that ECDSA operations succeed with curve25519.
3336 */
3337TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3338 if (!Curve25519Supported()) {
3339 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3340 }
3341
3342 EcCurve curve = EcCurve::CURVE_25519;
3343 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3344 .Authorization(TAG_NO_AUTH_REQUIRED)
3345 .EcdsaSigningKey(curve)
3346 .Digest(Digest::NONE)
3347 .SetDefaultValidity());
3348 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3349
3350 string message(1024, 'a');
3351 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3352 CheckedDeleteKey();
3353}
3354
3355/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003356 * SigningOperationsTest.EcdsaCurve25519MaxSize
3357 *
3358 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3359 */
3360TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3361 if (!Curve25519Supported()) {
3362 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3363 }
3364
3365 EcCurve curve = EcCurve::CURVE_25519;
3366 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3367 .Authorization(TAG_NO_AUTH_REQUIRED)
3368 .EcdsaSigningKey(curve)
3369 .Digest(Digest::NONE)
3370 .SetDefaultValidity());
3371 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3372
3373 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3374
3375 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3376 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3377 string message(msg_size, 'a');
3378
3379 // Attempt to sign via Begin+Finish.
3380 AuthorizationSet out_params;
3381 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3382 EXPECT_TRUE(out_params.empty());
3383 string signature;
3384 auto result = Finish(message, &signature);
3385 EXPECT_EQ(result, ErrorCode::OK);
3386 LocalVerifyMessage(message, signature, params);
3387
3388 // Attempt to sign via Begin+Update+Finish
3389 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3390 EXPECT_TRUE(out_params.empty());
3391 string output;
3392 result = Update(message, &output);
3393 EXPECT_EQ(result, ErrorCode::OK);
3394 EXPECT_EQ(output.size(), 0);
3395 string signature2;
3396 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3397 LocalVerifyMessage(message, signature2, params);
3398 }
3399
3400 CheckedDeleteKey();
3401}
3402
3403/*
3404 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3405 *
3406 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3407 */
3408TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3409 if (!Curve25519Supported()) {
3410 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3411 }
3412
3413 EcCurve curve = EcCurve::CURVE_25519;
3414 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3415 .Authorization(TAG_NO_AUTH_REQUIRED)
3416 .EcdsaSigningKey(curve)
3417 .Digest(Digest::NONE)
3418 .SetDefaultValidity());
3419 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3420
3421 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3422
3423 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3424 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3425 string message(msg_size, 'a');
3426
3427 // Attempt to sign via Begin+Finish.
3428 AuthorizationSet out_params;
3429 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3430 EXPECT_TRUE(out_params.empty());
3431 string signature;
3432 auto result = Finish(message, &signature);
3433 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3434
3435 // Attempt to sign via Begin+Update (but never get to Finish)
3436 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3437 EXPECT_TRUE(out_params.empty());
3438 string output;
3439 result = Update(message, &output);
3440 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3441 }
3442
3443 CheckedDeleteKey();
3444}
3445
3446/*
Selene Huang31ab4042020-04-29 04:22:39 -07003447 * SigningOperationsTest.EcdsaNoDigestHugeData
3448 *
3449 * Verifies that ECDSA operations support very large messages, even without digesting. This
3450 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3451 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3452 * the framework.
3453 */
3454TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3455 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3456 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003457 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003458 .Digest(Digest::NONE)
3459 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003460 string message(1 * 1024, 'a');
3461 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3462}
3463
3464/*
3465 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3466 *
3467 * Verifies that using an EC key requires the correct app ID/data.
3468 */
3469TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3470 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3471 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003472 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003473 .Digest(Digest::NONE)
3474 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003475 .Authorization(TAG_APPLICATION_DATA, "appdata")
3476 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003477
3478 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3479
Selene Huang31ab4042020-04-29 04:22:39 -07003480 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3481 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3482 AbortIfNeeded();
3483 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3484 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3485 .Digest(Digest::NONE)
3486 .Authorization(TAG_APPLICATION_ID, "clientid")));
3487 AbortIfNeeded();
3488 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3489 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3490 .Digest(Digest::NONE)
3491 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3492 AbortIfNeeded();
3493 EXPECT_EQ(ErrorCode::OK,
3494 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3495 .Digest(Digest::NONE)
3496 .Authorization(TAG_APPLICATION_DATA, "appdata")
3497 .Authorization(TAG_APPLICATION_ID, "clientid")));
3498 AbortIfNeeded();
3499}
3500
3501/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003502 * SigningOperationsTest.EcdsaIncompatibleDigest
3503 *
3504 * Verifies that using an EC key requires compatible digest.
3505 */
3506TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3507 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3508 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003509 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003510 .Digest(Digest::NONE)
3511 .Digest(Digest::SHA1)
3512 .SetDefaultValidity()));
3513 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3514 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3515 AbortIfNeeded();
3516}
3517
3518/*
Selene Huang31ab4042020-04-29 04:22:39 -07003519 * SigningOperationsTest.AesEcbSign
3520 *
3521 * Verifies that attempts to use AES keys to sign fail in the correct way.
3522 */
3523TEST_P(SigningOperationsTest, AesEcbSign) {
3524 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3525 .Authorization(TAG_NO_AUTH_REQUIRED)
3526 .SigningKey()
3527 .AesEncryptionKey(128)
3528 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3529
3530 AuthorizationSet out_params;
3531 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3532 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3533 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3534 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3535}
3536
3537/*
3538 * SigningOperationsTest.HmacAllDigests
3539 *
3540 * Verifies that HMAC works with all digests.
3541 */
3542TEST_P(SigningOperationsTest, HmacAllDigests) {
3543 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
3544 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3545 .Authorization(TAG_NO_AUTH_REQUIRED)
3546 .HmacKey(128)
3547 .Digest(digest)
3548 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3549 << "Failed to create HMAC key with digest " << digest;
3550 string message = "12345678901234567890123456789012";
3551 string signature = MacMessage(message, digest, 160);
3552 EXPECT_EQ(160U / 8U, signature.size())
3553 << "Failed to sign with HMAC key with digest " << digest;
3554 CheckedDeleteKey();
3555 }
3556}
3557
3558/*
3559 * SigningOperationsTest.HmacSha256TooLargeMacLength
3560 *
3561 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3562 * digest size.
3563 */
3564TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3565 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3566 .Authorization(TAG_NO_AUTH_REQUIRED)
3567 .HmacKey(128)
3568 .Digest(Digest::SHA_2_256)
3569 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3570 AuthorizationSet output_params;
3571 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3572 AuthorizationSetBuilder()
3573 .Digest(Digest::SHA_2_256)
3574 .Authorization(TAG_MAC_LENGTH, 264),
3575 &output_params));
3576}
3577
3578/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003579 * SigningOperationsTest.HmacSha256InvalidMacLength
3580 *
3581 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3582 * not a multiple of 8.
3583 */
3584TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3585 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3586 .Authorization(TAG_NO_AUTH_REQUIRED)
3587 .HmacKey(128)
3588 .Digest(Digest::SHA_2_256)
3589 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3590 AuthorizationSet output_params;
3591 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3592 AuthorizationSetBuilder()
3593 .Digest(Digest::SHA_2_256)
3594 .Authorization(TAG_MAC_LENGTH, 161),
3595 &output_params));
3596}
3597
3598/*
Selene Huang31ab4042020-04-29 04:22:39 -07003599 * SigningOperationsTest.HmacSha256TooSmallMacLength
3600 *
3601 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3602 * specified minimum MAC length.
3603 */
3604TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3605 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3606 .Authorization(TAG_NO_AUTH_REQUIRED)
3607 .HmacKey(128)
3608 .Digest(Digest::SHA_2_256)
3609 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3610 AuthorizationSet output_params;
3611 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3612 AuthorizationSetBuilder()
3613 .Digest(Digest::SHA_2_256)
3614 .Authorization(TAG_MAC_LENGTH, 120),
3615 &output_params));
3616}
3617
3618/*
3619 * SigningOperationsTest.HmacRfc4231TestCase3
3620 *
3621 * Validates against the test vectors from RFC 4231 test case 3.
3622 */
3623TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3624 string key(20, 0xaa);
3625 string message(50, 0xdd);
3626 uint8_t sha_224_expected[] = {
3627 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3628 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3629 };
3630 uint8_t sha_256_expected[] = {
3631 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3632 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3633 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3634 };
3635 uint8_t sha_384_expected[] = {
3636 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3637 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3638 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3639 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3640 };
3641 uint8_t sha_512_expected[] = {
3642 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3643 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3644 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3645 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3646 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3647 };
3648
3649 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3650 if (SecLevel() != SecurityLevel::STRONGBOX) {
3651 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3652 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3653 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3654 }
3655}
3656
3657/*
3658 * SigningOperationsTest.HmacRfc4231TestCase5
3659 *
3660 * Validates against the test vectors from RFC 4231 test case 5.
3661 */
3662TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3663 string key(20, 0x0c);
3664 string message = "Test With Truncation";
3665
3666 uint8_t sha_224_expected[] = {
3667 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3668 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3669 };
3670 uint8_t sha_256_expected[] = {
3671 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3672 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3673 };
3674 uint8_t sha_384_expected[] = {
3675 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3676 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3677 };
3678 uint8_t sha_512_expected[] = {
3679 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3680 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3681 };
3682
3683 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3684 if (SecLevel() != SecurityLevel::STRONGBOX) {
3685 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3686 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3687 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3688 }
3689}
3690
3691INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3692
3693typedef KeyMintAidlTestBase VerificationOperationsTest;
3694
3695/*
Selene Huang31ab4042020-04-29 04:22:39 -07003696 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3697 *
3698 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3699 */
3700TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3701 string key_material = "HelloThisIsAKey";
3702
3703 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003704 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003705 EXPECT_EQ(ErrorCode::OK,
3706 ImportKey(AuthorizationSetBuilder()
3707 .Authorization(TAG_NO_AUTH_REQUIRED)
3708 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3709 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3710 .Digest(Digest::SHA_2_256)
3711 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3712 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3713 EXPECT_EQ(ErrorCode::OK,
3714 ImportKey(AuthorizationSetBuilder()
3715 .Authorization(TAG_NO_AUTH_REQUIRED)
3716 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3717 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3718 .Digest(Digest::SHA_2_256)
3719 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3720 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3721
3722 string message = "This is a message.";
3723 string signature = SignMessage(
3724 signing_key, message,
3725 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3726
3727 // Signing key should not work.
3728 AuthorizationSet out_params;
3729 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3730 Begin(KeyPurpose::VERIFY, signing_key,
3731 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3732
3733 // Verification key should work.
3734 VerifyMessage(verification_key, message, signature,
3735 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3736
3737 CheckedDeleteKey(&signing_key);
3738 CheckedDeleteKey(&verification_key);
3739}
3740
Prashant Patildec9fdc2021-12-08 15:25:47 +00003741/*
3742 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3743 *
3744 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3745 */
3746TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3747 string key_material = "HelloThisIsAKey";
3748
3749 vector<uint8_t> signing_key, verification_key;
3750 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3751 EXPECT_EQ(ErrorCode::OK,
3752 ImportKey(AuthorizationSetBuilder()
3753 .Authorization(TAG_NO_AUTH_REQUIRED)
3754 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3755 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3756 .Digest(Digest::SHA_2_256)
3757 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3758 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3759 EXPECT_EQ(ErrorCode::OK,
3760 ImportKey(AuthorizationSetBuilder()
3761 .Authorization(TAG_NO_AUTH_REQUIRED)
3762 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3763 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3764 .Digest(Digest::SHA_2_256)
3765 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3766 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3767
3768 string message = "This is a message.";
3769 string signature = SignMessage(
3770 signing_key, message,
3771 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3772
3773 AuthorizationSet begin_out_params;
3774 ASSERT_EQ(ErrorCode::OK,
3775 Begin(KeyPurpose::VERIFY, verification_key,
3776 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3777
3778 string corruptMessage = "This is b message."; // Corrupted message
3779 string output;
3780 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3781
3782 ASSERT_EQ(ErrorCode::OK,
3783 Begin(KeyPurpose::VERIFY, verification_key,
3784 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3785
3786 signature[0] += 1; // Corrupt a signature
3787 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3788
3789 CheckedDeleteKey(&signing_key);
3790 CheckedDeleteKey(&verification_key);
3791}
3792
Selene Huang31ab4042020-04-29 04:22:39 -07003793INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3794
3795typedef KeyMintAidlTestBase ExportKeyTest;
3796
3797/*
3798 * ExportKeyTest.RsaUnsupportedKeyFormat
3799 *
3800 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3801 */
3802// TODO(seleneh) add ExportKey to GenerateKey
3803// check result
3804
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003805class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003806 public:
3807 template <TagType tag_type, Tag tag, typename ValueT>
3808 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3809 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003810 for (auto& entry : key_characteristics_) {
3811 if (entry.securityLevel == SecLevel()) {
3812 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3813 << "Tag " << tag << " with value " << expected
3814 << " not found at security level" << entry.securityLevel;
3815 } else {
3816 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3817 << "Tag " << tag << " found at security level " << entry.securityLevel;
3818 }
Selene Huang31ab4042020-04-29 04:22:39 -07003819 }
3820 }
3821
3822 void CheckOrigin() {
3823 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003824 // Origin isn't a crypto param, but it always lives with them.
3825 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003826 }
3827};
3828
3829/*
3830 * ImportKeyTest.RsaSuccess
3831 *
3832 * Verifies that importing and using an RSA key pair works correctly.
3833 */
3834TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003835 uint32_t key_size;
3836 string key;
3837
3838 if (SecLevel() == SecurityLevel::STRONGBOX) {
3839 key_size = 2048;
3840 key = rsa_2048_key;
3841 } else {
3842 key_size = 1024;
3843 key = rsa_key;
3844 }
3845
Selene Huang31ab4042020-04-29 04:22:39 -07003846 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3847 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003848 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003849 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003850 .Padding(PaddingMode::RSA_PSS)
3851 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003852 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003853
3854 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003855 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003856 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3857 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3858 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3859 CheckOrigin();
3860
3861 string message(1024 / 8, 'a');
3862 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3863 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003864 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003865}
3866
3867/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003868 * ImportKeyTest.RsaSuccessWithoutParams
3869 *
3870 * Verifies that importing and using an RSA key pair without specifying parameters
3871 * works correctly.
3872 */
3873TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3874 uint32_t key_size;
3875 string key;
3876
3877 if (SecLevel() == SecurityLevel::STRONGBOX) {
3878 key_size = 2048;
3879 key = rsa_2048_key;
3880 } else {
3881 key_size = 1024;
3882 key = rsa_key;
3883 }
3884
3885 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3886 .Authorization(TAG_NO_AUTH_REQUIRED)
3887 .SigningKey()
3888 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3889 .Digest(Digest::SHA_2_256)
3890 .Padding(PaddingMode::RSA_PSS)
3891 .SetDefaultValidity(),
3892 KeyFormat::PKCS8, key));
3893
3894 // Key size and public exponent are determined from the imported key material.
3895 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3896 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3897
3898 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3899 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3900 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3901 CheckOrigin();
3902
3903 string message(1024 / 8, 'a');
3904 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3905 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003906 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003907}
3908
3909/*
Selene Huang31ab4042020-04-29 04:22:39 -07003910 * ImportKeyTest.RsaKeySizeMismatch
3911 *
3912 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3913 * correct way.
3914 */
3915TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3916 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3917 ImportKey(AuthorizationSetBuilder()
3918 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3919 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003920 .Padding(PaddingMode::NONE)
3921 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003922 KeyFormat::PKCS8, rsa_key));
3923}
3924
3925/*
3926 * ImportKeyTest.RsaPublicExponentMismatch
3927 *
3928 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3929 * fails in the correct way.
3930 */
3931TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3932 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3933 ImportKey(AuthorizationSetBuilder()
3934 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3935 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003936 .Padding(PaddingMode::NONE)
3937 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003938 KeyFormat::PKCS8, rsa_key));
3939}
3940
3941/*
David Drysdalee60248c2021-10-04 12:54:13 +01003942 * ImportKeyTest.RsaAttestMultiPurposeFail
3943 *
3944 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
3945 */
3946TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00003947 if (AidlVersion() < 2) {
3948 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
3949 // with other key purposes. However, this was not checked at the time
3950 // so we can only be strict about checking this for implementations of KeyMint
3951 // version 2 and above.
3952 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
3953 }
David Drysdalee60248c2021-10-04 12:54:13 +01003954 uint32_t key_size = 2048;
3955 string key = rsa_2048_key;
3956
3957 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3958 ImportKey(AuthorizationSetBuilder()
3959 .Authorization(TAG_NO_AUTH_REQUIRED)
3960 .RsaSigningKey(key_size, 65537)
3961 .AttestKey()
3962 .Digest(Digest::SHA_2_256)
3963 .Padding(PaddingMode::RSA_PSS)
3964 .SetDefaultValidity(),
3965 KeyFormat::PKCS8, key));
3966}
3967
3968/*
Selene Huang31ab4042020-04-29 04:22:39 -07003969 * ImportKeyTest.EcdsaSuccess
3970 *
3971 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3972 */
3973TEST_P(ImportKeyTest, EcdsaSuccess) {
3974 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3975 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003976 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003977 .Digest(Digest::SHA_2_256)
3978 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003979 KeyFormat::PKCS8, ec_256_key));
3980
3981 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003982 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3983 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3984
3985 CheckOrigin();
3986
3987 string message(32, 'a');
3988 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3989 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003990 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003991}
3992
3993/*
3994 * ImportKeyTest.EcdsaP256RFC5915Success
3995 *
3996 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3997 * correctly.
3998 */
3999TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4000 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4001 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004002 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004003 .Digest(Digest::SHA_2_256)
4004 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004005 KeyFormat::PKCS8, ec_256_key_rfc5915));
4006
4007 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004008 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4009 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4010
4011 CheckOrigin();
4012
4013 string message(32, 'a');
4014 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4015 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004016 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004017}
4018
4019/*
4020 * ImportKeyTest.EcdsaP256SEC1Success
4021 *
4022 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4023 */
4024TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4025 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4026 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004027 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004028 .Digest(Digest::SHA_2_256)
4029 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004030 KeyFormat::PKCS8, ec_256_key_sec1));
4031
4032 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004033 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4034 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4035
4036 CheckOrigin();
4037
4038 string message(32, 'a');
4039 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4040 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004041 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004042}
4043
4044/*
4045 * ImportKeyTest.Ecdsa521Success
4046 *
4047 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4048 */
4049TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004050 if (SecLevel() == SecurityLevel::STRONGBOX) {
4051 GTEST_SKIP() << "Test not applicable to StrongBox device";
4052 }
Selene Huang31ab4042020-04-29 04:22:39 -07004053 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4054 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004055 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004056 .Digest(Digest::SHA_2_256)
4057 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004058 KeyFormat::PKCS8, ec_521_key));
4059
4060 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004061 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4062 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4063 CheckOrigin();
4064
4065 string message(32, 'a');
4066 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4067 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004068 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004069}
4070
4071/*
Selene Huang31ab4042020-04-29 04:22:39 -07004072 * ImportKeyTest.EcdsaCurveMismatch
4073 *
4074 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4075 * the correct way.
4076 */
4077TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4078 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4079 ImportKey(AuthorizationSetBuilder()
4080 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004081 .Digest(Digest::NONE)
4082 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004083 KeyFormat::PKCS8, ec_256_key));
4084}
4085
4086/*
David Drysdalee60248c2021-10-04 12:54:13 +01004087 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4088 *
4089 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4090 */
4091TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004092 if (AidlVersion() < 2) {
4093 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4094 // with other key purposes. However, this was not checked at the time
4095 // so we can only be strict about checking this for implementations of KeyMint
4096 // version 2 and above.
4097 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4098 }
David Drysdalee60248c2021-10-04 12:54:13 +01004099 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4100 ImportKey(AuthorizationSetBuilder()
4101 .Authorization(TAG_NO_AUTH_REQUIRED)
4102 .EcdsaSigningKey(EcCurve::P_256)
4103 .AttestKey()
4104 .Digest(Digest::SHA_2_256)
4105 .SetDefaultValidity(),
4106 KeyFormat::PKCS8, ec_256_key));
4107}
4108
4109/*
David Drysdale42fe1892021-10-14 14:43:46 +01004110 * ImportKeyTest.Ed25519RawSuccess
4111 *
4112 * Verifies that importing and using a raw Ed25519 private key works correctly.
4113 */
4114TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4115 if (!Curve25519Supported()) {
4116 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4117 }
4118
4119 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4120 .Authorization(TAG_NO_AUTH_REQUIRED)
4121 .EcdsaSigningKey(EcCurve::CURVE_25519)
4122 .Digest(Digest::NONE)
4123 .SetDefaultValidity(),
4124 KeyFormat::RAW, ed25519_key));
4125 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4126 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4127 CheckOrigin();
4128
4129 // The returned cert should hold the correct public key.
4130 ASSERT_GT(cert_chain_.size(), 0);
4131 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4132 ASSERT_NE(kmKeyCert, nullptr);
4133 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4134 ASSERT_NE(kmPubKey.get(), nullptr);
4135 size_t kmPubKeySize = 32;
4136 uint8_t kmPubKeyData[32];
4137 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4138 ASSERT_EQ(kmPubKeySize, 32);
4139 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4140
4141 string message(32, 'a');
4142 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4143 string signature = SignMessage(message, params);
4144 LocalVerifyMessage(message, signature, params);
4145}
4146
4147/*
4148 * ImportKeyTest.Ed25519Pkcs8Success
4149 *
4150 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4151 */
4152TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4153 if (!Curve25519Supported()) {
4154 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4155 }
4156
4157 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4158 .Authorization(TAG_NO_AUTH_REQUIRED)
4159 .EcdsaSigningKey(EcCurve::CURVE_25519)
4160 .Digest(Digest::NONE)
4161 .SetDefaultValidity(),
4162 KeyFormat::PKCS8, ed25519_pkcs8_key));
4163 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4164 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4165 CheckOrigin();
4166
4167 // The returned cert should hold the correct public key.
4168 ASSERT_GT(cert_chain_.size(), 0);
4169 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4170 ASSERT_NE(kmKeyCert, nullptr);
4171 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4172 ASSERT_NE(kmPubKey.get(), nullptr);
4173 size_t kmPubKeySize = 32;
4174 uint8_t kmPubKeyData[32];
4175 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4176 ASSERT_EQ(kmPubKeySize, 32);
4177 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4178
4179 string message(32, 'a');
4180 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4181 string signature = SignMessage(message, params);
4182 LocalVerifyMessage(message, signature, params);
4183}
4184
4185/*
4186 * ImportKeyTest.Ed25519CurveMismatch
4187 *
4188 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4189 * the correct way.
4190 */
4191TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4192 if (!Curve25519Supported()) {
4193 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4194 }
4195
4196 ASSERT_NE(ErrorCode::OK,
4197 ImportKey(AuthorizationSetBuilder()
4198 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4199 .Digest(Digest::NONE)
4200 .SetDefaultValidity(),
4201 KeyFormat::RAW, ed25519_key));
4202}
4203
4204/*
4205 * ImportKeyTest.Ed25519FormatMismatch
4206 *
4207 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4208 */
4209TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4210 if (!Curve25519Supported()) {
4211 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4212 }
4213
4214 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4215 .EcdsaSigningKey(EcCurve::CURVE_25519)
4216 .Digest(Digest::NONE)
4217 .SetDefaultValidity(),
4218 KeyFormat::PKCS8, ed25519_key));
4219 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4220 .EcdsaSigningKey(EcCurve::CURVE_25519)
4221 .Digest(Digest::NONE)
4222 .SetDefaultValidity(),
4223 KeyFormat::RAW, ed25519_pkcs8_key));
4224}
4225
4226/*
4227 * ImportKeyTest.Ed25519PurposeMismatch
4228 *
4229 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4230 */
4231TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4232 if (!Curve25519Supported()) {
4233 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4234 }
4235
4236 // Can't have both SIGN and ATTEST_KEY
4237 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4238 .EcdsaSigningKey(EcCurve::CURVE_25519)
4239 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4240 .Digest(Digest::NONE)
4241 .SetDefaultValidity(),
4242 KeyFormat::RAW, ed25519_key));
4243 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4244 // PKCS#8 format and so includes an OID).
4245 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4246 .EcdsaKey(EcCurve::CURVE_25519)
4247 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4248 .Digest(Digest::NONE)
4249 .SetDefaultValidity(),
4250 KeyFormat::PKCS8, ed25519_pkcs8_key));
4251}
4252
4253/*
4254 * ImportKeyTest.X25519RawSuccess
4255 *
4256 * Verifies that importing and using a raw X25519 private key works correctly.
4257 */
4258TEST_P(ImportKeyTest, X25519RawSuccess) {
4259 if (!Curve25519Supported()) {
4260 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4261 }
4262
4263 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4264 .Authorization(TAG_NO_AUTH_REQUIRED)
4265 .EcdsaKey(EcCurve::CURVE_25519)
4266 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4267 .SetDefaultValidity(),
4268 KeyFormat::RAW, x25519_key));
4269
4270 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4271 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4272 CheckOrigin();
4273}
4274
4275/*
4276 * ImportKeyTest.X25519Pkcs8Success
4277 *
4278 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4279 */
4280TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4281 if (!Curve25519Supported()) {
4282 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4283 }
4284
4285 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4286 .Authorization(TAG_NO_AUTH_REQUIRED)
4287 .EcdsaKey(EcCurve::CURVE_25519)
4288 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4289 .SetDefaultValidity(),
4290 KeyFormat::PKCS8, x25519_pkcs8_key));
4291
4292 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4293 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4294 CheckOrigin();
4295}
4296
4297/*
4298 * ImportKeyTest.X25519CurveMismatch
4299 *
4300 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4301 * the correct way.
4302 */
4303TEST_P(ImportKeyTest, X25519CurveMismatch) {
4304 if (!Curve25519Supported()) {
4305 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4306 }
4307
4308 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4309 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4310 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4311 .SetDefaultValidity(),
4312 KeyFormat::RAW, x25519_key));
4313}
4314
4315/*
4316 * ImportKeyTest.X25519FormatMismatch
4317 *
4318 * Verifies that importing an X25519 key with an invalid format fails.
4319 */
4320TEST_P(ImportKeyTest, X25519FormatMismatch) {
4321 if (!Curve25519Supported()) {
4322 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4323 }
4324
4325 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4326 .EcdsaKey(EcCurve::CURVE_25519)
4327 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4328 .SetDefaultValidity(),
4329 KeyFormat::PKCS8, x25519_key));
4330 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4331 .EcdsaKey(EcCurve::CURVE_25519)
4332 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4333 .SetDefaultValidity(),
4334 KeyFormat::RAW, x25519_pkcs8_key));
4335}
4336
4337/*
4338 * ImportKeyTest.X25519PurposeMismatch
4339 *
4340 * Verifies that importing an X25519 key pair with an invalid format fails.
4341 */
4342TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4343 if (!Curve25519Supported()) {
4344 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4345 }
4346
4347 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4348 .EcdsaKey(EcCurve::CURVE_25519)
4349 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4350 .SetDefaultValidity(),
4351 KeyFormat::PKCS8, x25519_pkcs8_key));
4352 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4353 .EcdsaSigningKey(EcCurve::CURVE_25519)
4354 .SetDefaultValidity(),
4355 KeyFormat::PKCS8, x25519_pkcs8_key));
4356}
4357
4358/*
Selene Huang31ab4042020-04-29 04:22:39 -07004359 * ImportKeyTest.AesSuccess
4360 *
4361 * Verifies that importing and using an AES key works.
4362 */
4363TEST_P(ImportKeyTest, AesSuccess) {
4364 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4365 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4366 .Authorization(TAG_NO_AUTH_REQUIRED)
4367 .AesEncryptionKey(key.size() * 8)
4368 .EcbMode()
4369 .Padding(PaddingMode::PKCS7),
4370 KeyFormat::RAW, key));
4371
4372 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4373 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4374 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4375 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4376 CheckOrigin();
4377
4378 string message = "Hello World!";
4379 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4380 string ciphertext = EncryptMessage(message, params);
4381 string plaintext = DecryptMessage(ciphertext, params);
4382 EXPECT_EQ(message, plaintext);
4383}
4384
4385/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004386 * ImportKeyTest.AesFailure
4387 *
4388 * Verifies that importing an invalid AES key fails.
4389 */
4390TEST_P(ImportKeyTest, AesFailure) {
4391 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4392 uint32_t bitlen = key.size() * 8;
4393 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004394 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004395 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004396 .Authorization(TAG_NO_AUTH_REQUIRED)
4397 .AesEncryptionKey(key_size)
4398 .EcbMode()
4399 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004400 KeyFormat::RAW, key);
4401 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004402 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4403 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004404 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004405
4406 // Explicit key size matches that of the provided key, but it's not a valid size.
4407 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4408 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4409 ImportKey(AuthorizationSetBuilder()
4410 .Authorization(TAG_NO_AUTH_REQUIRED)
4411 .AesEncryptionKey(long_key.size() * 8)
4412 .EcbMode()
4413 .Padding(PaddingMode::PKCS7),
4414 KeyFormat::RAW, long_key));
4415 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4416 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4417 ImportKey(AuthorizationSetBuilder()
4418 .Authorization(TAG_NO_AUTH_REQUIRED)
4419 .AesEncryptionKey(short_key.size() * 8)
4420 .EcbMode()
4421 .Padding(PaddingMode::PKCS7),
4422 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004423}
4424
4425/*
4426 * ImportKeyTest.TripleDesSuccess
4427 *
4428 * Verifies that importing and using a 3DES key works.
4429 */
4430TEST_P(ImportKeyTest, TripleDesSuccess) {
4431 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4432 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4433 .Authorization(TAG_NO_AUTH_REQUIRED)
4434 .TripleDesEncryptionKey(168)
4435 .EcbMode()
4436 .Padding(PaddingMode::PKCS7),
4437 KeyFormat::RAW, key));
4438
4439 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4440 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4441 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4442 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4443 CheckOrigin();
4444
4445 string message = "Hello World!";
4446 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4447 string ciphertext = EncryptMessage(message, params);
4448 string plaintext = DecryptMessage(ciphertext, params);
4449 EXPECT_EQ(message, plaintext);
4450}
4451
4452/*
4453 * ImportKeyTest.TripleDesFailure
4454 *
4455 * Verifies that importing an invalid 3DES key fails.
4456 */
4457TEST_P(ImportKeyTest, TripleDesFailure) {
4458 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004459 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004460 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004461 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004462 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004463 .Authorization(TAG_NO_AUTH_REQUIRED)
4464 .TripleDesEncryptionKey(key_size)
4465 .EcbMode()
4466 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004467 KeyFormat::RAW, key);
4468 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004469 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4470 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004471 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004472 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004473 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004474 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4475 ImportKey(AuthorizationSetBuilder()
4476 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004477 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004478 .EcbMode()
4479 .Padding(PaddingMode::PKCS7),
4480 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004481 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004482 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4483 ImportKey(AuthorizationSetBuilder()
4484 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004485 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004486 .EcbMode()
4487 .Padding(PaddingMode::PKCS7),
4488 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004489}
4490
4491/*
4492 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004493 *
4494 * Verifies that importing and using an HMAC key works.
4495 */
4496TEST_P(ImportKeyTest, HmacKeySuccess) {
4497 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4498 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4499 .Authorization(TAG_NO_AUTH_REQUIRED)
4500 .HmacKey(key.size() * 8)
4501 .Digest(Digest::SHA_2_256)
4502 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4503 KeyFormat::RAW, key));
4504
4505 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4506 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4507 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4508 CheckOrigin();
4509
4510 string message = "Hello World!";
4511 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4512 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4513}
4514
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004515/*
4516 * ImportKeyTest.GetKeyCharacteristics
4517 *
4518 * Verifies that imported keys have the correct characteristics.
4519 */
4520TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4521 vector<uint8_t> key_blob;
4522 vector<KeyCharacteristics> key_characteristics;
4523 auto base_builder = AuthorizationSetBuilder()
4524 .Padding(PaddingMode::NONE)
4525 .Authorization(TAG_NO_AUTH_REQUIRED)
4526 .SetDefaultValidity();
4527 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4528 Algorithm::TRIPLE_DES};
4529 ErrorCode result;
4530 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4531 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4532 for (auto alg : algorithms) {
4533 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4534 AuthorizationSetBuilder builder(base_builder);
4535 switch (alg) {
4536 case Algorithm::RSA:
4537 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4538
4539 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4540 &key_characteristics);
4541 break;
4542 case Algorithm::EC:
4543 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4544 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4545 &key_characteristics);
4546 break;
4547 case Algorithm::HMAC:
4548 builder.HmacKey(128)
4549 .Digest(Digest::SHA_2_256)
4550 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4551 result =
4552 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4553 break;
4554 case Algorithm::AES:
4555 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4556 result =
4557 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4558 break;
4559 case Algorithm::TRIPLE_DES:
4560 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4561 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4562 &key_characteristics);
4563 break;
4564 default:
4565 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4566 continue;
4567 }
4568 ASSERT_EQ(ErrorCode::OK, result);
4569 CheckCharacteristics(key_blob, key_characteristics);
4570 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4571 }
4572}
4573
Selene Huang31ab4042020-04-29 04:22:39 -07004574INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4575
4576auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004577 // IKeyMintDevice.aidl
4578 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4579 "020100" // INTEGER length 1 value 0x00 (version)
4580 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4581 "934bf94e2aa28a3f83c9f79297250262"
4582 "fbe3276b5a1c91159bbfa3ef8957aac8"
4583 "4b59b30b455a79c2973480823d8b3863"
4584 "c3deef4a8e243590268d80e18751a0e1"
4585 "30f67ce6a1ace9f79b95e097474febc9"
4586 "81195b1d13a69086c0863f66a7b7fdb4"
4587 "8792227b1ac5e2489febdf087ab54864"
4588 "83033a6f001ca5d1ec1e27f5c30f4cec"
4589 "2642074a39ae68aee552e196627a8e3d"
4590 "867e67a8c01b11e75f13cca0a97ab668"
4591 "b50cda07a8ecb7cd8e3dd7009c963653"
4592 "4f6f239cffe1fc8daa466f78b676c711"
4593 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4594 "99b801597d5220e307eaa5bee507fb94"
4595 "d1fa69f9e519b2de315bac92c36f2ea1"
4596 "fa1df4478c0ddedeae8c70e0233cd098"
4597 "040c" // OCTET STRING length 0x0c (initializationVector)
4598 "d796b02c370f1fa4cc0124f1"
4599 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4600 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4601 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4602 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4603 "3106" // SET length 0x06
4604 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4605 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4606 // } end SET
4607 // } end [1]
4608 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4609 "020120" // INTEGER length 1 value 0x20 (AES)
4610 // } end [2]
4611 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4612 "02020100" // INTEGER length 2 value 0x100
4613 // } end [3]
4614 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4615 "3103" // SET length 0x03 {
4616 "020101" // INTEGER length 1 value 0x01 (ECB)
4617 // } end SET
4618 // } end [4]
4619 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4620 "3103" // SET length 0x03 {
4621 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4622 // } end SET
4623 // } end [5]
4624 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4625 // (noAuthRequired)
4626 "0500" // NULL
4627 // } end [503]
4628 // } end SEQUENCE (AuthorizationList)
4629 // } end SEQUENCE (KeyDescription)
4630 "0420" // OCTET STRING length 0x20 (encryptedKey)
4631 "ccd540855f833a5e1480bfd2d36faf3a"
4632 "eee15df5beabe2691bc82dde2a7aa910"
4633 "0410" // OCTET STRING length 0x10 (tag)
4634 "64c9f689c60ff6223ab6e6999e0eb6e5"
4635 // } SEQUENCE (SecureKeyWrapper)
4636);
Selene Huang31ab4042020-04-29 04:22:39 -07004637
4638auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004639 // IKeyMintDevice.aidl
4640 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4641 "020100" // INTEGER length 1 value 0x00 (version)
4642 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4643 "aad93ed5924f283b4bb5526fbe7a1412"
4644 "f9d9749ec30db9062b29e574a8546f33"
4645 "c88732452f5b8e6a391ee76c39ed1712"
4646 "c61d8df6213dec1cffbc17a8c6d04c7b"
4647 "30893d8daa9b2015213e219468215532"
4648 "07f8f9931c4caba23ed3bee28b36947e"
4649 "47f10e0a5c3dc51c988a628daad3e5e1"
4650 "f4005e79c2d5a96c284b4b8d7e4948f3"
4651 "31e5b85dd5a236f85579f3ea1d1b8484"
4652 "87470bdb0ab4f81a12bee42c99fe0df4"
4653 "bee3759453e69ad1d68a809ce06b949f"
4654 "7694a990429b2fe81e066ff43e56a216"
4655 "02db70757922a4bcc23ab89f1e35da77"
4656 "586775f423e519c2ea394caf48a28d0c"
4657 "8020f1dcf6b3a68ec246f615ae96dae9"
4658 "a079b1f6eb959033c1af5c125fd94168"
4659 "040c" // OCTET STRING length 0x0c (initializationVector)
4660 "6d9721d08589581ab49204a3"
4661 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4662 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4663 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4664 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4665 "3106" // SET length 0x06
4666 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4667 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4668 // } end SET
4669 // } end [1]
4670 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4671 "020120" // INTEGER length 1 value 0x20 (AES)
4672 // } end [2]
4673 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4674 "02020100" // INTEGER length 2 value 0x100
4675 // } end [3]
4676 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4677 "3103" // SET length 0x03 {
4678 "020101" // INTEGER length 1 value 0x01 (ECB)
4679 // } end SET
4680 // } end [4]
4681 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4682 "3103" // SET length 0x03 {
4683 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4684 // } end SET
4685 // } end [5]
4686 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4687 // (noAuthRequired)
4688 "0500" // NULL
4689 // } end [503]
4690 // } end SEQUENCE (AuthorizationList)
4691 // } end SEQUENCE (KeyDescription)
4692 "0420" // OCTET STRING length 0x20 (encryptedKey)
4693 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4694 "c20d1f99a9a024a76f35c8e2cab9b68d"
4695 "0410" // OCTET STRING length 0x10 (tag)
4696 "2560c70109ae67c030f00b98b512a670"
4697 // } SEQUENCE (SecureKeyWrapper)
4698);
Selene Huang31ab4042020-04-29 04:22:39 -07004699
4700auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004701 // RFC 5208 s5
4702 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4703 "020100" // INTEGER length 1 value 0x00 (version)
4704 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4705 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4706 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4707 "0500" // NULL (parameters)
4708 // } SEQUENCE (AlgorithmIdentifier)
4709 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4710 // RFC 8017 A.1.2
4711 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4712 "020100" // INTEGER length 1 value 0x00 (version)
4713 "02820101" // INTEGER length 0x0101 (modulus) value...
4714 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4715 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4716 "7b06e673a837313d56b1c725150a3fef" // 0x30
4717 "86acbddc41bb759c2854eae32d35841e" // 0x40
4718 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4719 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4720 "312d7bd5921ffaea1347c157406fef71" // 0x70
4721 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4722 "f4645c11f5c1374c3886427411c44979" // 0x90
4723 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4724 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4725 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4726 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4727 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4728 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4729 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4730 "55" // 0x101
4731 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4732 "02820100" // INTEGER length 0x100 (privateExponent) value...
4733 "431447b6251908112b1ee76f99f3711a" // 0x10
4734 "52b6630960046c2de70de188d833f8b8" // 0x20
4735 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4736 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4737 "e710b630a03adc683b5d2c43080e52be" // 0x50
4738 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4739 "822bccff087d63c940ba8a45f670feb2" // 0x70
4740 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4741 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4742 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4743 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4744 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4745 "52659d5a5ba05b663737a8696281865b" // 0xd0
4746 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4747 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4748 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4749 "028181" // INTEGER length 0x81 (prime1) value...
4750 "00de392e18d682c829266cc3454e1d61" // 0x10
4751 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4752 "ff841be5bac82a164c5970007047b8c5" // 0x30
4753 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4754 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4755 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4756 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4757 "9e91346130748a6e3c124f9149d71c74" // 0x80
4758 "35"
4759 "028181" // INTEGER length 0x81 (prime2) value...
4760 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4761 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4762 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4763 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4764 "9ed39a2d934c880440aed8832f984316" // 0x50
4765 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4766 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4767 "b880677c068e1be936e81288815252a8" // 0x80
4768 "a1"
4769 "028180" // INTEGER length 0x80 (exponent1) value...
4770 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4771 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4772 "5a063212a4f105a3764743e53281988a" // 0x30
4773 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4774 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4775 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4776 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4777 "4719d6e2b9439823719cd08bcd031781" // 0x80
4778 "028181" // INTEGER length 0x81 (exponent2) value...
4779 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4780 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4781 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4782 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4783 "1254186af30b22c10582a8a43e34fe94" // 0x50
4784 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4785 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4786 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4787 "61"
4788 "028181" // INTEGER length 0x81 (coefficient) value...
4789 "00c931617c77829dfb1270502be9195c" // 0x10
4790 "8f2830885f57dba869536811e6864236" // 0x20
4791 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4792 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4793 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4794 "959356210723287b0affcc9f727044d4" // 0x60
4795 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4796 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4797 "22"
4798 // } SEQUENCE
4799 // } SEQUENCE ()
4800);
Selene Huang31ab4042020-04-29 04:22:39 -07004801
4802string zero_masking_key =
4803 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4804string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4805
4806class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4807
4808TEST_P(ImportWrappedKeyTest, Success) {
4809 auto wrapping_key_desc = AuthorizationSetBuilder()
4810 .RsaEncryptionKey(2048, 65537)
4811 .Digest(Digest::SHA_2_256)
4812 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004813 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4814 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004815
4816 ASSERT_EQ(ErrorCode::OK,
4817 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4818 AuthorizationSetBuilder()
4819 .Digest(Digest::SHA_2_256)
4820 .Padding(PaddingMode::RSA_OAEP)));
4821
4822 string message = "Hello World!";
4823 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4824 string ciphertext = EncryptMessage(message, params);
4825 string plaintext = DecryptMessage(ciphertext, params);
4826 EXPECT_EQ(message, plaintext);
4827}
4828
David Drysdaled2cc8c22021-04-15 13:29:45 +01004829/*
4830 * ImportWrappedKeyTest.SuccessSidsIgnored
4831 *
4832 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
4833 * include Tag:USER_SECURE_ID.
4834 */
4835TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
4836 auto wrapping_key_desc = AuthorizationSetBuilder()
4837 .RsaEncryptionKey(2048, 65537)
4838 .Digest(Digest::SHA_2_256)
4839 .Padding(PaddingMode::RSA_OAEP)
4840 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4841 .SetDefaultValidity();
4842
4843 int64_t password_sid = 42;
4844 int64_t biometric_sid = 24;
4845 ASSERT_EQ(ErrorCode::OK,
4846 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4847 AuthorizationSetBuilder()
4848 .Digest(Digest::SHA_2_256)
4849 .Padding(PaddingMode::RSA_OAEP),
4850 password_sid, biometric_sid));
4851
4852 string message = "Hello World!";
4853 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4854 string ciphertext = EncryptMessage(message, params);
4855 string plaintext = DecryptMessage(ciphertext, params);
4856 EXPECT_EQ(message, plaintext);
4857}
4858
Selene Huang31ab4042020-04-29 04:22:39 -07004859TEST_P(ImportWrappedKeyTest, SuccessMasked) {
4860 auto wrapping_key_desc = AuthorizationSetBuilder()
4861 .RsaEncryptionKey(2048, 65537)
4862 .Digest(Digest::SHA_2_256)
4863 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004864 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4865 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004866
4867 ASSERT_EQ(ErrorCode::OK,
4868 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
4869 AuthorizationSetBuilder()
4870 .Digest(Digest::SHA_2_256)
4871 .Padding(PaddingMode::RSA_OAEP)));
4872}
4873
4874TEST_P(ImportWrappedKeyTest, WrongMask) {
4875 auto wrapping_key_desc = AuthorizationSetBuilder()
4876 .RsaEncryptionKey(2048, 65537)
4877 .Digest(Digest::SHA_2_256)
4878 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004879 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4880 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004881
4882 ASSERT_EQ(
4883 ErrorCode::VERIFICATION_FAILED,
4884 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4885 AuthorizationSetBuilder()
4886 .Digest(Digest::SHA_2_256)
4887 .Padding(PaddingMode::RSA_OAEP)));
4888}
4889
4890TEST_P(ImportWrappedKeyTest, WrongPurpose) {
4891 auto wrapping_key_desc = AuthorizationSetBuilder()
4892 .RsaEncryptionKey(2048, 65537)
4893 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004894 .Padding(PaddingMode::RSA_OAEP)
4895 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004896
4897 ASSERT_EQ(
4898 ErrorCode::INCOMPATIBLE_PURPOSE,
4899 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4900 AuthorizationSetBuilder()
4901 .Digest(Digest::SHA_2_256)
4902 .Padding(PaddingMode::RSA_OAEP)));
4903}
4904
David Drysdaled2cc8c22021-04-15 13:29:45 +01004905TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
4906 auto wrapping_key_desc = AuthorizationSetBuilder()
4907 .RsaEncryptionKey(2048, 65537)
4908 .Digest(Digest::SHA_2_256)
4909 .Padding(PaddingMode::RSA_PSS)
4910 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4911 .SetDefaultValidity();
4912
4913 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
4914 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4915 AuthorizationSetBuilder()
4916 .Digest(Digest::SHA_2_256)
4917 .Padding(PaddingMode::RSA_OAEP)));
4918}
4919
4920TEST_P(ImportWrappedKeyTest, WrongDigest) {
4921 auto wrapping_key_desc = AuthorizationSetBuilder()
4922 .RsaEncryptionKey(2048, 65537)
4923 .Digest(Digest::SHA_2_512)
4924 .Padding(PaddingMode::RSA_OAEP)
4925 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4926 .SetDefaultValidity();
4927
4928 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
4929 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4930 AuthorizationSetBuilder()
4931 .Digest(Digest::SHA_2_256)
4932 .Padding(PaddingMode::RSA_OAEP)));
4933}
4934
Selene Huang31ab4042020-04-29 04:22:39 -07004935INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
4936
4937typedef KeyMintAidlTestBase EncryptionOperationsTest;
4938
4939/*
4940 * EncryptionOperationsTest.RsaNoPaddingSuccess
4941 *
David Drysdale59cae642021-05-12 13:52:03 +01004942 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07004943 */
4944TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00004945 for (uint64_t exponent : ValidExponents()) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01004946 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4947 .Authorization(TAG_NO_AUTH_REQUIRED)
4948 .RsaEncryptionKey(2048, exponent)
4949 .Padding(PaddingMode::NONE)
4950 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004951
David Drysdaled2cc8c22021-04-15 13:29:45 +01004952 string message = string(2048 / 8, 'a');
4953 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004954 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004955 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004956
David Drysdale59cae642021-05-12 13:52:03 +01004957 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004958 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004959
David Drysdaled2cc8c22021-04-15 13:29:45 +01004960 // Unpadded RSA is deterministic
4961 EXPECT_EQ(ciphertext1, ciphertext2);
4962
4963 CheckedDeleteKey();
4964 }
Selene Huang31ab4042020-04-29 04:22:39 -07004965}
4966
4967/*
4968 * EncryptionOperationsTest.RsaNoPaddingShortMessage
4969 *
David Drysdale59cae642021-05-12 13:52:03 +01004970 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07004971 */
4972TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
4973 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4974 .Authorization(TAG_NO_AUTH_REQUIRED)
4975 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004976 .Padding(PaddingMode::NONE)
4977 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004978
4979 string message = "1";
4980 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4981
David Drysdale59cae642021-05-12 13:52:03 +01004982 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004983 EXPECT_EQ(2048U / 8, ciphertext.size());
4984
4985 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
4986 string plaintext = DecryptMessage(ciphertext, params);
4987
4988 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07004989}
4990
4991/*
Selene Huang31ab4042020-04-29 04:22:39 -07004992 * EncryptionOperationsTest.RsaOaepSuccess
4993 *
David Drysdale59cae642021-05-12 13:52:03 +01004994 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07004995 */
4996TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
4997 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4998
4999 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01005000 ASSERT_EQ(ErrorCode::OK,
5001 GenerateKey(AuthorizationSetBuilder()
5002 .Authorization(TAG_NO_AUTH_REQUIRED)
5003 .RsaEncryptionKey(key_size, 65537)
5004 .Padding(PaddingMode::RSA_OAEP)
5005 .Digest(digests)
5006 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
5007 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005008
5009 string message = "Hello";
5010
5011 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005012 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5013
5014 auto params = AuthorizationSetBuilder()
5015 .Digest(digest)
5016 .Padding(PaddingMode::RSA_OAEP)
5017 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5018 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005019 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5020 EXPECT_EQ(key_size / 8, ciphertext1.size());
5021
David Drysdale59cae642021-05-12 13:52:03 +01005022 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005023 EXPECT_EQ(key_size / 8, ciphertext2.size());
5024
5025 // OAEP randomizes padding so every result should be different (with astronomically high
5026 // probability).
5027 EXPECT_NE(ciphertext1, ciphertext2);
5028
5029 string plaintext1 = DecryptMessage(ciphertext1, params);
5030 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5031 string plaintext2 = DecryptMessage(ciphertext2, params);
5032 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5033
5034 // Decrypting corrupted ciphertext should fail.
5035 size_t offset_to_corrupt = random() % ciphertext1.size();
5036 char corrupt_byte;
5037 do {
5038 corrupt_byte = static_cast<char>(random() % 256);
5039 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5040 ciphertext1[offset_to_corrupt] = corrupt_byte;
5041
5042 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5043 string result;
5044 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5045 EXPECT_EQ(0U, result.size());
5046 }
5047}
5048
5049/*
5050 * EncryptionOperationsTest.RsaOaepInvalidDigest
5051 *
David Drysdale59cae642021-05-12 13:52:03 +01005052 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005053 * without a digest.
5054 */
5055TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5056 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5057 .Authorization(TAG_NO_AUTH_REQUIRED)
5058 .RsaEncryptionKey(2048, 65537)
5059 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005060 .Digest(Digest::NONE)
5061 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005062
5063 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005064 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005065}
5066
5067/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005068 * EncryptionOperationsTest.RsaOaepInvalidPadding
5069 *
David Drysdale59cae642021-05-12 13:52:03 +01005070 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005071 * with a padding value that is only suitable for signing/verifying.
5072 */
5073TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5074 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5075 .Authorization(TAG_NO_AUTH_REQUIRED)
5076 .RsaEncryptionKey(2048, 65537)
5077 .Padding(PaddingMode::RSA_PSS)
5078 .Digest(Digest::NONE)
5079 .SetDefaultValidity()));
5080
5081 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005082 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005083}
5084
5085/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005086 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005087 *
David Drysdale59cae642021-05-12 13:52:03 +01005088 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005089 * with a different digest than was used to encrypt.
5090 */
5091TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005092 if (SecLevel() == SecurityLevel::STRONGBOX) {
5093 GTEST_SKIP() << "Test not applicable to StrongBox device";
5094 }
Selene Huang31ab4042020-04-29 04:22:39 -07005095
5096 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5097 .Authorization(TAG_NO_AUTH_REQUIRED)
5098 .RsaEncryptionKey(1024, 65537)
5099 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005100 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5101 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005102 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005103 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005104 message,
5105 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5106
5107 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5108 .Digest(Digest::SHA_2_256)
5109 .Padding(PaddingMode::RSA_OAEP)));
5110 string result;
5111 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5112 EXPECT_EQ(0U, result.size());
5113}
5114
5115/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005116 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5117 *
David Drysdale59cae642021-05-12 13:52:03 +01005118 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005119 * digests.
5120 */
5121TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5122 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5123
5124 size_t key_size = 2048; // Need largish key for SHA-512 test.
5125 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5126 .OaepMGFDigest(digests)
5127 .Authorization(TAG_NO_AUTH_REQUIRED)
5128 .RsaEncryptionKey(key_size, 65537)
5129 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005130 .Digest(Digest::SHA_2_256)
5131 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005132
5133 string message = "Hello";
5134
5135 for (auto digest : digests) {
5136 auto params = AuthorizationSetBuilder()
5137 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5138 .Digest(Digest::SHA_2_256)
5139 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005140 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005141 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5142 EXPECT_EQ(key_size / 8, ciphertext1.size());
5143
David Drysdale59cae642021-05-12 13:52:03 +01005144 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005145 EXPECT_EQ(key_size / 8, ciphertext2.size());
5146
5147 // OAEP randomizes padding so every result should be different (with astronomically high
5148 // probability).
5149 EXPECT_NE(ciphertext1, ciphertext2);
5150
5151 string plaintext1 = DecryptMessage(ciphertext1, params);
5152 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5153 string plaintext2 = DecryptMessage(ciphertext2, params);
5154 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5155
5156 // Decrypting corrupted ciphertext should fail.
5157 size_t offset_to_corrupt = random() % ciphertext1.size();
5158 char corrupt_byte;
5159 do {
5160 corrupt_byte = static_cast<char>(random() % 256);
5161 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5162 ciphertext1[offset_to_corrupt] = corrupt_byte;
5163
5164 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5165 string result;
5166 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5167 EXPECT_EQ(0U, result.size());
5168 }
5169}
5170
5171/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005172 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5173 *
5174 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5175 * specified, defaulting to SHA-1.
5176 */
5177TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5178 size_t key_size = 2048;
5179 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5180 .Authorization(TAG_NO_AUTH_REQUIRED)
5181 .RsaEncryptionKey(key_size, 65537)
5182 .Padding(PaddingMode::RSA_OAEP)
5183 .Digest(Digest::SHA_2_256)
5184 .SetDefaultValidity()));
5185
5186 // Do local RSA encryption using the default MGF digest of SHA-1.
5187 string message = "Hello";
5188 auto params =
5189 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5190 string ciphertext = LocalRsaEncryptMessage(message, params);
5191 EXPECT_EQ(key_size / 8, ciphertext.size());
5192
5193 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5194 string plaintext = DecryptMessage(ciphertext, params);
5195 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5196
5197 // Decrypting corrupted ciphertext should fail.
5198 size_t offset_to_corrupt = random() % ciphertext.size();
5199 char corrupt_byte;
5200 do {
5201 corrupt_byte = static_cast<char>(random() % 256);
5202 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5203 ciphertext[offset_to_corrupt] = corrupt_byte;
5204
5205 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5206 string result;
5207 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5208 EXPECT_EQ(0U, result.size());
5209}
5210
5211/*
5212 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5213 *
5214 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5215 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5216 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5217 */
5218TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5219 size_t key_size = 2048;
5220 ASSERT_EQ(ErrorCode::OK,
5221 GenerateKey(AuthorizationSetBuilder()
5222 .Authorization(TAG_NO_AUTH_REQUIRED)
5223 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5224 .RsaEncryptionKey(key_size, 65537)
5225 .Padding(PaddingMode::RSA_OAEP)
5226 .Digest(Digest::SHA_2_256)
5227 .SetDefaultValidity()));
5228
5229 // Do local RSA encryption using the default MGF digest of SHA-1.
5230 string message = "Hello";
5231 auto params =
5232 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5233 string ciphertext = LocalRsaEncryptMessage(message, params);
5234 EXPECT_EQ(key_size / 8, ciphertext.size());
5235
5236 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5237 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5238 // is checked against those values, and found absent.
5239 auto result = Begin(KeyPurpose::DECRYPT, params);
5240 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5241 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5242}
5243
5244/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005245 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5246 *
David Drysdale59cae642021-05-12 13:52:03 +01005247 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005248 * with incompatible MGF digest.
5249 */
5250TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5251 ASSERT_EQ(ErrorCode::OK,
5252 GenerateKey(AuthorizationSetBuilder()
5253 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5254 .Authorization(TAG_NO_AUTH_REQUIRED)
5255 .RsaEncryptionKey(2048, 65537)
5256 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005257 .Digest(Digest::SHA_2_256)
5258 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005259 string message = "Hello World!";
5260
5261 auto params = AuthorizationSetBuilder()
5262 .Padding(PaddingMode::RSA_OAEP)
5263 .Digest(Digest::SHA_2_256)
5264 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005265 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005266}
5267
5268/*
5269 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5270 *
5271 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5272 * with unsupported MGF digest.
5273 */
5274TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5275 ASSERT_EQ(ErrorCode::OK,
5276 GenerateKey(AuthorizationSetBuilder()
5277 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5278 .Authorization(TAG_NO_AUTH_REQUIRED)
5279 .RsaEncryptionKey(2048, 65537)
5280 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005281 .Digest(Digest::SHA_2_256)
5282 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005283 string message = "Hello World!";
5284
5285 auto params = AuthorizationSetBuilder()
5286 .Padding(PaddingMode::RSA_OAEP)
5287 .Digest(Digest::SHA_2_256)
5288 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005289 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005290}
5291
5292/*
Selene Huang31ab4042020-04-29 04:22:39 -07005293 * EncryptionOperationsTest.RsaPkcs1Success
5294 *
5295 * Verifies that RSA PKCS encryption/decrypts works.
5296 */
5297TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5298 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5299 .Authorization(TAG_NO_AUTH_REQUIRED)
5300 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005301 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5302 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005303
5304 string message = "Hello World!";
5305 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005306 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005307 EXPECT_EQ(2048U / 8, ciphertext1.size());
5308
David Drysdale59cae642021-05-12 13:52:03 +01005309 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005310 EXPECT_EQ(2048U / 8, ciphertext2.size());
5311
5312 // PKCS1 v1.5 randomizes padding so every result should be different.
5313 EXPECT_NE(ciphertext1, ciphertext2);
5314
5315 string plaintext = DecryptMessage(ciphertext1, params);
5316 EXPECT_EQ(message, plaintext);
5317
5318 // Decrypting corrupted ciphertext should fail.
5319 size_t offset_to_corrupt = random() % ciphertext1.size();
5320 char corrupt_byte;
5321 do {
5322 corrupt_byte = static_cast<char>(random() % 256);
5323 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5324 ciphertext1[offset_to_corrupt] = corrupt_byte;
5325
5326 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5327 string result;
5328 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5329 EXPECT_EQ(0U, result.size());
5330}
5331
5332/*
Selene Huang31ab4042020-04-29 04:22:39 -07005333 * EncryptionOperationsTest.EcdsaEncrypt
5334 *
5335 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5336 */
5337TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5338 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5339 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005340 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005341 .Digest(Digest::NONE)
5342 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005343 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5344 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5345 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5346}
5347
5348/*
5349 * EncryptionOperationsTest.HmacEncrypt
5350 *
5351 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5352 */
5353TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5354 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5355 .Authorization(TAG_NO_AUTH_REQUIRED)
5356 .HmacKey(128)
5357 .Digest(Digest::SHA_2_256)
5358 .Padding(PaddingMode::NONE)
5359 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5360 auto params = AuthorizationSetBuilder()
5361 .Digest(Digest::SHA_2_256)
5362 .Padding(PaddingMode::NONE)
5363 .Authorization(TAG_MAC_LENGTH, 128);
5364 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5365 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5366}
5367
5368/*
5369 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5370 *
5371 * Verifies that AES ECB mode works.
5372 */
5373TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5374 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5375 .Authorization(TAG_NO_AUTH_REQUIRED)
5376 .AesEncryptionKey(128)
5377 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5378 .Padding(PaddingMode::NONE)));
5379
5380 ASSERT_GT(key_blob_.size(), 0U);
5381 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5382
5383 // Two-block message.
5384 string message = "12345678901234567890123456789012";
5385 string ciphertext1 = EncryptMessage(message, params);
5386 EXPECT_EQ(message.size(), ciphertext1.size());
5387
5388 string ciphertext2 = EncryptMessage(string(message), params);
5389 EXPECT_EQ(message.size(), ciphertext2.size());
5390
5391 // ECB is deterministic.
5392 EXPECT_EQ(ciphertext1, ciphertext2);
5393
5394 string plaintext = DecryptMessage(ciphertext1, params);
5395 EXPECT_EQ(message, plaintext);
5396}
5397
5398/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005399 * EncryptionOperationsTest.AesEcbUnknownTag
5400 *
5401 * Verifies that AES ECB operations ignore unknown tags.
5402 */
5403TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5404 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5405 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5406 KeyParameter unknown_param;
5407 unknown_param.tag = unknown_tag;
5408
5409 vector<KeyCharacteristics> key_characteristics;
5410 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5411 .Authorization(TAG_NO_AUTH_REQUIRED)
5412 .AesEncryptionKey(128)
5413 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5414 .Padding(PaddingMode::NONE)
5415 .Authorization(unknown_param),
5416 &key_blob_, &key_characteristics));
5417 ASSERT_GT(key_blob_.size(), 0U);
5418
5419 // Unknown tags should not be returned in key characteristics.
5420 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5421 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5422 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5423 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5424
5425 // Encrypt without mentioning the unknown parameter.
5426 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5427 string message = "12345678901234567890123456789012";
5428 string ciphertext = EncryptMessage(message, params);
5429 EXPECT_EQ(message.size(), ciphertext.size());
5430
5431 // Decrypt including the unknown parameter.
5432 auto decrypt_params = AuthorizationSetBuilder()
5433 .BlockMode(BlockMode::ECB)
5434 .Padding(PaddingMode::NONE)
5435 .Authorization(unknown_param);
5436 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5437 EXPECT_EQ(message, plaintext);
5438}
5439
5440/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005441 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005442 *
5443 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5444 */
5445TEST_P(EncryptionOperationsTest, AesWrongMode) {
5446 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5447 .Authorization(TAG_NO_AUTH_REQUIRED)
5448 .AesEncryptionKey(128)
5449 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5450 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005451 ASSERT_GT(key_blob_.size(), 0U);
5452
Selene Huang31ab4042020-04-29 04:22:39 -07005453 EXPECT_EQ(
5454 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5455 Begin(KeyPurpose::ENCRYPT,
5456 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5457}
5458
5459/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005460 * EncryptionOperationsTest.AesWrongPadding
5461 *
5462 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5463 */
5464TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5465 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5466 .Authorization(TAG_NO_AUTH_REQUIRED)
5467 .AesEncryptionKey(128)
5468 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5469 .Padding(PaddingMode::NONE)));
5470 ASSERT_GT(key_blob_.size(), 0U);
5471
5472 EXPECT_EQ(
5473 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5474 Begin(KeyPurpose::ENCRYPT,
5475 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5476}
5477
5478/*
5479 * EncryptionOperationsTest.AesInvalidParams
5480 *
5481 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5482 */
5483TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5484 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5485 .Authorization(TAG_NO_AUTH_REQUIRED)
5486 .AesEncryptionKey(128)
5487 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5488 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5489 .Padding(PaddingMode::NONE)
5490 .Padding(PaddingMode::PKCS7)));
5491 ASSERT_GT(key_blob_.size(), 0U);
5492
5493 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5494 .BlockMode(BlockMode::CBC)
5495 .BlockMode(BlockMode::ECB)
5496 .Padding(PaddingMode::NONE));
5497 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5498 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5499
5500 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5501 .BlockMode(BlockMode::ECB)
5502 .Padding(PaddingMode::NONE)
5503 .Padding(PaddingMode::PKCS7));
5504 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5505 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5506}
5507
5508/*
Selene Huang31ab4042020-04-29 04:22:39 -07005509 * EncryptionOperationsTest.AesWrongPurpose
5510 *
5511 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5512 * specified.
5513 */
5514TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5515 auto err = GenerateKey(AuthorizationSetBuilder()
5516 .Authorization(TAG_NO_AUTH_REQUIRED)
5517 .AesKey(128)
5518 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5519 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5520 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5521 .Padding(PaddingMode::NONE));
5522 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5523 ASSERT_GT(key_blob_.size(), 0U);
5524
5525 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5526 .BlockMode(BlockMode::GCM)
5527 .Padding(PaddingMode::NONE)
5528 .Authorization(TAG_MAC_LENGTH, 128));
5529 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5530
5531 CheckedDeleteKey();
5532
5533 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5534 .Authorization(TAG_NO_AUTH_REQUIRED)
5535 .AesKey(128)
5536 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5537 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5538 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5539 .Padding(PaddingMode::NONE)));
5540
5541 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5542 .BlockMode(BlockMode::GCM)
5543 .Padding(PaddingMode::NONE)
5544 .Authorization(TAG_MAC_LENGTH, 128));
5545 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5546}
5547
5548/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005549 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005550 *
5551 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5552 * multiple of the block size and no padding is specified.
5553 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005554TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5555 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5556 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5557 .Authorization(TAG_NO_AUTH_REQUIRED)
5558 .AesEncryptionKey(128)
5559 .Authorization(TAG_BLOCK_MODE, blockMode)
5560 .Padding(PaddingMode::NONE)));
5561 // Message is slightly shorter than two blocks.
5562 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005563
David Drysdaled2cc8c22021-04-15 13:29:45 +01005564 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5565 AuthorizationSet out_params;
5566 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5567 string ciphertext;
5568 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5569 EXPECT_EQ(0U, ciphertext.size());
5570
5571 CheckedDeleteKey();
5572 }
Selene Huang31ab4042020-04-29 04:22:39 -07005573}
5574
5575/*
5576 * EncryptionOperationsTest.AesEcbPkcs7Padding
5577 *
5578 * Verifies that AES PKCS7 padding works for any message length.
5579 */
5580TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5581 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5582 .Authorization(TAG_NO_AUTH_REQUIRED)
5583 .AesEncryptionKey(128)
5584 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5585 .Padding(PaddingMode::PKCS7)));
5586
5587 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5588
5589 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005590 for (size_t i = 0; i <= 48; i++) {
5591 SCOPED_TRACE(testing::Message() << "i = " << i);
5592 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5593 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005594 string ciphertext = EncryptMessage(message, params);
5595 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5596 string plaintext = DecryptMessage(ciphertext, params);
5597 EXPECT_EQ(message, plaintext);
5598 }
5599}
5600
5601/*
5602 * EncryptionOperationsTest.AesEcbWrongPadding
5603 *
5604 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5605 * specified.
5606 */
5607TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5608 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5609 .Authorization(TAG_NO_AUTH_REQUIRED)
5610 .AesEncryptionKey(128)
5611 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5612 .Padding(PaddingMode::NONE)));
5613
5614 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5615
5616 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005617 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005618 string message(i, 'a');
5619 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5620 }
5621}
5622
5623/*
5624 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5625 *
5626 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5627 */
5628TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5629 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5630 .Authorization(TAG_NO_AUTH_REQUIRED)
5631 .AesEncryptionKey(128)
5632 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5633 .Padding(PaddingMode::PKCS7)));
5634
5635 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5636
5637 string message = "a";
5638 string ciphertext = EncryptMessage(message, params);
5639 EXPECT_EQ(16U, ciphertext.size());
5640 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005641
Seth Moore7a55ae32021-06-23 14:28:11 -07005642 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5643 ++ciphertext[ciphertext.size() / 2];
5644
5645 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5646 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005647 ErrorCode error = Finish(ciphertext, &plaintext);
5648 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005649 // This is the expected error, we can exit the test now.
5650 return;
5651 } else {
5652 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005653 ASSERT_EQ(error, ErrorCode::OK)
5654 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005655 }
5656 }
5657 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005658}
5659
David Drysdaleb8093292022-04-08 12:22:35 +01005660/*
5661 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5662 *
5663 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5664 */
5665TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5666 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5667 .Authorization(TAG_NO_AUTH_REQUIRED)
5668 .AesEncryptionKey(128)
5669 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5670 .Padding(PaddingMode::PKCS7)));
5671
5672 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5673
5674 string message = "a";
5675 string ciphertext = EncryptMessage(message, params);
5676 EXPECT_EQ(16U, ciphertext.size());
5677 EXPECT_NE(ciphertext, message);
5678
5679 // Shorten the ciphertext.
5680 ciphertext.resize(ciphertext.size() - 1);
5681 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5682 string plaintext;
5683 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5684}
5685
Selene Huang31ab4042020-04-29 04:22:39 -07005686vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5687 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005688 EXPECT_TRUE(iv);
5689 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005690}
5691
5692/*
5693 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5694 *
5695 * Verifies that AES CTR mode works.
5696 */
5697TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5698 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5699 .Authorization(TAG_NO_AUTH_REQUIRED)
5700 .AesEncryptionKey(128)
5701 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5702 .Padding(PaddingMode::NONE)));
5703
5704 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5705
5706 string message = "123";
5707 AuthorizationSet out_params;
5708 string ciphertext1 = EncryptMessage(message, params, &out_params);
5709 vector<uint8_t> iv1 = CopyIv(out_params);
5710 EXPECT_EQ(16U, iv1.size());
5711
5712 EXPECT_EQ(message.size(), ciphertext1.size());
5713
5714 out_params.Clear();
5715 string ciphertext2 = EncryptMessage(message, params, &out_params);
5716 vector<uint8_t> iv2 = CopyIv(out_params);
5717 EXPECT_EQ(16U, iv2.size());
5718
5719 // IVs should be random, so ciphertexts should differ.
5720 EXPECT_NE(ciphertext1, ciphertext2);
5721
5722 auto params_iv1 =
5723 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5724 auto params_iv2 =
5725 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5726
5727 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5728 EXPECT_EQ(message, plaintext);
5729 plaintext = DecryptMessage(ciphertext2, params_iv2);
5730 EXPECT_EQ(message, plaintext);
5731
5732 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5733 plaintext = DecryptMessage(ciphertext1, params_iv2);
5734 EXPECT_NE(message, plaintext);
5735 plaintext = DecryptMessage(ciphertext2, params_iv1);
5736 EXPECT_NE(message, plaintext);
5737}
5738
5739/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305740 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07005741 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305742 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07005743 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305744TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5745 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5746}
Selene Huang31ab4042020-04-29 04:22:39 -07005747
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305748/*
5749 * EncryptionOperationsTest.AesCbcIncremental
5750 *
5751 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5752 */
5753TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5754 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5755}
Selene Huang31ab4042020-04-29 04:22:39 -07005756
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305757/*
5758 * EncryptionOperationsTest.AesCtrIncremental
5759 *
5760 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5761 */
5762TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5763 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5764}
Selene Huang31ab4042020-04-29 04:22:39 -07005765
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305766/*
5767 * EncryptionOperationsTest.AesGcmIncremental
5768 *
5769 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5770 */
5771TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5772 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07005773}
5774
5775struct AesCtrSp80038aTestVector {
5776 const char* key;
5777 const char* nonce;
5778 const char* plaintext;
5779 const char* ciphertext;
5780};
5781
5782// These test vectors are taken from
5783// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
5784static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
5785 // AES-128
5786 {
5787 "2b7e151628aed2a6abf7158809cf4f3c",
5788 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5789 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5790 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5791 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
5792 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
5793 },
5794 // AES-192
5795 {
5796 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
5797 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5798 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5799 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5800 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
5801 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
5802 },
5803 // AES-256
5804 {
5805 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
5806 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5807 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5808 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5809 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
5810 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
5811 },
5812};
5813
5814/*
5815 * EncryptionOperationsTest.AesCtrSp80038aTestVector
5816 *
5817 * Verifies AES CTR implementation against SP800-38A test vectors.
5818 */
5819TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
5820 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
5821 for (size_t i = 0; i < 3; i++) {
5822 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
5823 const string key = hex2str(test.key);
5824 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
5825 InvalidSizes.end())
5826 continue;
5827 const string nonce = hex2str(test.nonce);
5828 const string plaintext = hex2str(test.plaintext);
5829 const string ciphertext = hex2str(test.ciphertext);
5830 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
5831 }
5832}
5833
5834/*
5835 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
5836 *
5837 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
5838 */
5839TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
5840 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5841 .Authorization(TAG_NO_AUTH_REQUIRED)
5842 .AesEncryptionKey(128)
5843 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5844 .Padding(PaddingMode::PKCS7)));
5845 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5846 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5847}
5848
5849/*
5850 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
5851 *
5852 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5853 */
5854TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
5855 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5856 .Authorization(TAG_NO_AUTH_REQUIRED)
5857 .AesEncryptionKey(128)
5858 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5859 .Authorization(TAG_CALLER_NONCE)
5860 .Padding(PaddingMode::NONE)));
5861
5862 auto params = AuthorizationSetBuilder()
5863 .BlockMode(BlockMode::CTR)
5864 .Padding(PaddingMode::NONE)
5865 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
5866 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5867
5868 params = AuthorizationSetBuilder()
5869 .BlockMode(BlockMode::CTR)
5870 .Padding(PaddingMode::NONE)
5871 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
5872 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5873
5874 params = AuthorizationSetBuilder()
5875 .BlockMode(BlockMode::CTR)
5876 .Padding(PaddingMode::NONE)
5877 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
5878 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5879}
5880
5881/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005882 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07005883 *
5884 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5885 */
5886TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
5887 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5888 .Authorization(TAG_NO_AUTH_REQUIRED)
5889 .AesEncryptionKey(128)
5890 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5891 .Padding(PaddingMode::NONE)));
5892 // Two-block message.
5893 string message = "12345678901234567890123456789012";
5894 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5895 AuthorizationSet out_params;
5896 string ciphertext1 = EncryptMessage(message, params, &out_params);
5897 vector<uint8_t> iv1 = CopyIv(out_params);
5898 EXPECT_EQ(message.size(), ciphertext1.size());
5899
5900 out_params.Clear();
5901
5902 string ciphertext2 = EncryptMessage(message, params, &out_params);
5903 vector<uint8_t> iv2 = CopyIv(out_params);
5904 EXPECT_EQ(message.size(), ciphertext2.size());
5905
5906 // IVs should be random, so ciphertexts should differ.
5907 EXPECT_NE(ciphertext1, ciphertext2);
5908
5909 params.push_back(TAG_NONCE, iv1);
5910 string plaintext = DecryptMessage(ciphertext1, params);
5911 EXPECT_EQ(message, plaintext);
5912}
5913
5914/*
Tommy Chiuee705692021-09-23 20:09:13 +08005915 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
5916 *
5917 * Verifies that keymaster generates correct output on zero-input with
5918 * NonePadding mode
5919 */
5920TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
5921 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5922 .Authorization(TAG_NO_AUTH_REQUIRED)
5923 .AesEncryptionKey(128)
5924 .BlockMode(BlockMode::CBC)
5925 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
5926
5927 // Zero input message
5928 string message = "";
5929 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
5930 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
5931 AuthorizationSet out_params;
5932 string ciphertext1 = EncryptMessage(message, params, &out_params);
5933 vector<uint8_t> iv1 = CopyIv(out_params);
5934 if (padding == PaddingMode::NONE)
5935 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
5936 else
5937 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
5938
5939 out_params.Clear();
5940
5941 string ciphertext2 = EncryptMessage(message, params, &out_params);
5942 vector<uint8_t> iv2 = CopyIv(out_params);
5943 if (padding == PaddingMode::NONE)
5944 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
5945 else
5946 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
5947
5948 // IVs should be random
5949 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
5950
5951 params.push_back(TAG_NONCE, iv1);
5952 string plaintext = DecryptMessage(ciphertext1, params);
5953 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
5954 }
5955}
5956
5957/*
Selene Huang31ab4042020-04-29 04:22:39 -07005958 * EncryptionOperationsTest.AesCallerNonce
5959 *
5960 * Verifies that AES caller-provided nonces work correctly.
5961 */
5962TEST_P(EncryptionOperationsTest, AesCallerNonce) {
5963 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5964 .Authorization(TAG_NO_AUTH_REQUIRED)
5965 .AesEncryptionKey(128)
5966 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5967 .Authorization(TAG_CALLER_NONCE)
5968 .Padding(PaddingMode::NONE)));
5969
5970 string message = "12345678901234567890123456789012";
5971
5972 // Don't specify nonce, should get a random one.
5973 AuthorizationSetBuilder params =
5974 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5975 AuthorizationSet out_params;
5976 string ciphertext = EncryptMessage(message, params, &out_params);
5977 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005978 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005979
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005980 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005981 string plaintext = DecryptMessage(ciphertext, params);
5982 EXPECT_EQ(message, plaintext);
5983
5984 // Now specify a nonce, should also work.
5985 params = AuthorizationSetBuilder()
5986 .BlockMode(BlockMode::CBC)
5987 .Padding(PaddingMode::NONE)
5988 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5989 out_params.Clear();
5990 ciphertext = EncryptMessage(message, params, &out_params);
5991
5992 // Decrypt with correct nonce.
5993 plaintext = DecryptMessage(ciphertext, params);
5994 EXPECT_EQ(message, plaintext);
5995
5996 // Try with wrong nonce.
5997 params = AuthorizationSetBuilder()
5998 .BlockMode(BlockMode::CBC)
5999 .Padding(PaddingMode::NONE)
6000 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6001 plaintext = DecryptMessage(ciphertext, params);
6002 EXPECT_NE(message, plaintext);
6003}
6004
6005/*
6006 * EncryptionOperationsTest.AesCallerNonceProhibited
6007 *
6008 * Verifies that caller-provided nonces are not permitted when not specified in the key
6009 * authorizations.
6010 */
6011TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6012 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6013 .Authorization(TAG_NO_AUTH_REQUIRED)
6014 .AesEncryptionKey(128)
6015 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6016 .Padding(PaddingMode::NONE)));
6017
6018 string message = "12345678901234567890123456789012";
6019
6020 // Don't specify nonce, should get a random one.
6021 AuthorizationSetBuilder params =
6022 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6023 AuthorizationSet out_params;
6024 string ciphertext = EncryptMessage(message, params, &out_params);
6025 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006026 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006027
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006028 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006029 string plaintext = DecryptMessage(ciphertext, params);
6030 EXPECT_EQ(message, plaintext);
6031
6032 // Now specify a nonce, should fail
6033 params = AuthorizationSetBuilder()
6034 .BlockMode(BlockMode::CBC)
6035 .Padding(PaddingMode::NONE)
6036 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6037 out_params.Clear();
6038 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6039}
6040
6041/*
6042 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6043 *
6044 * Verifies that AES GCM mode works.
6045 */
6046TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6047 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6048 .Authorization(TAG_NO_AUTH_REQUIRED)
6049 .AesEncryptionKey(128)
6050 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6051 .Padding(PaddingMode::NONE)
6052 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6053
6054 string aad = "foobar";
6055 string message = "123456789012345678901234567890123456";
6056
6057 auto begin_params = AuthorizationSetBuilder()
6058 .BlockMode(BlockMode::GCM)
6059 .Padding(PaddingMode::NONE)
6060 .Authorization(TAG_MAC_LENGTH, 128);
6061
Selene Huang31ab4042020-04-29 04:22:39 -07006062 // Encrypt
6063 AuthorizationSet begin_out_params;
6064 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6065 << "Begin encrypt";
6066 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006067 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6068 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006069 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6070
6071 // Grab nonce
6072 begin_params.push_back(begin_out_params);
6073
6074 // Decrypt.
6075 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006076 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006077 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006078 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006079 EXPECT_EQ(message.length(), plaintext.length());
6080 EXPECT_EQ(message, plaintext);
6081}
6082
6083/*
6084 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6085 *
6086 * Verifies that AES GCM mode works, even when there's a long delay
6087 * between operations.
6088 */
6089TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6090 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6091 .Authorization(TAG_NO_AUTH_REQUIRED)
6092 .AesEncryptionKey(128)
6093 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6094 .Padding(PaddingMode::NONE)
6095 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6096
6097 string aad = "foobar";
6098 string message = "123456789012345678901234567890123456";
6099
6100 auto begin_params = AuthorizationSetBuilder()
6101 .BlockMode(BlockMode::GCM)
6102 .Padding(PaddingMode::NONE)
6103 .Authorization(TAG_MAC_LENGTH, 128);
6104
Selene Huang31ab4042020-04-29 04:22:39 -07006105 // Encrypt
6106 AuthorizationSet begin_out_params;
6107 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6108 << "Begin encrypt";
6109 string ciphertext;
6110 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006111 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006112 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006113 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006114
6115 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6116
6117 // Grab nonce
6118 begin_params.push_back(begin_out_params);
6119
6120 // Decrypt.
6121 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6122 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006123 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006124 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006125 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006126 sleep(5);
6127 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6128 EXPECT_EQ(message.length(), plaintext.length());
6129 EXPECT_EQ(message, plaintext);
6130}
6131
6132/*
6133 * EncryptionOperationsTest.AesGcmDifferentNonces
6134 *
6135 * Verifies that encrypting the same data with different nonces produces different outputs.
6136 */
6137TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6138 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6139 .Authorization(TAG_NO_AUTH_REQUIRED)
6140 .AesEncryptionKey(128)
6141 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6142 .Padding(PaddingMode::NONE)
6143 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6144 .Authorization(TAG_CALLER_NONCE)));
6145
6146 string aad = "foobar";
6147 string message = "123456789012345678901234567890123456";
6148 string nonce1 = "000000000000";
6149 string nonce2 = "111111111111";
6150 string nonce3 = "222222222222";
6151
6152 string ciphertext1 =
6153 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6154 string ciphertext2 =
6155 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6156 string ciphertext3 =
6157 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6158
6159 ASSERT_NE(ciphertext1, ciphertext2);
6160 ASSERT_NE(ciphertext1, ciphertext3);
6161 ASSERT_NE(ciphertext2, ciphertext3);
6162}
6163
6164/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006165 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6166 *
6167 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6168 */
6169TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6170 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6171 .Authorization(TAG_NO_AUTH_REQUIRED)
6172 .AesEncryptionKey(128)
6173 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6174 .Padding(PaddingMode::NONE)
6175 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6176
6177 string aad = "foobar";
6178 string message = "123456789012345678901234567890123456";
6179
6180 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6181 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6182 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6183
6184 ASSERT_NE(ciphertext1, ciphertext2);
6185 ASSERT_NE(ciphertext1, ciphertext3);
6186 ASSERT_NE(ciphertext2, ciphertext3);
6187}
6188
6189/*
Selene Huang31ab4042020-04-29 04:22:39 -07006190 * EncryptionOperationsTest.AesGcmTooShortTag
6191 *
6192 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6193 */
6194TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6195 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6196 .Authorization(TAG_NO_AUTH_REQUIRED)
6197 .AesEncryptionKey(128)
6198 .BlockMode(BlockMode::GCM)
6199 .Padding(PaddingMode::NONE)
6200 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6201 string message = "123456789012345678901234567890123456";
6202 auto params = AuthorizationSetBuilder()
6203 .BlockMode(BlockMode::GCM)
6204 .Padding(PaddingMode::NONE)
6205 .Authorization(TAG_MAC_LENGTH, 96);
6206
6207 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6208}
6209
6210/*
6211 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6212 *
6213 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6214 */
6215TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6216 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6217 .Authorization(TAG_NO_AUTH_REQUIRED)
6218 .AesEncryptionKey(128)
6219 .BlockMode(BlockMode::GCM)
6220 .Padding(PaddingMode::NONE)
6221 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6222 string aad = "foobar";
6223 string message = "123456789012345678901234567890123456";
6224 auto params = AuthorizationSetBuilder()
6225 .BlockMode(BlockMode::GCM)
6226 .Padding(PaddingMode::NONE)
6227 .Authorization(TAG_MAC_LENGTH, 128);
6228
Selene Huang31ab4042020-04-29 04:22:39 -07006229 // Encrypt
6230 AuthorizationSet begin_out_params;
6231 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6232 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006233 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006234
6235 AuthorizationSet finish_out_params;
6236 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006237 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6238 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006239
6240 params = AuthorizationSetBuilder()
6241 .Authorizations(begin_out_params)
6242 .BlockMode(BlockMode::GCM)
6243 .Padding(PaddingMode::NONE)
6244 .Authorization(TAG_MAC_LENGTH, 96);
6245
6246 // Decrypt.
6247 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6248}
6249
6250/*
6251 * EncryptionOperationsTest.AesGcmCorruptKey
6252 *
6253 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6254 */
6255TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6256 const uint8_t nonce_bytes[] = {
6257 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6258 };
6259 string nonce = make_string(nonce_bytes);
6260 const uint8_t ciphertext_bytes[] = {
6261 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6262 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6263 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6264 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6265 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6266 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6267 };
6268 string ciphertext = make_string(ciphertext_bytes);
6269
6270 auto params = AuthorizationSetBuilder()
6271 .BlockMode(BlockMode::GCM)
6272 .Padding(PaddingMode::NONE)
6273 .Authorization(TAG_MAC_LENGTH, 128)
6274 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6275
6276 auto import_params = AuthorizationSetBuilder()
6277 .Authorization(TAG_NO_AUTH_REQUIRED)
6278 .AesEncryptionKey(128)
6279 .BlockMode(BlockMode::GCM)
6280 .Padding(PaddingMode::NONE)
6281 .Authorization(TAG_CALLER_NONCE)
6282 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6283
6284 // Import correct key and decrypt
6285 const uint8_t key_bytes[] = {
6286 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6287 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6288 };
6289 string key = make_string(key_bytes);
6290 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6291 string plaintext = DecryptMessage(ciphertext, params);
6292 CheckedDeleteKey();
6293
6294 // Corrupt key and attempt to decrypt
6295 key[0] = 0;
6296 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6297 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6298 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6299 CheckedDeleteKey();
6300}
6301
6302/*
6303 * EncryptionOperationsTest.AesGcmAadNoData
6304 *
6305 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6306 * encrypt.
6307 */
6308TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6309 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6310 .Authorization(TAG_NO_AUTH_REQUIRED)
6311 .AesEncryptionKey(128)
6312 .BlockMode(BlockMode::GCM)
6313 .Padding(PaddingMode::NONE)
6314 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6315
6316 string aad = "1234567890123456";
6317 auto params = AuthorizationSetBuilder()
6318 .BlockMode(BlockMode::GCM)
6319 .Padding(PaddingMode::NONE)
6320 .Authorization(TAG_MAC_LENGTH, 128);
6321
Selene Huang31ab4042020-04-29 04:22:39 -07006322 // Encrypt
6323 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006324 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006325 string ciphertext;
6326 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006327 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6328 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006329 EXPECT_TRUE(finish_out_params.empty());
6330
6331 // Grab nonce
6332 params.push_back(begin_out_params);
6333
6334 // Decrypt.
6335 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006336 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006337 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006338 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006339
6340 EXPECT_TRUE(finish_out_params.empty());
6341
6342 EXPECT_EQ("", plaintext);
6343}
6344
6345/*
6346 * EncryptionOperationsTest.AesGcmMultiPartAad
6347 *
6348 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6349 * chunks.
6350 */
6351TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6352 const size_t tag_bits = 128;
6353 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6354 .Authorization(TAG_NO_AUTH_REQUIRED)
6355 .AesEncryptionKey(128)
6356 .BlockMode(BlockMode::GCM)
6357 .Padding(PaddingMode::NONE)
6358 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6359
6360 string message = "123456789012345678901234567890123456";
6361 auto begin_params = AuthorizationSetBuilder()
6362 .BlockMode(BlockMode::GCM)
6363 .Padding(PaddingMode::NONE)
6364 .Authorization(TAG_MAC_LENGTH, tag_bits);
6365 AuthorizationSet begin_out_params;
6366
David Drysdale7fc26b92022-05-13 09:54:24 +01006367 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006368
6369 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006370 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6371 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006372 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006373 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6374 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006375
Selene Huang31ab4042020-04-29 04:22:39 -07006376 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006377 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006378
6379 // Grab nonce.
6380 begin_params.push_back(begin_out_params);
6381
6382 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01006383 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006384 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006385 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006386 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006387 EXPECT_EQ(message, plaintext);
6388}
6389
6390/*
6391 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6392 *
6393 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6394 */
6395TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6396 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6397 .Authorization(TAG_NO_AUTH_REQUIRED)
6398 .AesEncryptionKey(128)
6399 .BlockMode(BlockMode::GCM)
6400 .Padding(PaddingMode::NONE)
6401 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6402
6403 string message = "123456789012345678901234567890123456";
6404 auto begin_params = AuthorizationSetBuilder()
6405 .BlockMode(BlockMode::GCM)
6406 .Padding(PaddingMode::NONE)
6407 .Authorization(TAG_MAC_LENGTH, 128);
6408 AuthorizationSet begin_out_params;
6409
David Drysdale7fc26b92022-05-13 09:54:24 +01006410 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006411
Shawn Willden92d79c02021-02-19 07:31:55 -07006412 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006413 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006414 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6415 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006416
David Drysdaled2cc8c22021-04-15 13:29:45 +01006417 // The failure should have already cancelled the operation.
6418 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6419
Shawn Willden92d79c02021-02-19 07:31:55 -07006420 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006421}
6422
6423/*
6424 * EncryptionOperationsTest.AesGcmBadAad
6425 *
6426 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6427 */
6428TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6429 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6430 .Authorization(TAG_NO_AUTH_REQUIRED)
6431 .AesEncryptionKey(128)
6432 .BlockMode(BlockMode::GCM)
6433 .Padding(PaddingMode::NONE)
6434 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6435
6436 string message = "12345678901234567890123456789012";
6437 auto begin_params = AuthorizationSetBuilder()
6438 .BlockMode(BlockMode::GCM)
6439 .Padding(PaddingMode::NONE)
6440 .Authorization(TAG_MAC_LENGTH, 128);
6441
Selene Huang31ab4042020-04-29 04:22:39 -07006442 // Encrypt
6443 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006444 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006445 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006446 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006447 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006448
6449 // Grab nonce
6450 begin_params.push_back(begin_out_params);
6451
Selene Huang31ab4042020-04-29 04:22:39 -07006452 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006453 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006454 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006455 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006456 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006457}
6458
6459/*
6460 * EncryptionOperationsTest.AesGcmWrongNonce
6461 *
6462 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6463 */
6464TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6465 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6466 .Authorization(TAG_NO_AUTH_REQUIRED)
6467 .AesEncryptionKey(128)
6468 .BlockMode(BlockMode::GCM)
6469 .Padding(PaddingMode::NONE)
6470 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6471
6472 string message = "12345678901234567890123456789012";
6473 auto begin_params = AuthorizationSetBuilder()
6474 .BlockMode(BlockMode::GCM)
6475 .Padding(PaddingMode::NONE)
6476 .Authorization(TAG_MAC_LENGTH, 128);
6477
Selene Huang31ab4042020-04-29 04:22:39 -07006478 // Encrypt
6479 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006480 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006481 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006482 string ciphertext;
6483 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006484 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006485
6486 // Wrong nonce
6487 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6488
6489 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006490 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006491 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006492 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006493 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006494
6495 // With wrong nonce, should have gotten garbage plaintext (or none).
6496 EXPECT_NE(message, plaintext);
6497}
6498
6499/*
6500 * EncryptionOperationsTest.AesGcmCorruptTag
6501 *
6502 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6503 */
6504TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6505 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6506 .Authorization(TAG_NO_AUTH_REQUIRED)
6507 .AesEncryptionKey(128)
6508 .BlockMode(BlockMode::GCM)
6509 .Padding(PaddingMode::NONE)
6510 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6511
6512 string aad = "1234567890123456";
6513 string message = "123456789012345678901234567890123456";
6514
6515 auto params = AuthorizationSetBuilder()
6516 .BlockMode(BlockMode::GCM)
6517 .Padding(PaddingMode::NONE)
6518 .Authorization(TAG_MAC_LENGTH, 128);
6519
Selene Huang31ab4042020-04-29 04:22:39 -07006520 // Encrypt
6521 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006522 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006523 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006524 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006525 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006526
6527 // Corrupt tag
6528 ++(*ciphertext.rbegin());
6529
6530 // Grab nonce
6531 params.push_back(begin_out_params);
6532
6533 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006534 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006535 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006536 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006537 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006538}
6539
6540/*
6541 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
6542 *
6543 * Verifies that 3DES is basically functional.
6544 */
6545TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
6546 auto auths = AuthorizationSetBuilder()
6547 .TripleDesEncryptionKey(168)
6548 .BlockMode(BlockMode::ECB)
6549 .Authorization(TAG_NO_AUTH_REQUIRED)
6550 .Padding(PaddingMode::NONE);
6551
6552 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
6553 // Two-block message.
6554 string message = "1234567890123456";
6555 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6556 string ciphertext1 = EncryptMessage(message, inParams);
6557 EXPECT_EQ(message.size(), ciphertext1.size());
6558
6559 string ciphertext2 = EncryptMessage(string(message), inParams);
6560 EXPECT_EQ(message.size(), ciphertext2.size());
6561
6562 // ECB is deterministic.
6563 EXPECT_EQ(ciphertext1, ciphertext2);
6564
6565 string plaintext = DecryptMessage(ciphertext1, inParams);
6566 EXPECT_EQ(message, plaintext);
6567}
6568
6569/*
6570 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
6571 *
6572 * Verifies that CBC keys reject ECB usage.
6573 */
6574TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
6575 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6576 .TripleDesEncryptionKey(168)
6577 .BlockMode(BlockMode::CBC)
6578 .Authorization(TAG_NO_AUTH_REQUIRED)
6579 .Padding(PaddingMode::NONE)));
6580
6581 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6582 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
6583}
6584
6585/*
6586 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
6587 *
6588 * Tests ECB mode with PKCS#7 padding, various message sizes.
6589 */
6590TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
6591 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6592 .TripleDesEncryptionKey(168)
6593 .BlockMode(BlockMode::ECB)
6594 .Authorization(TAG_NO_AUTH_REQUIRED)
6595 .Padding(PaddingMode::PKCS7)));
6596
6597 for (size_t i = 0; i < 32; ++i) {
6598 string message(i, 'a');
6599 auto inParams =
6600 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6601 string ciphertext = EncryptMessage(message, inParams);
6602 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6603 string plaintext = DecryptMessage(ciphertext, inParams);
6604 EXPECT_EQ(message, plaintext);
6605 }
6606}
6607
6608/*
6609 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
6610 *
6611 * Verifies that keys configured for no padding reject PKCS7 padding
6612 */
6613TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
6614 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6615 .TripleDesEncryptionKey(168)
6616 .BlockMode(BlockMode::ECB)
6617 .Authorization(TAG_NO_AUTH_REQUIRED)
6618 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00006619 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6620 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07006621}
6622
6623/*
6624 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
6625 *
6626 * Verifies that corrupted padding is detected.
6627 */
6628TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
6629 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6630 .TripleDesEncryptionKey(168)
6631 .BlockMode(BlockMode::ECB)
6632 .Authorization(TAG_NO_AUTH_REQUIRED)
6633 .Padding(PaddingMode::PKCS7)));
6634
6635 string message = "a";
6636 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
6637 EXPECT_EQ(8U, ciphertext.size());
6638 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006639
6640 AuthorizationSetBuilder begin_params;
6641 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
6642 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07006643
6644 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
6645 ++ciphertext[ciphertext.size() / 2];
6646
David Drysdale7fc26b92022-05-13 09:54:24 +01006647 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07006648 string plaintext;
6649 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6650 ErrorCode error = Finish(&plaintext);
6651 if (error == ErrorCode::INVALID_ARGUMENT) {
6652 // This is the expected error, we can exit the test now.
6653 return;
6654 } else {
6655 // Very small chance we got valid decryption, so try again.
6656 ASSERT_EQ(error, ErrorCode::OK);
6657 }
6658 }
6659 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006660}
6661
6662struct TripleDesTestVector {
6663 const char* name;
6664 const KeyPurpose purpose;
6665 const BlockMode block_mode;
6666 const PaddingMode padding_mode;
6667 const char* key;
6668 const char* iv;
6669 const char* input;
6670 const char* output;
6671};
6672
6673// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
6674// of the NIST vectors are multiples of the block size.
6675static const TripleDesTestVector kTripleDesTestVectors[] = {
6676 {
6677 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6678 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
6679 "", // IV
6680 "329d86bdf1bc5af4", // input
6681 "d946c2756d78633f", // output
6682 },
6683 {
6684 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6685 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
6686 "", // IV
6687 "6b1540781b01ce1997adae102dbf3c5b", // input
6688 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
6689 },
6690 {
6691 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6692 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
6693 "", // IV
6694 "6daad94ce08acfe7", // input
6695 "660e7d32dcc90e79", // output
6696 },
6697 {
6698 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6699 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
6700 "", // IV
6701 "e9653a0a1f05d31b9acd12d73aa9879d", // input
6702 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
6703 },
6704 {
6705 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6706 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
6707 "43f791134c5647ba", // IV
6708 "dcc153cef81d6f24", // input
6709 "92538bd8af18d3ba", // output
6710 },
6711 {
6712 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6713 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6714 "c2e999cb6249023c", // IV
6715 "c689aee38a301bb316da75db36f110b5", // input
6716 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
6717 },
6718 {
6719 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
6720 PaddingMode::PKCS7,
6721 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6722 "c2e999cb6249023c", // IV
6723 "c689aee38a301bb316da75db36f110b500", // input
6724 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
6725 },
6726 {
6727 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
6728 PaddingMode::PKCS7,
6729 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6730 "c2e999cb6249023c", // IV
6731 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
6732 "c689aee38a301bb316da75db36f110b500", // output
6733 },
6734 {
6735 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6736 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
6737 "41746c7e442d3681", // IV
6738 "c53a7b0ec40600fe", // input
6739 "d4f00eb455de1034", // output
6740 },
6741 {
6742 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6743 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
6744 "3982bc02c3727d45", // IV
6745 "6006f10adef52991fcc777a1238bbb65", // input
6746 "edae09288e9e3bc05746d872b48e3b29", // output
6747 },
6748};
6749
6750/*
6751 * EncryptionOperationsTest.TripleDesTestVector
6752 *
6753 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
6754 */
6755TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
6756 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
6757 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
6758 SCOPED_TRACE(test->name);
6759 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
6760 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
6761 hex2str(test->output));
6762 }
6763}
6764
6765/*
6766 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
6767 *
6768 * Validates CBC mode functionality.
6769 */
6770TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
6771 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6772 .TripleDesEncryptionKey(168)
6773 .BlockMode(BlockMode::CBC)
6774 .Authorization(TAG_NO_AUTH_REQUIRED)
6775 .Padding(PaddingMode::NONE)));
6776
6777 ASSERT_GT(key_blob_.size(), 0U);
6778
Brian J Murray734c8412022-01-13 14:55:30 -08006779 // Four-block message.
6780 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07006781 vector<uint8_t> iv1;
6782 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
6783 EXPECT_EQ(message.size(), ciphertext1.size());
6784
6785 vector<uint8_t> iv2;
6786 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
6787 EXPECT_EQ(message.size(), ciphertext2.size());
6788
6789 // IVs should be random, so ciphertexts should differ.
6790 EXPECT_NE(iv1, iv2);
6791 EXPECT_NE(ciphertext1, ciphertext2);
6792
6793 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
6794 EXPECT_EQ(message, plaintext);
6795}
6796
6797/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006798 * EncryptionOperationsTest.TripleDesInvalidCallerIv
6799 *
6800 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
6801 */
6802TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
6803 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6804 .TripleDesEncryptionKey(168)
6805 .BlockMode(BlockMode::CBC)
6806 .Authorization(TAG_NO_AUTH_REQUIRED)
6807 .Authorization(TAG_CALLER_NONCE)
6808 .Padding(PaddingMode::NONE)));
6809 auto params = AuthorizationSetBuilder()
6810 .BlockMode(BlockMode::CBC)
6811 .Padding(PaddingMode::NONE)
6812 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
6813 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6814}
6815
6816/*
Selene Huang31ab4042020-04-29 04:22:39 -07006817 * EncryptionOperationsTest.TripleDesCallerIv
6818 *
6819 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
6820 */
6821TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
6822 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6823 .TripleDesEncryptionKey(168)
6824 .BlockMode(BlockMode::CBC)
6825 .Authorization(TAG_NO_AUTH_REQUIRED)
6826 .Authorization(TAG_CALLER_NONCE)
6827 .Padding(PaddingMode::NONE)));
6828 string message = "1234567890123456";
6829 vector<uint8_t> iv;
6830 // Don't specify IV, should get a random one.
6831 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6832 EXPECT_EQ(message.size(), ciphertext1.size());
6833 EXPECT_EQ(8U, iv.size());
6834
6835 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6836 EXPECT_EQ(message, plaintext);
6837
6838 // Now specify an IV, should also work.
6839 iv = AidlBuf("abcdefgh");
6840 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
6841
6842 // Decrypt with correct IV.
6843 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
6844 EXPECT_EQ(message, plaintext);
6845
6846 // Now try with wrong IV.
6847 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
6848 EXPECT_NE(message, plaintext);
6849}
6850
6851/*
6852 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
6853 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01006854 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07006855 */
6856TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
6857 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6858 .TripleDesEncryptionKey(168)
6859 .BlockMode(BlockMode::CBC)
6860 .Authorization(TAG_NO_AUTH_REQUIRED)
6861 .Padding(PaddingMode::NONE)));
6862
6863 string message = "12345678901234567890123456789012";
6864 vector<uint8_t> iv;
6865 // Don't specify nonce, should get a random one.
6866 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6867 EXPECT_EQ(message.size(), ciphertext1.size());
6868 EXPECT_EQ(8U, iv.size());
6869
6870 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6871 EXPECT_EQ(message, plaintext);
6872
6873 // Now specify a nonce, should fail.
6874 auto input_params = AuthorizationSetBuilder()
6875 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
6876 .BlockMode(BlockMode::CBC)
6877 .Padding(PaddingMode::NONE);
6878 AuthorizationSet output_params;
6879 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
6880 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6881}
6882
6883/*
6884 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
6885 *
6886 * Verifies that 3DES ECB-only keys do not allow CBC usage.
6887 */
6888TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
6889 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6890 .TripleDesEncryptionKey(168)
6891 .BlockMode(BlockMode::ECB)
6892 .Authorization(TAG_NO_AUTH_REQUIRED)
6893 .Padding(PaddingMode::NONE)));
6894 // Two-block message.
6895 string message = "1234567890123456";
6896 auto begin_params =
6897 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6898 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6899}
6900
6901/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006902 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07006903 *
6904 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
6905 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01006906TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
6907 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
6908 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6909 .TripleDesEncryptionKey(168)
6910 .BlockMode(blockMode)
6911 .Authorization(TAG_NO_AUTH_REQUIRED)
6912 .Padding(PaddingMode::NONE)));
6913 // Message is slightly shorter than two blocks.
6914 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07006915
David Drysdaled2cc8c22021-04-15 13:29:45 +01006916 auto begin_params =
6917 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
6918 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006919 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01006920 string ciphertext;
6921 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
6922
6923 CheckedDeleteKey();
6924 }
Selene Huang31ab4042020-04-29 04:22:39 -07006925}
6926
6927/*
6928 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
6929 *
6930 * Verifies that PKCS7 padding works correctly in CBC mode.
6931 */
6932TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
6933 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6934 .TripleDesEncryptionKey(168)
6935 .BlockMode(BlockMode::CBC)
6936 .Authorization(TAG_NO_AUTH_REQUIRED)
6937 .Padding(PaddingMode::PKCS7)));
6938
6939 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08006940 for (size_t i = 0; i <= 32; i++) {
6941 SCOPED_TRACE(testing::Message() << "i = " << i);
6942 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
6943 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07006944 vector<uint8_t> iv;
6945 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6946 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6947 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
6948 EXPECT_EQ(message, plaintext);
6949 }
6950}
6951
6952/*
6953 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
6954 *
6955 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
6956 */
6957TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
6958 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6959 .TripleDesEncryptionKey(168)
6960 .BlockMode(BlockMode::CBC)
6961 .Authorization(TAG_NO_AUTH_REQUIRED)
6962 .Padding(PaddingMode::NONE)));
6963
6964 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08006965 for (size_t i = 0; i <= 32; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07006966 auto begin_params =
6967 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
6968 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6969 }
6970}
6971
6972/*
6973 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
6974 *
6975 * Verifies that corrupted PKCS7 padding is rejected during decryption.
6976 */
6977TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
6978 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6979 .TripleDesEncryptionKey(168)
6980 .BlockMode(BlockMode::CBC)
6981 .Authorization(TAG_NO_AUTH_REQUIRED)
6982 .Padding(PaddingMode::PKCS7)));
6983
6984 string message = "a";
6985 vector<uint8_t> iv;
6986 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6987 EXPECT_EQ(8U, ciphertext.size());
6988 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006989
6990 auto begin_params = AuthorizationSetBuilder()
6991 .BlockMode(BlockMode::CBC)
6992 .Padding(PaddingMode::PKCS7)
6993 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07006994
6995 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08006996 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07006997 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01006998 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07006999 string plaintext;
7000 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7001 ErrorCode error = Finish(&plaintext);
7002 if (error == ErrorCode::INVALID_ARGUMENT) {
7003 // This is the expected error, we can exit the test now.
7004 return;
7005 } else {
7006 // Very small chance we got valid decryption, so try again.
7007 ASSERT_EQ(error, ErrorCode::OK);
7008 }
7009 }
7010 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007011}
7012
7013/*
7014 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7015 *
7016 * Verifies that 3DES CBC works with many different input sizes.
7017 */
7018TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7019 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7020 .TripleDesEncryptionKey(168)
7021 .BlockMode(BlockMode::CBC)
7022 .Authorization(TAG_NO_AUTH_REQUIRED)
7023 .Padding(PaddingMode::NONE)));
7024
7025 int increment = 7;
7026 string message(240, 'a');
7027 AuthorizationSet input_params =
7028 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7029 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007030 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007031
7032 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007033 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007034 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007035 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7036 EXPECT_EQ(message.size(), ciphertext.size());
7037
7038 // Move TAG_NONCE into input_params
7039 input_params = output_params;
7040 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7041 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7042 output_params.Clear();
7043
David Drysdale7fc26b92022-05-13 09:54:24 +01007044 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007045 string plaintext;
7046 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007047 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007048 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7049 EXPECT_EQ(ciphertext.size(), plaintext.size());
7050 EXPECT_EQ(message, plaintext);
7051}
7052
7053INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7054
7055typedef KeyMintAidlTestBase MaxOperationsTest;
7056
7057/*
7058 * MaxOperationsTest.TestLimitAes
7059 *
7060 * Verifies that the max uses per boot tag works correctly with AES keys.
7061 */
7062TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007063 if (SecLevel() == SecurityLevel::STRONGBOX) {
7064 GTEST_SKIP() << "Test not applicable to StrongBox device";
7065 }
Selene Huang31ab4042020-04-29 04:22:39 -07007066
7067 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7068 .Authorization(TAG_NO_AUTH_REQUIRED)
7069 .AesEncryptionKey(128)
7070 .EcbMode()
7071 .Padding(PaddingMode::NONE)
7072 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7073
7074 string message = "1234567890123456";
7075
7076 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7077
7078 EncryptMessage(message, params);
7079 EncryptMessage(message, params);
7080 EncryptMessage(message, params);
7081
7082 // Fourth time should fail.
7083 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7084}
7085
7086/*
Qi Wud22ec842020-11-26 13:27:53 +08007087 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007088 *
7089 * Verifies that the max uses per boot tag works correctly with RSA keys.
7090 */
7091TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007092 if (SecLevel() == SecurityLevel::STRONGBOX) {
7093 GTEST_SKIP() << "Test not applicable to StrongBox device";
7094 }
Selene Huang31ab4042020-04-29 04:22:39 -07007095
7096 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7097 .Authorization(TAG_NO_AUTH_REQUIRED)
7098 .RsaSigningKey(1024, 65537)
7099 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007100 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7101 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007102
7103 string message = "1234567890123456";
7104
7105 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7106
7107 SignMessage(message, params);
7108 SignMessage(message, params);
7109 SignMessage(message, params);
7110
7111 // Fourth time should fail.
7112 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7113}
7114
7115INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7116
Qi Wud22ec842020-11-26 13:27:53 +08007117typedef KeyMintAidlTestBase UsageCountLimitTest;
7118
7119/*
Qi Wubeefae42021-01-28 23:16:37 +08007120 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007121 *
Qi Wubeefae42021-01-28 23:16:37 +08007122 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007123 */
Qi Wubeefae42021-01-28 23:16:37 +08007124TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007125 if (SecLevel() == SecurityLevel::STRONGBOX) {
7126 GTEST_SKIP() << "Test not applicable to StrongBox device";
7127 }
Qi Wud22ec842020-11-26 13:27:53 +08007128
7129 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7130 .Authorization(TAG_NO_AUTH_REQUIRED)
7131 .AesEncryptionKey(128)
7132 .EcbMode()
7133 .Padding(PaddingMode::NONE)
7134 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7135
7136 // Check the usage count limit tag appears in the authorizations.
7137 AuthorizationSet auths;
7138 for (auto& entry : key_characteristics_) {
7139 auths.push_back(AuthorizationSet(entry.authorizations));
7140 }
7141 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7142 << "key usage count limit " << 1U << " missing";
7143
7144 string message = "1234567890123456";
7145 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7146
Qi Wubeefae42021-01-28 23:16:37 +08007147 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7148 AuthorizationSet keystore_auths =
7149 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7150
Qi Wud22ec842020-11-26 13:27:53 +08007151 // First usage of AES key should work.
7152 EncryptMessage(message, params);
7153
Qi Wud22ec842020-11-26 13:27:53 +08007154 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7155 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7156 // must be invalidated from secure storage (such as RPMB partition).
7157 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7158 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007159 // Usage count limit tag is enforced by keystore, keymint does nothing.
7160 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007161 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007162 }
7163}
7164
7165/*
Qi Wubeefae42021-01-28 23:16:37 +08007166 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007167 *
Qi Wubeefae42021-01-28 23:16:37 +08007168 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007169 */
Qi Wubeefae42021-01-28 23:16:37 +08007170TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007171 if (SecLevel() == SecurityLevel::STRONGBOX) {
7172 GTEST_SKIP() << "Test not applicable to StrongBox device";
7173 }
Qi Wubeefae42021-01-28 23:16:37 +08007174
7175 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7176 .Authorization(TAG_NO_AUTH_REQUIRED)
7177 .AesEncryptionKey(128)
7178 .EcbMode()
7179 .Padding(PaddingMode::NONE)
7180 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7181
7182 // Check the usage count limit tag appears in the authorizations.
7183 AuthorizationSet auths;
7184 for (auto& entry : key_characteristics_) {
7185 auths.push_back(AuthorizationSet(entry.authorizations));
7186 }
7187 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7188 << "key usage count limit " << 3U << " missing";
7189
7190 string message = "1234567890123456";
7191 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7192
7193 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7194 AuthorizationSet keystore_auths =
7195 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7196
7197 EncryptMessage(message, params);
7198 EncryptMessage(message, params);
7199 EncryptMessage(message, params);
7200
7201 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7202 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7203 // must be invalidated from secure storage (such as RPMB partition).
7204 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7205 } else {
7206 // Usage count limit tag is enforced by keystore, keymint does nothing.
7207 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007208 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007209 }
7210}
7211
7212/*
7213 * UsageCountLimitTest.TestSingleUseRsa
7214 *
7215 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7216 */
7217TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007218 if (SecLevel() == SecurityLevel::STRONGBOX) {
7219 GTEST_SKIP() << "Test not applicable to StrongBox device";
7220 }
Qi Wud22ec842020-11-26 13:27:53 +08007221
7222 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7223 .Authorization(TAG_NO_AUTH_REQUIRED)
7224 .RsaSigningKey(1024, 65537)
7225 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007226 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7227 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007228
7229 // Check the usage count limit tag appears in the authorizations.
7230 AuthorizationSet auths;
7231 for (auto& entry : key_characteristics_) {
7232 auths.push_back(AuthorizationSet(entry.authorizations));
7233 }
7234 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7235 << "key usage count limit " << 1U << " missing";
7236
7237 string message = "1234567890123456";
7238 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7239
Qi Wubeefae42021-01-28 23:16:37 +08007240 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7241 AuthorizationSet keystore_auths =
7242 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7243
Qi Wud22ec842020-11-26 13:27:53 +08007244 // First usage of RSA key should work.
7245 SignMessage(message, params);
7246
Qi Wud22ec842020-11-26 13:27:53 +08007247 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7248 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7249 // must be invalidated from secure storage (such as RPMB partition).
7250 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7251 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007252 // Usage count limit tag is enforced by keystore, keymint does nothing.
7253 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007254 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007255 }
7256}
7257
7258/*
7259 * UsageCountLimitTest.TestLimitUseRsa
7260 *
7261 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7262 */
7263TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007264 if (SecLevel() == SecurityLevel::STRONGBOX) {
7265 GTEST_SKIP() << "Test not applicable to StrongBox device";
7266 }
Qi Wubeefae42021-01-28 23:16:37 +08007267
7268 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7269 .Authorization(TAG_NO_AUTH_REQUIRED)
7270 .RsaSigningKey(1024, 65537)
7271 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007272 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7273 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007274
7275 // Check the usage count limit tag appears in the authorizations.
7276 AuthorizationSet auths;
7277 for (auto& entry : key_characteristics_) {
7278 auths.push_back(AuthorizationSet(entry.authorizations));
7279 }
7280 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7281 << "key usage count limit " << 3U << " missing";
7282
7283 string message = "1234567890123456";
7284 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7285
7286 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7287 AuthorizationSet keystore_auths =
7288 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7289
7290 SignMessage(message, params);
7291 SignMessage(message, params);
7292 SignMessage(message, params);
7293
7294 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7295 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7296 // must be invalidated from secure storage (such as RPMB partition).
7297 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7298 } else {
7299 // Usage count limit tag is enforced by keystore, keymint does nothing.
7300 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007301 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007302 }
7303}
7304
Qi Wu8e727f72021-02-11 02:49:33 +08007305/*
7306 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7307 *
7308 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7309 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7310 * in hardware.
7311 */
7312TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01007313 if (SecLevel() == SecurityLevel::STRONGBOX) {
7314 GTEST_SKIP() << "Test not applicable to StrongBox device";
7315 }
Qi Wu8e727f72021-02-11 02:49:33 +08007316
7317 auto error = GenerateKey(AuthorizationSetBuilder()
7318 .RsaSigningKey(2048, 65537)
7319 .Digest(Digest::NONE)
7320 .Padding(PaddingMode::NONE)
7321 .Authorization(TAG_NO_AUTH_REQUIRED)
7322 .Authorization(TAG_ROLLBACK_RESISTANCE)
7323 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007324 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7325 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007326 }
David Drysdale513bf122021-10-06 11:53:13 +01007327
7328 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7329 ASSERT_EQ(ErrorCode::OK, error);
7330 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7331 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7332 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7333
7334 // The KeyMint should also enforce single use key in hardware when it supports rollback
7335 // resistance.
7336 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7337 .Authorization(TAG_NO_AUTH_REQUIRED)
7338 .RsaSigningKey(1024, 65537)
7339 .NoDigestOrPadding()
7340 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7341 .SetDefaultValidity()));
7342
7343 // Check the usage count limit tag appears in the hardware authorizations.
7344 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7345 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7346 << "key usage count limit " << 1U << " missing";
7347
7348 string message = "1234567890123456";
7349 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7350
7351 // First usage of RSA key should work.
7352 SignMessage(message, params);
7353
7354 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7355 // must be invalidated from secure storage (such as RPMB partition).
7356 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007357}
7358
Qi Wud22ec842020-11-26 13:27:53 +08007359INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7360
David Drysdale7de9feb2021-03-05 14:56:19 +00007361typedef KeyMintAidlTestBase GetHardwareInfoTest;
7362
7363TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7364 // Retrieving hardware info should give the same result each time.
7365 KeyMintHardwareInfo info;
7366 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7367 KeyMintHardwareInfo info2;
7368 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7369 EXPECT_EQ(info, info2);
7370}
7371
7372INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7373
Selene Huang31ab4042020-04-29 04:22:39 -07007374typedef KeyMintAidlTestBase AddEntropyTest;
7375
7376/*
7377 * AddEntropyTest.AddEntropy
7378 *
7379 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7380 * is actually added.
7381 */
7382TEST_P(AddEntropyTest, AddEntropy) {
7383 string data = "foo";
7384 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7385}
7386
7387/*
7388 * AddEntropyTest.AddEmptyEntropy
7389 *
7390 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7391 */
7392TEST_P(AddEntropyTest, AddEmptyEntropy) {
7393 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7394}
7395
7396/*
7397 * AddEntropyTest.AddLargeEntropy
7398 *
7399 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7400 */
7401TEST_P(AddEntropyTest, AddLargeEntropy) {
7402 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7403}
7404
David Drysdalebb3d85e2021-04-13 11:15:51 +01007405/*
7406 * AddEntropyTest.AddTooLargeEntropy
7407 *
7408 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7409 */
7410TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7411 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7412 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7413}
7414
Selene Huang31ab4042020-04-29 04:22:39 -07007415INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7416
Selene Huang31ab4042020-04-29 04:22:39 -07007417typedef KeyMintAidlTestBase KeyDeletionTest;
7418
7419/**
7420 * KeyDeletionTest.DeleteKey
7421 *
7422 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7423 * valid key blob.
7424 */
7425TEST_P(KeyDeletionTest, DeleteKey) {
7426 auto error = GenerateKey(AuthorizationSetBuilder()
7427 .RsaSigningKey(2048, 65537)
7428 .Digest(Digest::NONE)
7429 .Padding(PaddingMode::NONE)
7430 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007431 .Authorization(TAG_ROLLBACK_RESISTANCE)
7432 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007433 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7434 GTEST_SKIP() << "Rollback resistance not supported";
7435 }
Selene Huang31ab4042020-04-29 04:22:39 -07007436
7437 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007438 ASSERT_EQ(ErrorCode::OK, error);
7439 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7440 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007441
David Drysdale513bf122021-10-06 11:53:13 +01007442 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007443
David Drysdale513bf122021-10-06 11:53:13 +01007444 string message = "12345678901234567890123456789012";
7445 AuthorizationSet begin_out_params;
7446 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7447 Begin(KeyPurpose::SIGN, key_blob_,
7448 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7449 &begin_out_params));
7450 AbortIfNeeded();
7451 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007452}
7453
7454/**
7455 * KeyDeletionTest.DeleteInvalidKey
7456 *
7457 * This test checks that the HAL excepts invalid key blobs..
7458 */
7459TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7460 // Generate key just to check if rollback protection is implemented
7461 auto error = GenerateKey(AuthorizationSetBuilder()
7462 .RsaSigningKey(2048, 65537)
7463 .Digest(Digest::NONE)
7464 .Padding(PaddingMode::NONE)
7465 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007466 .Authorization(TAG_ROLLBACK_RESISTANCE)
7467 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007468 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7469 GTEST_SKIP() << "Rollback resistance not supported";
7470 }
Selene Huang31ab4042020-04-29 04:22:39 -07007471
7472 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007473 ASSERT_EQ(ErrorCode::OK, error);
7474 AuthorizationSet enforced(SecLevelAuthorizations());
7475 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007476
David Drysdale513bf122021-10-06 11:53:13 +01007477 // Delete the key we don't care about the result at this point.
7478 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007479
David Drysdale513bf122021-10-06 11:53:13 +01007480 // Now create an invalid key blob and delete it.
7481 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007482
David Drysdale513bf122021-10-06 11:53:13 +01007483 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007484}
7485
7486/**
7487 * KeyDeletionTest.DeleteAllKeys
7488 *
7489 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7490 *
7491 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7492 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7493 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7494 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7495 * credentials stored in Keystore/Keymint.
7496 */
7497TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007498 if (!arm_deleteAllKeys) {
7499 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7500 return;
7501 }
Selene Huang31ab4042020-04-29 04:22:39 -07007502 auto error = GenerateKey(AuthorizationSetBuilder()
7503 .RsaSigningKey(2048, 65537)
7504 .Digest(Digest::NONE)
7505 .Padding(PaddingMode::NONE)
7506 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007507 .Authorization(TAG_ROLLBACK_RESISTANCE)
7508 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007509 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7510 GTEST_SKIP() << "Rollback resistance not supported";
7511 }
Selene Huang31ab4042020-04-29 04:22:39 -07007512
7513 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007514 ASSERT_EQ(ErrorCode::OK, error);
7515 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7516 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007517
David Drysdale513bf122021-10-06 11:53:13 +01007518 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007519
David Drysdale513bf122021-10-06 11:53:13 +01007520 string message = "12345678901234567890123456789012";
7521 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07007522
David Drysdale513bf122021-10-06 11:53:13 +01007523 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7524 Begin(KeyPurpose::SIGN, key_blob_,
7525 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7526 &begin_out_params));
7527 AbortIfNeeded();
7528 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007529}
7530
7531INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
7532
David Drysdaled2cc8c22021-04-15 13:29:45 +01007533typedef KeyMintAidlTestBase KeyUpgradeTest;
7534
7535/**
7536 * KeyUpgradeTest.UpgradeInvalidKey
7537 *
7538 * This test checks that the HAL excepts invalid key blobs..
7539 */
7540TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
7541 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
7542
7543 std::vector<uint8_t> new_blob;
7544 Status result = keymint_->upgradeKey(key_blob,
7545 AuthorizationSetBuilder()
7546 .Authorization(TAG_APPLICATION_ID, "clientid")
7547 .Authorization(TAG_APPLICATION_DATA, "appdata")
7548 .vector_data(),
7549 &new_blob);
7550 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
7551}
7552
7553INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
7554
Selene Huang31ab4042020-04-29 04:22:39 -07007555using UpgradeKeyTest = KeyMintAidlTestBase;
7556
7557/*
7558 * UpgradeKeyTest.UpgradeKey
7559 *
7560 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
7561 */
7562TEST_P(UpgradeKeyTest, UpgradeKey) {
7563 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7564 .AesEncryptionKey(128)
7565 .Padding(PaddingMode::NONE)
7566 .Authorization(TAG_NO_AUTH_REQUIRED)));
7567
7568 auto result = UpgradeKey(key_blob_);
7569
7570 // Key doesn't need upgrading. Should get okay, but no new key blob.
7571 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
7572}
7573
7574INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
7575
7576using ClearOperationsTest = KeyMintAidlTestBase;
7577
7578/*
7579 * ClearSlotsTest.TooManyOperations
7580 *
7581 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
7582 * operations are started without being finished or aborted. Also verifies
7583 * that aborting the operations clears the operations.
7584 *
7585 */
7586TEST_P(ClearOperationsTest, TooManyOperations) {
7587 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7588 .Authorization(TAG_NO_AUTH_REQUIRED)
7589 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08007590 .Padding(PaddingMode::NONE)
7591 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007592
7593 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
7594 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08007595 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07007596 AuthorizationSet out_params;
7597 ErrorCode result;
7598 size_t i;
7599
7600 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00007601 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07007602 if (ErrorCode::OK != result) {
7603 break;
7604 }
7605 }
7606 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
7607 // Try again just in case there's a weird overflow bug
7608 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00007609 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007610 for (size_t j = 0; j < i; j++) {
7611 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
7612 << "Aboort failed for i = " << j << std::endl;
7613 }
David Drysdale7fc26b92022-05-13 09:54:24 +01007614 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007615 AbortIfNeeded();
7616}
7617
7618INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
7619
7620typedef KeyMintAidlTestBase TransportLimitTest;
7621
7622/*
David Drysdale7de9feb2021-03-05 14:56:19 +00007623 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07007624 *
7625 * Verifies that passing input data to finish succeeds as expected.
7626 */
7627TEST_P(TransportLimitTest, LargeFinishInput) {
7628 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7629 .Authorization(TAG_NO_AUTH_REQUIRED)
7630 .AesEncryptionKey(128)
7631 .BlockMode(BlockMode::ECB)
7632 .Padding(PaddingMode::NONE)));
7633
7634 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
7635 auto cipher_params =
7636 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7637
7638 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007639 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007640
7641 string plain_message = std::string(1 << msg_size, 'x');
7642 string encrypted_message;
7643 auto rc = Finish(plain_message, &encrypted_message);
7644
7645 EXPECT_EQ(ErrorCode::OK, rc);
7646 EXPECT_EQ(plain_message.size(), encrypted_message.size())
7647 << "Encrypt finish returned OK, but did not consume all of the given input";
7648 cipher_params.push_back(out_params);
7649
David Drysdale7fc26b92022-05-13 09:54:24 +01007650 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007651
7652 string decrypted_message;
7653 rc = Finish(encrypted_message, &decrypted_message);
7654 EXPECT_EQ(ErrorCode::OK, rc);
7655 EXPECT_EQ(plain_message.size(), decrypted_message.size())
7656 << "Decrypt finish returned OK, did not consume all of the given input";
7657 }
7658}
7659
7660INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
7661
Seth Moored79a0ec2021-12-13 20:03:33 +00007662static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05007663 switch (curve) {
7664 case EcCurve::P_224:
7665 return NID_secp224r1;
7666 case EcCurve::P_256:
7667 return NID_X9_62_prime256v1;
7668 case EcCurve::P_384:
7669 return NID_secp384r1;
7670 case EcCurve::P_521:
7671 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00007672 case EcCurve::CURVE_25519:
7673 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05007674 }
7675}
7676
David Drysdale42fe1892021-10-14 14:43:46 +01007677class KeyAgreementTest : public KeyMintAidlTestBase {
7678 protected:
7679 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
7680 std::vector<uint8_t>* localPublicKey) {
7681 // Generate EC key locally (with access to private key material)
7682 if (localCurve == EcCurve::CURVE_25519) {
7683 uint8_t privKeyData[32];
7684 uint8_t pubKeyData[32];
7685 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01007686 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
7687 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
7688 } else {
7689 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
7690 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
7691 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
7692 ASSERT_NE(group, nullptr);
7693 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
7694 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
7695 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
7696 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01007697 }
David Drysdalea410b772022-05-09 16:44:13 +01007698
7699 // Get encoded form of the public part of the locally generated key...
7700 unsigned char* p = nullptr;
7701 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
7702 ASSERT_GT(localPublicKeySize, 0);
7703 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
7704 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
7705 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01007706 }
7707
7708 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
7709 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00007710 auto builder = AuthorizationSetBuilder()
7711 .Authorization(TAG_NO_AUTH_REQUIRED)
7712 .Authorization(TAG_EC_CURVE, curve)
7713 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7714 .Authorization(TAG_ALGORITHM, Algorithm::EC)
7715 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
7716 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
7717 .SetDefaultValidity();
7718 ErrorCode result = GenerateKey(builder);
7719
7720 if (SecLevel() == SecurityLevel::STRONGBOX) {
7721 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
7722 result = GenerateKeyWithSelfSignedAttestKey(
7723 AuthorizationSetBuilder()
7724 .EcdsaKey(EcCurve::P_256)
7725 .AttestKey()
7726 .SetDefaultValidity(), /* attest key params */
7727 builder, &key_blob_, &key_characteristics_, &cert_chain_);
7728 }
7729 }
David Drysdale42fe1892021-10-14 14:43:46 +01007730 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
7731 ASSERT_GT(cert_chain_.size(), 0);
7732 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7733 ASSERT_NE(kmKeyCert, nullptr);
7734 // Check that keyAgreement (bit 4) is set in KeyUsage
7735 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
7736 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
7737 ASSERT_NE(*kmPubKey, nullptr);
7738 if (dump_Attestations) {
7739 for (size_t n = 0; n < cert_chain_.size(); n++) {
7740 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
7741 }
7742 }
7743 }
7744
7745 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
7746 const std::vector<uint8_t>& localPublicKey) {
7747 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7748 string ZabFromKeyMintStr;
7749 ASSERT_EQ(ErrorCode::OK,
7750 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
7751 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
7752 vector<uint8_t> ZabFromTest;
7753
7754 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
7755 size_t kmPubKeySize = 32;
7756 uint8_t kmPubKeyData[32];
7757 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7758 ASSERT_EQ(kmPubKeySize, 32);
7759
7760 uint8_t localPrivKeyData[32];
7761 size_t localPrivKeySize = 32;
7762 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
7763 &localPrivKeySize));
7764 ASSERT_EQ(localPrivKeySize, 32);
7765
7766 uint8_t sharedKey[32];
7767 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
7768 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
7769 } else {
7770 // Perform local ECDH between the two keys so we can check if we get the same Zab..
7771 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
7772 ASSERT_NE(ctx, nullptr);
7773 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
7774 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
7775 size_t ZabFromTestLen = 0;
7776 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
7777 ZabFromTest.resize(ZabFromTestLen);
7778 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
7779 }
7780 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
7781 }
7782};
7783
David Zeuthene0c40892021-01-08 12:54:11 -05007784/*
7785 * KeyAgreementTest.Ecdh
7786 *
David Drysdale42fe1892021-10-14 14:43:46 +01007787 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05007788 */
7789TEST_P(KeyAgreementTest, Ecdh) {
7790 // Because it's possible to use this API with keys on different curves, we
7791 // check all N^2 combinations where N is the number of supported
7792 // curves.
7793 //
7794 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
7795 // lot more curves we can be smart about things and just pick |otherCurve| so
7796 // it's not |curve| and that way we end up with only 2*N runs
7797 //
7798 for (auto curve : ValidCurves()) {
7799 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01007800 SCOPED_TRACE(testing::Message()
7801 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
7802
David Zeuthene0c40892021-01-08 12:54:11 -05007803 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007804 EVP_PKEY_Ptr localPrivKey;
7805 vector<uint8_t> localPublicKey;
7806 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007807
7808 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007809 EVP_PKEY_Ptr kmPubKey;
7810 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007811
7812 // Now that we have the two keys, we ask KeyMint to perform ECDH...
7813 if (curve != localCurve) {
7814 // If the keys are using different curves KeyMint should fail with
7815 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01007816 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05007817 string ZabFromKeyMintStr;
7818 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01007819 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05007820 &ZabFromKeyMintStr));
7821
7822 } else {
7823 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01007824 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007825 }
7826
7827 CheckedDeleteKey();
7828 }
7829 }
7830}
7831
David Drysdale42fe1892021-10-14 14:43:46 +01007832/*
7833 * KeyAgreementTest.EcdhCurve25519
7834 *
7835 * Verifies that ECDH works for curve25519. This is also covered by the general
7836 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
7837 * KeyMint 1.0.
7838 */
7839TEST_P(KeyAgreementTest, EcdhCurve25519) {
7840 if (!Curve25519Supported()) {
7841 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7842 }
7843
7844 // Generate EC key in KeyMint (only access to public key material)
7845 EcCurve curve = EcCurve::CURVE_25519;
7846 EVP_PKEY_Ptr kmPubKey = nullptr;
7847 GenerateKeyMintEcKey(curve, &kmPubKey);
7848
7849 // Generate EC key on same curve locally (with access to private key material).
7850 EVP_PKEY_Ptr privKey;
7851 vector<uint8_t> encodedPublicKey;
7852 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7853
7854 // Agree on a key between local and KeyMint and check it.
7855 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7856
7857 CheckedDeleteKey();
7858}
7859
7860/*
7861 * KeyAgreementTest.EcdhCurve25519Imported
7862 *
7863 * Verifies that ECDH works for an imported curve25519 key.
7864 */
7865TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
7866 if (!Curve25519Supported()) {
7867 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7868 }
7869
7870 // Import x25519 key into KeyMint.
7871 EcCurve curve = EcCurve::CURVE_25519;
7872 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
7873 .Authorization(TAG_NO_AUTH_REQUIRED)
7874 .EcdsaKey(EcCurve::CURVE_25519)
7875 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7876 .SetDefaultValidity(),
7877 KeyFormat::PKCS8, x25519_pkcs8_key));
7878 ASSERT_GT(cert_chain_.size(), 0);
7879 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7880 ASSERT_NE(kmKeyCert, nullptr);
7881 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
7882 ASSERT_NE(kmPubKey.get(), nullptr);
7883
7884 // Expect the import to emit corresponding public key data.
7885 size_t kmPubKeySize = 32;
7886 uint8_t kmPubKeyData[32];
7887 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7888 ASSERT_EQ(kmPubKeySize, 32);
7889 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
7890 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
7891
7892 // Generate EC key on same curve locally (with access to private key material).
7893 EVP_PKEY_Ptr privKey;
7894 vector<uint8_t> encodedPublicKey;
7895 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7896
7897 // Agree on a key between local and KeyMint and check it.
7898 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7899
7900 CheckedDeleteKey();
7901}
7902
7903/*
7904 * KeyAgreementTest.EcdhCurve25519InvalidSize
7905 *
7906 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
7907 */
7908TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
7909 if (!Curve25519Supported()) {
7910 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7911 }
7912
7913 // Generate EC key in KeyMint (only access to public key material)
7914 EcCurve curve = EcCurve::CURVE_25519;
7915 EVP_PKEY_Ptr kmPubKey = nullptr;
7916 GenerateKeyMintEcKey(curve, &kmPubKey);
7917
7918 // Generate EC key on same curve locally (with access to private key material).
7919 EVP_PKEY_Ptr privKey;
7920 vector<uint8_t> encodedPublicKey;
7921 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7922
7923 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7924 string ZabFromKeyMintStr;
7925 // Send in an incomplete public key.
7926 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
7927 &ZabFromKeyMintStr));
7928
7929 CheckedDeleteKey();
7930}
7931
7932/*
7933 * KeyAgreementTest.EcdhCurve25519Mismatch
7934 *
7935 * Verifies that ECDH fails between curve25519 and other curves.
7936 */
7937TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
7938 if (!Curve25519Supported()) {
7939 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7940 }
7941
7942 // Generate EC key in KeyMint (only access to public key material)
7943 EcCurve curve = EcCurve::CURVE_25519;
7944 EVP_PKEY_Ptr kmPubKey = nullptr;
7945 GenerateKeyMintEcKey(curve, &kmPubKey);
7946
7947 for (auto localCurve : ValidCurves()) {
7948 if (localCurve == curve) {
7949 continue;
7950 }
7951 // Generate EC key on a different curve locally (with access to private key material).
7952 EVP_PKEY_Ptr privKey;
7953 vector<uint8_t> encodedPublicKey;
7954 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
7955
David Drysdale7fc26b92022-05-13 09:54:24 +01007956 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01007957 string ZabFromKeyMintStr;
7958 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
7959 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
7960 &ZabFromKeyMintStr));
7961 }
7962
7963 CheckedDeleteKey();
7964}
7965
David Zeuthene0c40892021-01-08 12:54:11 -05007966INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
7967
David Drysdaled2cc8c22021-04-15 13:29:45 +01007968using DestroyAttestationIdsTest = KeyMintAidlTestBase;
7969
7970// This is a problematic test, as it can render the device under test permanently unusable.
7971// Re-enable and run at your own risk.
7972TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
7973 auto result = DestroyAttestationIds();
7974 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
7975}
7976
7977INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
7978
Shawn Willdend659c7c2021-02-19 14:51:51 -07007979using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007980
David Drysdaledb0dcf52021-05-18 11:43:31 +01007981/*
7982 * EarlyBootKeyTest.CreateEarlyBootKeys
7983 *
7984 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
7985 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007986TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01007987 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007988 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7989 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7990
David Drysdaleadfe6112021-05-27 12:00:53 +01007991 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
7992 ASSERT_GT(keyData.blob.size(), 0U);
7993 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7994 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7995 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007996 CheckedDeleteKey(&aesKeyData.blob);
7997 CheckedDeleteKey(&hmacKeyData.blob);
7998 CheckedDeleteKey(&rsaKeyData.blob);
7999 CheckedDeleteKey(&ecdsaKeyData.blob);
8000}
8001
David Drysdaledb0dcf52021-05-18 11:43:31 +01008002/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008003 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8004 *
8005 * Verifies that creating an early boot key with attestation succeeds.
8006 */
8007TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8008 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8009 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8010 builder->AttestationChallenge("challenge");
8011 builder->AttestationApplicationId("app_id");
8012 });
8013
8014 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008015 // Strongbox may not support factory attestation. Key creation might fail with
8016 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8017 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8018 continue;
8019 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008020 ASSERT_GT(keyData.blob.size(), 0U);
8021 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8022 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8023 }
8024 CheckedDeleteKey(&aesKeyData.blob);
8025 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00008026 if (rsaKeyData.blob.size() != 0U) {
8027 CheckedDeleteKey(&rsaKeyData.blob);
8028 }
8029 if (ecdsaKeyData.blob.size() != 0U) {
8030 CheckedDeleteKey(&ecdsaKeyData.blob);
8031 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008032}
8033
8034/*
8035 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008036 *
8037 * Verifies that using early boot keys at a later stage fails.
8038 */
8039TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8040 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8041 .Authorization(TAG_NO_AUTH_REQUIRED)
8042 .Authorization(TAG_EARLY_BOOT_ONLY)
8043 .HmacKey(128)
8044 .Digest(Digest::SHA_2_256)
8045 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8046 AuthorizationSet output_params;
8047 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8048 AuthorizationSetBuilder()
8049 .Digest(Digest::SHA_2_256)
8050 .Authorization(TAG_MAC_LENGTH, 256),
8051 &output_params));
8052}
8053
8054/*
8055 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8056 *
8057 * Verifies that importing early boot keys fails.
8058 */
8059TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8060 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8061 .Authorization(TAG_NO_AUTH_REQUIRED)
8062 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008063 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008064 .Digest(Digest::SHA_2_256)
8065 .SetDefaultValidity(),
8066 KeyFormat::PKCS8, ec_256_key));
8067}
8068
David Drysdaled2cc8c22021-04-15 13:29:45 +01008069// 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 +00008070// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8071// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8072// early boot, so you'll have to reboot between runs.
8073TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8074 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8075 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8076 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8077 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8078 EXPECT_TRUE(
8079 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8080 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8081 EXPECT_TRUE(
8082 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8083
8084 // Should be able to use keys, since early boot has not ended
8085 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8086 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8087 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8088 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8089
8090 // End early boot
8091 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8092 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8093
8094 // Should not be able to use already-created keys.
8095 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8096 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8097 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8098 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8099
8100 CheckedDeleteKey(&aesKeyData.blob);
8101 CheckedDeleteKey(&hmacKeyData.blob);
8102 CheckedDeleteKey(&rsaKeyData.blob);
8103 CheckedDeleteKey(&ecdsaKeyData.blob);
8104
8105 // Should not be able to create new keys
8106 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
8107 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
8108
8109 CheckedDeleteKey(&aesKeyData.blob);
8110 CheckedDeleteKey(&hmacKeyData.blob);
8111 CheckedDeleteKey(&rsaKeyData.blob);
8112 CheckedDeleteKey(&ecdsaKeyData.blob);
8113}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008114
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008115INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8116
Shawn Willdend659c7c2021-02-19 14:51:51 -07008117using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008118
8119// This may be a problematic test. It can't be run repeatedly without unlocking the device in
8120// between runs... and on most test devices there are no enrolled credentials so it can't be
8121// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8122// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8123// a manual test process, which includes unlocking between runs, which is why it's included here.
8124// Well, that and the fact that it's the only test we can do without also making calls into the
8125// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8126// implications might be, so that may or may not be a solution.
8127TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8128 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8129 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
8130
8131 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8132 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8133 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8134 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8135
8136 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008137 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008138 ASSERT_EQ(ErrorCode::OK, rc);
8139 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8140 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8141 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8142 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
8143
8144 CheckedDeleteKey(&aesKeyData.blob);
8145 CheckedDeleteKey(&hmacKeyData.blob);
8146 CheckedDeleteKey(&rsaKeyData.blob);
8147 CheckedDeleteKey(&ecdsaKeyData.blob);
8148}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008149
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008150INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8151
Shawn Willden22fb9c12022-06-02 14:04:33 -06008152using VsrRequirementTest = KeyMintAidlTestBase;
8153
8154TEST_P(VsrRequirementTest, Vsr13Test) {
8155 int vsr_api_level = get_vsr_api_level();
8156 if (vsr_api_level < 33) {
8157 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8158 }
8159 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8160}
8161
8162INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8163
Janis Danisevskis24c04702020-12-16 18:28:39 -08008164} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008165
8166int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008167 std::cout << "Testing ";
8168 auto halInstances =
8169 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8170 std::cout << "HAL instances:\n";
8171 for (auto& entry : halInstances) {
8172 std::cout << " " << entry << '\n';
8173 }
8174
Selene Huang31ab4042020-04-29 04:22:39 -07008175 ::testing::InitGoogleTest(&argc, argv);
8176 for (int i = 1; i < argc; ++i) {
8177 if (argv[i][0] == '-') {
8178 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008179 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8180 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008181 }
8182 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008183 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8184 dump_Attestations = true;
8185 } else {
8186 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008187 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008188 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8189 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8190 // be run in emulated environments that don't have the normal bootloader
8191 // interactions.
8192 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8193 }
Selene Huang31ab4042020-04-29 04:22:39 -07008194 }
8195 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008196 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008197}