blob: 8b622997ae47bdbd2dbd63ae4839f94bcd4b75ae [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/*
5172 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5173 *
David Drysdale59cae642021-05-12 13:52:03 +01005174 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005175 * with incompatible MGF digest.
5176 */
5177TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5178 ASSERT_EQ(ErrorCode::OK,
5179 GenerateKey(AuthorizationSetBuilder()
5180 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5181 .Authorization(TAG_NO_AUTH_REQUIRED)
5182 .RsaEncryptionKey(2048, 65537)
5183 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005184 .Digest(Digest::SHA_2_256)
5185 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005186 string message = "Hello World!";
5187
5188 auto params = AuthorizationSetBuilder()
5189 .Padding(PaddingMode::RSA_OAEP)
5190 .Digest(Digest::SHA_2_256)
5191 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005192 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005193}
5194
5195/*
5196 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5197 *
5198 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5199 * with unsupported MGF digest.
5200 */
5201TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5202 ASSERT_EQ(ErrorCode::OK,
5203 GenerateKey(AuthorizationSetBuilder()
5204 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5205 .Authorization(TAG_NO_AUTH_REQUIRED)
5206 .RsaEncryptionKey(2048, 65537)
5207 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005208 .Digest(Digest::SHA_2_256)
5209 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005210 string message = "Hello World!";
5211
5212 auto params = AuthorizationSetBuilder()
5213 .Padding(PaddingMode::RSA_OAEP)
5214 .Digest(Digest::SHA_2_256)
5215 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005216 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005217}
5218
5219/*
Selene Huang31ab4042020-04-29 04:22:39 -07005220 * EncryptionOperationsTest.RsaPkcs1Success
5221 *
5222 * Verifies that RSA PKCS encryption/decrypts works.
5223 */
5224TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5225 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5226 .Authorization(TAG_NO_AUTH_REQUIRED)
5227 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005228 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5229 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005230
5231 string message = "Hello World!";
5232 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005233 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005234 EXPECT_EQ(2048U / 8, ciphertext1.size());
5235
David Drysdale59cae642021-05-12 13:52:03 +01005236 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005237 EXPECT_EQ(2048U / 8, ciphertext2.size());
5238
5239 // PKCS1 v1.5 randomizes padding so every result should be different.
5240 EXPECT_NE(ciphertext1, ciphertext2);
5241
5242 string plaintext = DecryptMessage(ciphertext1, params);
5243 EXPECT_EQ(message, plaintext);
5244
5245 // Decrypting corrupted ciphertext should fail.
5246 size_t offset_to_corrupt = random() % ciphertext1.size();
5247 char corrupt_byte;
5248 do {
5249 corrupt_byte = static_cast<char>(random() % 256);
5250 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5251 ciphertext1[offset_to_corrupt] = corrupt_byte;
5252
5253 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5254 string result;
5255 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5256 EXPECT_EQ(0U, result.size());
5257}
5258
5259/*
Selene Huang31ab4042020-04-29 04:22:39 -07005260 * EncryptionOperationsTest.EcdsaEncrypt
5261 *
5262 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5263 */
5264TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5265 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5266 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005267 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005268 .Digest(Digest::NONE)
5269 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005270 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5271 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5272 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5273}
5274
5275/*
5276 * EncryptionOperationsTest.HmacEncrypt
5277 *
5278 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5279 */
5280TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5281 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5282 .Authorization(TAG_NO_AUTH_REQUIRED)
5283 .HmacKey(128)
5284 .Digest(Digest::SHA_2_256)
5285 .Padding(PaddingMode::NONE)
5286 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5287 auto params = AuthorizationSetBuilder()
5288 .Digest(Digest::SHA_2_256)
5289 .Padding(PaddingMode::NONE)
5290 .Authorization(TAG_MAC_LENGTH, 128);
5291 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5292 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5293}
5294
5295/*
5296 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5297 *
5298 * Verifies that AES ECB mode works.
5299 */
5300TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5301 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5302 .Authorization(TAG_NO_AUTH_REQUIRED)
5303 .AesEncryptionKey(128)
5304 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5305 .Padding(PaddingMode::NONE)));
5306
5307 ASSERT_GT(key_blob_.size(), 0U);
5308 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5309
5310 // Two-block message.
5311 string message = "12345678901234567890123456789012";
5312 string ciphertext1 = EncryptMessage(message, params);
5313 EXPECT_EQ(message.size(), ciphertext1.size());
5314
5315 string ciphertext2 = EncryptMessage(string(message), params);
5316 EXPECT_EQ(message.size(), ciphertext2.size());
5317
5318 // ECB is deterministic.
5319 EXPECT_EQ(ciphertext1, ciphertext2);
5320
5321 string plaintext = DecryptMessage(ciphertext1, params);
5322 EXPECT_EQ(message, plaintext);
5323}
5324
5325/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005326 * EncryptionOperationsTest.AesEcbUnknownTag
5327 *
5328 * Verifies that AES ECB operations ignore unknown tags.
5329 */
5330TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5331 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5332 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5333 KeyParameter unknown_param;
5334 unknown_param.tag = unknown_tag;
5335
5336 vector<KeyCharacteristics> key_characteristics;
5337 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5338 .Authorization(TAG_NO_AUTH_REQUIRED)
5339 .AesEncryptionKey(128)
5340 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5341 .Padding(PaddingMode::NONE)
5342 .Authorization(unknown_param),
5343 &key_blob_, &key_characteristics));
5344 ASSERT_GT(key_blob_.size(), 0U);
5345
5346 // Unknown tags should not be returned in key characteristics.
5347 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5348 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5349 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5350 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5351
5352 // Encrypt without mentioning the unknown parameter.
5353 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5354 string message = "12345678901234567890123456789012";
5355 string ciphertext = EncryptMessage(message, params);
5356 EXPECT_EQ(message.size(), ciphertext.size());
5357
5358 // Decrypt including the unknown parameter.
5359 auto decrypt_params = AuthorizationSetBuilder()
5360 .BlockMode(BlockMode::ECB)
5361 .Padding(PaddingMode::NONE)
5362 .Authorization(unknown_param);
5363 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5364 EXPECT_EQ(message, plaintext);
5365}
5366
5367/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005368 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005369 *
5370 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5371 */
5372TEST_P(EncryptionOperationsTest, AesWrongMode) {
5373 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5374 .Authorization(TAG_NO_AUTH_REQUIRED)
5375 .AesEncryptionKey(128)
5376 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5377 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005378 ASSERT_GT(key_blob_.size(), 0U);
5379
Selene Huang31ab4042020-04-29 04:22:39 -07005380 EXPECT_EQ(
5381 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5382 Begin(KeyPurpose::ENCRYPT,
5383 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5384}
5385
5386/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005387 * EncryptionOperationsTest.AesWrongPadding
5388 *
5389 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5390 */
5391TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5392 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5393 .Authorization(TAG_NO_AUTH_REQUIRED)
5394 .AesEncryptionKey(128)
5395 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5396 .Padding(PaddingMode::NONE)));
5397 ASSERT_GT(key_blob_.size(), 0U);
5398
5399 EXPECT_EQ(
5400 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5401 Begin(KeyPurpose::ENCRYPT,
5402 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5403}
5404
5405/*
5406 * EncryptionOperationsTest.AesInvalidParams
5407 *
5408 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5409 */
5410TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5411 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5412 .Authorization(TAG_NO_AUTH_REQUIRED)
5413 .AesEncryptionKey(128)
5414 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5415 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5416 .Padding(PaddingMode::NONE)
5417 .Padding(PaddingMode::PKCS7)));
5418 ASSERT_GT(key_blob_.size(), 0U);
5419
5420 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5421 .BlockMode(BlockMode::CBC)
5422 .BlockMode(BlockMode::ECB)
5423 .Padding(PaddingMode::NONE));
5424 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5425 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5426
5427 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5428 .BlockMode(BlockMode::ECB)
5429 .Padding(PaddingMode::NONE)
5430 .Padding(PaddingMode::PKCS7));
5431 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5432 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5433}
5434
5435/*
Selene Huang31ab4042020-04-29 04:22:39 -07005436 * EncryptionOperationsTest.AesWrongPurpose
5437 *
5438 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5439 * specified.
5440 */
5441TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5442 auto err = GenerateKey(AuthorizationSetBuilder()
5443 .Authorization(TAG_NO_AUTH_REQUIRED)
5444 .AesKey(128)
5445 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5446 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5447 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5448 .Padding(PaddingMode::NONE));
5449 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5450 ASSERT_GT(key_blob_.size(), 0U);
5451
5452 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5453 .BlockMode(BlockMode::GCM)
5454 .Padding(PaddingMode::NONE)
5455 .Authorization(TAG_MAC_LENGTH, 128));
5456 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5457
5458 CheckedDeleteKey();
5459
5460 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5461 .Authorization(TAG_NO_AUTH_REQUIRED)
5462 .AesKey(128)
5463 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5464 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5465 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5466 .Padding(PaddingMode::NONE)));
5467
5468 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5469 .BlockMode(BlockMode::GCM)
5470 .Padding(PaddingMode::NONE)
5471 .Authorization(TAG_MAC_LENGTH, 128));
5472 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5473}
5474
5475/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005476 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005477 *
5478 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5479 * multiple of the block size and no padding is specified.
5480 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005481TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5482 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5483 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5484 .Authorization(TAG_NO_AUTH_REQUIRED)
5485 .AesEncryptionKey(128)
5486 .Authorization(TAG_BLOCK_MODE, blockMode)
5487 .Padding(PaddingMode::NONE)));
5488 // Message is slightly shorter than two blocks.
5489 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005490
David Drysdaled2cc8c22021-04-15 13:29:45 +01005491 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5492 AuthorizationSet out_params;
5493 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5494 string ciphertext;
5495 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5496 EXPECT_EQ(0U, ciphertext.size());
5497
5498 CheckedDeleteKey();
5499 }
Selene Huang31ab4042020-04-29 04:22:39 -07005500}
5501
5502/*
5503 * EncryptionOperationsTest.AesEcbPkcs7Padding
5504 *
5505 * Verifies that AES PKCS7 padding works for any message length.
5506 */
5507TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5508 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5509 .Authorization(TAG_NO_AUTH_REQUIRED)
5510 .AesEncryptionKey(128)
5511 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5512 .Padding(PaddingMode::PKCS7)));
5513
5514 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5515
5516 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005517 for (size_t i = 0; i <= 48; i++) {
5518 SCOPED_TRACE(testing::Message() << "i = " << i);
5519 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5520 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005521 string ciphertext = EncryptMessage(message, params);
5522 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5523 string plaintext = DecryptMessage(ciphertext, params);
5524 EXPECT_EQ(message, plaintext);
5525 }
5526}
5527
5528/*
5529 * EncryptionOperationsTest.AesEcbWrongPadding
5530 *
5531 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5532 * specified.
5533 */
5534TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5535 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5536 .Authorization(TAG_NO_AUTH_REQUIRED)
5537 .AesEncryptionKey(128)
5538 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5539 .Padding(PaddingMode::NONE)));
5540
5541 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5542
5543 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005544 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005545 string message(i, 'a');
5546 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5547 }
5548}
5549
5550/*
5551 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5552 *
5553 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5554 */
5555TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5556 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5557 .Authorization(TAG_NO_AUTH_REQUIRED)
5558 .AesEncryptionKey(128)
5559 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5560 .Padding(PaddingMode::PKCS7)));
5561
5562 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5563
5564 string message = "a";
5565 string ciphertext = EncryptMessage(message, params);
5566 EXPECT_EQ(16U, ciphertext.size());
5567 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005568
Seth Moore7a55ae32021-06-23 14:28:11 -07005569 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5570 ++ciphertext[ciphertext.size() / 2];
5571
5572 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5573 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005574 ErrorCode error = Finish(ciphertext, &plaintext);
5575 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005576 // This is the expected error, we can exit the test now.
5577 return;
5578 } else {
5579 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005580 ASSERT_EQ(error, ErrorCode::OK)
5581 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005582 }
5583 }
5584 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005585}
5586
David Drysdaleb8093292022-04-08 12:22:35 +01005587/*
5588 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5589 *
5590 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5591 */
5592TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5593 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5594 .Authorization(TAG_NO_AUTH_REQUIRED)
5595 .AesEncryptionKey(128)
5596 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5597 .Padding(PaddingMode::PKCS7)));
5598
5599 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5600
5601 string message = "a";
5602 string ciphertext = EncryptMessage(message, params);
5603 EXPECT_EQ(16U, ciphertext.size());
5604 EXPECT_NE(ciphertext, message);
5605
5606 // Shorten the ciphertext.
5607 ciphertext.resize(ciphertext.size() - 1);
5608 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5609 string plaintext;
5610 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5611}
5612
Selene Huang31ab4042020-04-29 04:22:39 -07005613vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5614 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005615 EXPECT_TRUE(iv);
5616 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005617}
5618
5619/*
5620 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5621 *
5622 * Verifies that AES CTR mode works.
5623 */
5624TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5625 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5626 .Authorization(TAG_NO_AUTH_REQUIRED)
5627 .AesEncryptionKey(128)
5628 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5629 .Padding(PaddingMode::NONE)));
5630
5631 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5632
5633 string message = "123";
5634 AuthorizationSet out_params;
5635 string ciphertext1 = EncryptMessage(message, params, &out_params);
5636 vector<uint8_t> iv1 = CopyIv(out_params);
5637 EXPECT_EQ(16U, iv1.size());
5638
5639 EXPECT_EQ(message.size(), ciphertext1.size());
5640
5641 out_params.Clear();
5642 string ciphertext2 = EncryptMessage(message, params, &out_params);
5643 vector<uint8_t> iv2 = CopyIv(out_params);
5644 EXPECT_EQ(16U, iv2.size());
5645
5646 // IVs should be random, so ciphertexts should differ.
5647 EXPECT_NE(ciphertext1, ciphertext2);
5648
5649 auto params_iv1 =
5650 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5651 auto params_iv2 =
5652 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5653
5654 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5655 EXPECT_EQ(message, plaintext);
5656 plaintext = DecryptMessage(ciphertext2, params_iv2);
5657 EXPECT_EQ(message, plaintext);
5658
5659 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5660 plaintext = DecryptMessage(ciphertext1, params_iv2);
5661 EXPECT_NE(message, plaintext);
5662 plaintext = DecryptMessage(ciphertext2, params_iv1);
5663 EXPECT_NE(message, plaintext);
5664}
5665
5666/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305667 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07005668 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305669 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07005670 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305671TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5672 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5673}
Selene Huang31ab4042020-04-29 04:22:39 -07005674
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305675/*
5676 * EncryptionOperationsTest.AesCbcIncremental
5677 *
5678 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5679 */
5680TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5681 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5682}
Selene Huang31ab4042020-04-29 04:22:39 -07005683
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305684/*
5685 * EncryptionOperationsTest.AesCtrIncremental
5686 *
5687 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5688 */
5689TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5690 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5691}
Selene Huang31ab4042020-04-29 04:22:39 -07005692
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305693/*
5694 * EncryptionOperationsTest.AesGcmIncremental
5695 *
5696 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5697 */
5698TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5699 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07005700}
5701
Prashant Patildd5f7f02022-07-06 18:58:07 +00005702/*
5703 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
5704 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5705 */
5706TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
5707 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
5708 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
5709 string kat_plaintext =
5710 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
5711 "809FFF37081C22EF278F896AB213A2A631");
5712 string kat_ciphertext =
5713 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
5714 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
5715 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5716 kat_ciphertext);
5717}
5718
5719/*
5720 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
5721 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5722 */
5723TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
5724 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
5725 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
5726 string kat_plaintext =
5727 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
5728 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
5729 string kat_ciphertext =
5730 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
5731 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
5732 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
5733 kat_plaintext, kat_ciphertext);
5734}
5735
5736/*
5737 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
5738 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
5739 */
5740TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
5741 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
5742 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
5743 string kat_plaintext =
5744 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
5745 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
5746 string kat_ciphertext =
5747 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
5748 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
5749 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
5750 kat_ciphertext);
5751}
5752
5753/*
5754 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
5755 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
5756 */
5757TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
5758 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
5759 string kat_plaintext =
5760 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
5761 "7B6168A9A27BCE554BEA94EF26E6C742A0");
5762 string kat_ciphertext =
5763 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
5764 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
5765 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
5766 kat_ciphertext);
5767}
5768
5769/*
5770 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
5771 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
5772 */
5773TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
5774 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
5775 string kat_plaintext =
5776 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
5777 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
5778 string kat_ciphertext =
5779 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
5780 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
5781 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
5782 kat_ciphertext);
5783}
5784
5785/*
5786 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
5787 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
5788 */
5789TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
5790 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
5791 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
5792 string kat_plaintext =
5793 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
5794 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
5795 string kat_ciphertext =
5796 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
5797 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
5798 "bdfcc0cba0");
5799
5800 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
5801 kat_ciphertext);
5802}
5803
5804/*
5805 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
5806 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5807 */
5808TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
5809 if (SecLevel() == SecurityLevel::STRONGBOX) {
5810 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5811 }
5812 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
5813 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
5814 string kat_plaintext =
5815 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
5816 "167f2497c994bd496eb80bfb2ba2c9d5af");
5817 string kat_ciphertext =
5818 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
5819 "72c134552f3a138e726fbe493b3a839598");
5820 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5821 kat_ciphertext);
5822}
5823
5824/*
5825 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
5826 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5827 */
5828TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
5829 if (SecLevel() == SecurityLevel::STRONGBOX) {
5830 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5831 }
5832 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
5833 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
5834 string kat_plaintext =
5835 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
5836 "b170");
5837 string kat_ciphertext =
5838 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
5839 "4e3884138ff403a41fd99818708ada301c");
5840 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
5841 kat_plaintext, kat_ciphertext);
5842}
5843
5844/*
5845 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
5846 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
5847 */
5848TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
5849 if (SecLevel() == SecurityLevel::STRONGBOX) {
5850 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5851 }
5852 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
5853 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
5854 string kat_plaintext =
5855 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
5856 "28091e09cdbbd3b42b");
5857 string kat_ciphertext =
5858 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
5859 "2ae0f90f0c19f42b4a");
5860 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
5861 kat_ciphertext);
5862}
5863
5864/*
5865 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
5866 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
5867 */
5868TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
5869 if (SecLevel() == SecurityLevel::STRONGBOX) {
5870 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5871 }
5872 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
5873 string kat_plaintext =
5874 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
5875 "44ab");
5876 string kat_ciphertext =
5877 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
5878 "2453");
5879 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
5880 kat_ciphertext);
5881}
5882
5883/*
5884 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
5885 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
5886 */
5887TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
5888 if (SecLevel() == SecurityLevel::STRONGBOX) {
5889 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5890 }
5891 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
5892 string kat_plaintext =
5893 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
5894 "e2c7");
5895 string kat_ciphertext =
5896 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
5897 "bb7e3a889dd4a9589098b44acf1056e7aa");
5898 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
5899 kat_ciphertext);
5900}
5901
5902/*
5903 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
5904 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
5905 */
5906TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
5907 if (SecLevel() == SecurityLevel::STRONGBOX) {
5908 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5909 }
5910 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
5911 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
5912 string kat_plaintext =
5913 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
5914 "ff52");
5915 string kat_ciphertext =
5916 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
5917 "1413ad70fb0e1970669095ad77ebb5974ae8");
5918
5919 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
5920 kat_ciphertext);
5921}
5922
5923/*
5924 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
5925 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5926 */
5927TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
5928 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
5929 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
5930 string kat_plaintext =
5931 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
5932 "494cb53caca353e4b637ba05687be20f8d");
5933 string kat_ciphertext =
5934 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
5935 "6047da1e4fd7c4e1cf2656097f75ae8685");
5936 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5937 kat_ciphertext);
5938}
5939
5940/*
5941 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
5942 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5943 */
5944TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
5945 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
5946 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
5947 string kat_plaintext =
5948 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
5949 "2545a82b73c48078b9dae62261c65909");
5950 string kat_ciphertext =
5951 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
5952 "9403a71987b95124073d69f2a3cb95b0ab");
5953 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
5954 kat_plaintext, kat_ciphertext);
5955}
5956
5957/*
5958 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
5959 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
5960 */
5961TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
5962 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
5963 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
5964 string kat_plaintext =
5965 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
5966 "1f6db3c884");
5967 string kat_ciphertext =
5968 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
5969 "a7be30d4c3");
5970 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
5971 kat_ciphertext);
5972}
5973
5974/*
5975 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
5976 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
5977 */
5978TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
5979 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
5980 string kat_plaintext =
5981 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
5982 "31a476d6806b8116089c6ec50bb543200f");
5983 string kat_ciphertext =
5984 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
5985 "c83e377faf246288931136bef2a07c0be4");
5986 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
5987 kat_ciphertext);
5988}
5989
5990/*
5991 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
5992 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
5993 */
5994TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
5995 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
5996 string kat_plaintext =
5997 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
5998 "6f");
5999 string kat_ciphertext =
6000 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6001 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6002 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6003 kat_ciphertext);
6004}
6005
6006/*
6007 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6008 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6009 */
6010TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6011 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6012 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6013 string kat_plaintext =
6014 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6015 "f0");
6016 string kat_ciphertext =
6017 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6018 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6019
6020 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6021 kat_ciphertext);
6022}
6023
Selene Huang31ab4042020-04-29 04:22:39 -07006024struct AesCtrSp80038aTestVector {
6025 const char* key;
6026 const char* nonce;
6027 const char* plaintext;
6028 const char* ciphertext;
6029};
6030
6031// These test vectors are taken from
6032// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6033static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6034 // AES-128
6035 {
6036 "2b7e151628aed2a6abf7158809cf4f3c",
6037 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6038 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6039 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6040 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6041 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6042 },
6043 // AES-192
6044 {
6045 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6046 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6047 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6048 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6049 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6050 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6051 },
6052 // AES-256
6053 {
6054 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6055 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6056 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6057 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6058 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6059 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6060 },
6061};
6062
6063/*
6064 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6065 *
6066 * Verifies AES CTR implementation against SP800-38A test vectors.
6067 */
6068TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6069 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6070 for (size_t i = 0; i < 3; i++) {
6071 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6072 const string key = hex2str(test.key);
6073 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6074 InvalidSizes.end())
6075 continue;
6076 const string nonce = hex2str(test.nonce);
6077 const string plaintext = hex2str(test.plaintext);
6078 const string ciphertext = hex2str(test.ciphertext);
6079 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6080 }
6081}
6082
6083/*
6084 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6085 *
6086 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6087 */
6088TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6089 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6090 .Authorization(TAG_NO_AUTH_REQUIRED)
6091 .AesEncryptionKey(128)
6092 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6093 .Padding(PaddingMode::PKCS7)));
6094 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6095 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6096}
6097
6098/*
6099 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6100 *
6101 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6102 */
6103TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6104 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6105 .Authorization(TAG_NO_AUTH_REQUIRED)
6106 .AesEncryptionKey(128)
6107 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6108 .Authorization(TAG_CALLER_NONCE)
6109 .Padding(PaddingMode::NONE)));
6110
6111 auto params = AuthorizationSetBuilder()
6112 .BlockMode(BlockMode::CTR)
6113 .Padding(PaddingMode::NONE)
6114 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6115 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6116
6117 params = AuthorizationSetBuilder()
6118 .BlockMode(BlockMode::CTR)
6119 .Padding(PaddingMode::NONE)
6120 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6121 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6122
6123 params = AuthorizationSetBuilder()
6124 .BlockMode(BlockMode::CTR)
6125 .Padding(PaddingMode::NONE)
6126 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6127 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6128}
6129
6130/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006131 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006132 *
6133 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6134 */
6135TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6136 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6137 .Authorization(TAG_NO_AUTH_REQUIRED)
6138 .AesEncryptionKey(128)
6139 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6140 .Padding(PaddingMode::NONE)));
6141 // Two-block message.
6142 string message = "12345678901234567890123456789012";
6143 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6144 AuthorizationSet out_params;
6145 string ciphertext1 = EncryptMessage(message, params, &out_params);
6146 vector<uint8_t> iv1 = CopyIv(out_params);
6147 EXPECT_EQ(message.size(), ciphertext1.size());
6148
6149 out_params.Clear();
6150
6151 string ciphertext2 = EncryptMessage(message, params, &out_params);
6152 vector<uint8_t> iv2 = CopyIv(out_params);
6153 EXPECT_EQ(message.size(), ciphertext2.size());
6154
6155 // IVs should be random, so ciphertexts should differ.
6156 EXPECT_NE(ciphertext1, ciphertext2);
6157
6158 params.push_back(TAG_NONCE, iv1);
6159 string plaintext = DecryptMessage(ciphertext1, params);
6160 EXPECT_EQ(message, plaintext);
6161}
6162
6163/*
Tommy Chiuee705692021-09-23 20:09:13 +08006164 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6165 *
6166 * Verifies that keymaster generates correct output on zero-input with
6167 * NonePadding mode
6168 */
6169TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6170 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6171 .Authorization(TAG_NO_AUTH_REQUIRED)
6172 .AesEncryptionKey(128)
6173 .BlockMode(BlockMode::CBC)
6174 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6175
6176 // Zero input message
6177 string message = "";
6178 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
6179 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6180 AuthorizationSet out_params;
6181 string ciphertext1 = EncryptMessage(message, params, &out_params);
6182 vector<uint8_t> iv1 = CopyIv(out_params);
6183 if (padding == PaddingMode::NONE)
6184 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6185 else
6186 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6187
6188 out_params.Clear();
6189
6190 string ciphertext2 = EncryptMessage(message, params, &out_params);
6191 vector<uint8_t> iv2 = CopyIv(out_params);
6192 if (padding == PaddingMode::NONE)
6193 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6194 else
6195 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6196
6197 // IVs should be random
6198 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6199
6200 params.push_back(TAG_NONCE, iv1);
6201 string plaintext = DecryptMessage(ciphertext1, params);
6202 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6203 }
6204}
6205
6206/*
Selene Huang31ab4042020-04-29 04:22:39 -07006207 * EncryptionOperationsTest.AesCallerNonce
6208 *
6209 * Verifies that AES caller-provided nonces work correctly.
6210 */
6211TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6212 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6213 .Authorization(TAG_NO_AUTH_REQUIRED)
6214 .AesEncryptionKey(128)
6215 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6216 .Authorization(TAG_CALLER_NONCE)
6217 .Padding(PaddingMode::NONE)));
6218
6219 string message = "12345678901234567890123456789012";
6220
6221 // Don't specify nonce, should get a random one.
6222 AuthorizationSetBuilder params =
6223 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6224 AuthorizationSet out_params;
6225 string ciphertext = EncryptMessage(message, params, &out_params);
6226 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006227 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006228
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006229 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006230 string plaintext = DecryptMessage(ciphertext, params);
6231 EXPECT_EQ(message, plaintext);
6232
6233 // Now specify a nonce, should also work.
6234 params = AuthorizationSetBuilder()
6235 .BlockMode(BlockMode::CBC)
6236 .Padding(PaddingMode::NONE)
6237 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6238 out_params.Clear();
6239 ciphertext = EncryptMessage(message, params, &out_params);
6240
6241 // Decrypt with correct nonce.
6242 plaintext = DecryptMessage(ciphertext, params);
6243 EXPECT_EQ(message, plaintext);
6244
6245 // Try with wrong nonce.
6246 params = AuthorizationSetBuilder()
6247 .BlockMode(BlockMode::CBC)
6248 .Padding(PaddingMode::NONE)
6249 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6250 plaintext = DecryptMessage(ciphertext, params);
6251 EXPECT_NE(message, plaintext);
6252}
6253
6254/*
6255 * EncryptionOperationsTest.AesCallerNonceProhibited
6256 *
6257 * Verifies that caller-provided nonces are not permitted when not specified in the key
6258 * authorizations.
6259 */
6260TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6261 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6262 .Authorization(TAG_NO_AUTH_REQUIRED)
6263 .AesEncryptionKey(128)
6264 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6265 .Padding(PaddingMode::NONE)));
6266
6267 string message = "12345678901234567890123456789012";
6268
6269 // Don't specify nonce, should get a random one.
6270 AuthorizationSetBuilder params =
6271 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6272 AuthorizationSet out_params;
6273 string ciphertext = EncryptMessage(message, params, &out_params);
6274 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006275 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006276
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006277 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006278 string plaintext = DecryptMessage(ciphertext, params);
6279 EXPECT_EQ(message, plaintext);
6280
6281 // Now specify a nonce, should fail
6282 params = AuthorizationSetBuilder()
6283 .BlockMode(BlockMode::CBC)
6284 .Padding(PaddingMode::NONE)
6285 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6286 out_params.Clear();
6287 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6288}
6289
6290/*
6291 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6292 *
6293 * Verifies that AES GCM mode works.
6294 */
6295TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6296 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6297 .Authorization(TAG_NO_AUTH_REQUIRED)
6298 .AesEncryptionKey(128)
6299 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6300 .Padding(PaddingMode::NONE)
6301 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6302
6303 string aad = "foobar";
6304 string message = "123456789012345678901234567890123456";
6305
6306 auto begin_params = AuthorizationSetBuilder()
6307 .BlockMode(BlockMode::GCM)
6308 .Padding(PaddingMode::NONE)
6309 .Authorization(TAG_MAC_LENGTH, 128);
6310
Selene Huang31ab4042020-04-29 04:22:39 -07006311 // Encrypt
6312 AuthorizationSet begin_out_params;
6313 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6314 << "Begin encrypt";
6315 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006316 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6317 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006318 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6319
6320 // Grab nonce
6321 begin_params.push_back(begin_out_params);
6322
6323 // Decrypt.
6324 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006325 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006326 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006327 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006328 EXPECT_EQ(message.length(), plaintext.length());
6329 EXPECT_EQ(message, plaintext);
6330}
6331
6332/*
6333 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6334 *
6335 * Verifies that AES GCM mode works, even when there's a long delay
6336 * between operations.
6337 */
6338TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6339 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6340 .Authorization(TAG_NO_AUTH_REQUIRED)
6341 .AesEncryptionKey(128)
6342 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6343 .Padding(PaddingMode::NONE)
6344 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6345
6346 string aad = "foobar";
6347 string message = "123456789012345678901234567890123456";
6348
6349 auto begin_params = AuthorizationSetBuilder()
6350 .BlockMode(BlockMode::GCM)
6351 .Padding(PaddingMode::NONE)
6352 .Authorization(TAG_MAC_LENGTH, 128);
6353
Selene Huang31ab4042020-04-29 04:22:39 -07006354 // Encrypt
6355 AuthorizationSet begin_out_params;
6356 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6357 << "Begin encrypt";
6358 string ciphertext;
6359 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006360 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006361 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006362 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006363
6364 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6365
6366 // Grab nonce
6367 begin_params.push_back(begin_out_params);
6368
6369 // Decrypt.
6370 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6371 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006372 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006373 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006374 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006375 sleep(5);
6376 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6377 EXPECT_EQ(message.length(), plaintext.length());
6378 EXPECT_EQ(message, plaintext);
6379}
6380
6381/*
6382 * EncryptionOperationsTest.AesGcmDifferentNonces
6383 *
6384 * Verifies that encrypting the same data with different nonces produces different outputs.
6385 */
6386TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6387 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6388 .Authorization(TAG_NO_AUTH_REQUIRED)
6389 .AesEncryptionKey(128)
6390 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6391 .Padding(PaddingMode::NONE)
6392 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6393 .Authorization(TAG_CALLER_NONCE)));
6394
6395 string aad = "foobar";
6396 string message = "123456789012345678901234567890123456";
6397 string nonce1 = "000000000000";
6398 string nonce2 = "111111111111";
6399 string nonce3 = "222222222222";
6400
6401 string ciphertext1 =
6402 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6403 string ciphertext2 =
6404 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6405 string ciphertext3 =
6406 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6407
6408 ASSERT_NE(ciphertext1, ciphertext2);
6409 ASSERT_NE(ciphertext1, ciphertext3);
6410 ASSERT_NE(ciphertext2, ciphertext3);
6411}
6412
6413/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006414 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6415 *
6416 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6417 */
6418TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6419 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6420 .Authorization(TAG_NO_AUTH_REQUIRED)
6421 .AesEncryptionKey(128)
6422 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6423 .Padding(PaddingMode::NONE)
6424 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6425
6426 string aad = "foobar";
6427 string message = "123456789012345678901234567890123456";
6428
6429 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6430 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6431 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6432
6433 ASSERT_NE(ciphertext1, ciphertext2);
6434 ASSERT_NE(ciphertext1, ciphertext3);
6435 ASSERT_NE(ciphertext2, ciphertext3);
6436}
6437
6438/*
Selene Huang31ab4042020-04-29 04:22:39 -07006439 * EncryptionOperationsTest.AesGcmTooShortTag
6440 *
6441 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6442 */
6443TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6444 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6445 .Authorization(TAG_NO_AUTH_REQUIRED)
6446 .AesEncryptionKey(128)
6447 .BlockMode(BlockMode::GCM)
6448 .Padding(PaddingMode::NONE)
6449 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6450 string message = "123456789012345678901234567890123456";
6451 auto params = AuthorizationSetBuilder()
6452 .BlockMode(BlockMode::GCM)
6453 .Padding(PaddingMode::NONE)
6454 .Authorization(TAG_MAC_LENGTH, 96);
6455
6456 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6457}
6458
6459/*
6460 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6461 *
6462 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6463 */
6464TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
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 string aad = "foobar";
6472 string message = "123456789012345678901234567890123456";
6473 auto 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;
6480 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6481 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006482 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006483
6484 AuthorizationSet finish_out_params;
6485 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006486 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6487 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006488
6489 params = AuthorizationSetBuilder()
6490 .Authorizations(begin_out_params)
6491 .BlockMode(BlockMode::GCM)
6492 .Padding(PaddingMode::NONE)
6493 .Authorization(TAG_MAC_LENGTH, 96);
6494
6495 // Decrypt.
6496 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6497}
6498
6499/*
6500 * EncryptionOperationsTest.AesGcmCorruptKey
6501 *
6502 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6503 */
6504TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6505 const uint8_t nonce_bytes[] = {
6506 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6507 };
6508 string nonce = make_string(nonce_bytes);
6509 const uint8_t ciphertext_bytes[] = {
6510 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6511 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6512 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6513 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6514 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6515 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6516 };
6517 string ciphertext = make_string(ciphertext_bytes);
6518
6519 auto params = AuthorizationSetBuilder()
6520 .BlockMode(BlockMode::GCM)
6521 .Padding(PaddingMode::NONE)
6522 .Authorization(TAG_MAC_LENGTH, 128)
6523 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6524
6525 auto import_params = AuthorizationSetBuilder()
6526 .Authorization(TAG_NO_AUTH_REQUIRED)
6527 .AesEncryptionKey(128)
6528 .BlockMode(BlockMode::GCM)
6529 .Padding(PaddingMode::NONE)
6530 .Authorization(TAG_CALLER_NONCE)
6531 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6532
6533 // Import correct key and decrypt
6534 const uint8_t key_bytes[] = {
6535 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6536 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6537 };
6538 string key = make_string(key_bytes);
6539 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6540 string plaintext = DecryptMessage(ciphertext, params);
6541 CheckedDeleteKey();
6542
6543 // Corrupt key and attempt to decrypt
6544 key[0] = 0;
6545 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6546 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6547 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6548 CheckedDeleteKey();
6549}
6550
6551/*
6552 * EncryptionOperationsTest.AesGcmAadNoData
6553 *
6554 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6555 * encrypt.
6556 */
6557TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6558 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6559 .Authorization(TAG_NO_AUTH_REQUIRED)
6560 .AesEncryptionKey(128)
6561 .BlockMode(BlockMode::GCM)
6562 .Padding(PaddingMode::NONE)
6563 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6564
6565 string aad = "1234567890123456";
6566 auto params = AuthorizationSetBuilder()
6567 .BlockMode(BlockMode::GCM)
6568 .Padding(PaddingMode::NONE)
6569 .Authorization(TAG_MAC_LENGTH, 128);
6570
Selene Huang31ab4042020-04-29 04:22:39 -07006571 // Encrypt
6572 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006573 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006574 string ciphertext;
6575 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006576 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6577 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006578 EXPECT_TRUE(finish_out_params.empty());
6579
6580 // Grab nonce
6581 params.push_back(begin_out_params);
6582
6583 // Decrypt.
6584 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006585 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006586 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006587 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006588
6589 EXPECT_TRUE(finish_out_params.empty());
6590
6591 EXPECT_EQ("", plaintext);
6592}
6593
6594/*
6595 * EncryptionOperationsTest.AesGcmMultiPartAad
6596 *
6597 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6598 * chunks.
6599 */
6600TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6601 const size_t tag_bits = 128;
6602 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6603 .Authorization(TAG_NO_AUTH_REQUIRED)
6604 .AesEncryptionKey(128)
6605 .BlockMode(BlockMode::GCM)
6606 .Padding(PaddingMode::NONE)
6607 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6608
6609 string message = "123456789012345678901234567890123456";
6610 auto begin_params = AuthorizationSetBuilder()
6611 .BlockMode(BlockMode::GCM)
6612 .Padding(PaddingMode::NONE)
6613 .Authorization(TAG_MAC_LENGTH, tag_bits);
6614 AuthorizationSet begin_out_params;
6615
David Drysdale7fc26b92022-05-13 09:54:24 +01006616 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006617
6618 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006619 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6620 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006621 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006622 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6623 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006624
Selene Huang31ab4042020-04-29 04:22:39 -07006625 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006626 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006627
6628 // Grab nonce.
6629 begin_params.push_back(begin_out_params);
6630
6631 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01006632 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006633 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006634 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006635 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006636 EXPECT_EQ(message, plaintext);
6637}
6638
6639/*
6640 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6641 *
6642 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6643 */
6644TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6645 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6646 .Authorization(TAG_NO_AUTH_REQUIRED)
6647 .AesEncryptionKey(128)
6648 .BlockMode(BlockMode::GCM)
6649 .Padding(PaddingMode::NONE)
6650 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6651
6652 string message = "123456789012345678901234567890123456";
6653 auto begin_params = AuthorizationSetBuilder()
6654 .BlockMode(BlockMode::GCM)
6655 .Padding(PaddingMode::NONE)
6656 .Authorization(TAG_MAC_LENGTH, 128);
6657 AuthorizationSet begin_out_params;
6658
David Drysdale7fc26b92022-05-13 09:54:24 +01006659 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006660
Shawn Willden92d79c02021-02-19 07:31:55 -07006661 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006662 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006663 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6664 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006665
David Drysdaled2cc8c22021-04-15 13:29:45 +01006666 // The failure should have already cancelled the operation.
6667 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6668
Shawn Willden92d79c02021-02-19 07:31:55 -07006669 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006670}
6671
6672/*
6673 * EncryptionOperationsTest.AesGcmBadAad
6674 *
6675 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6676 */
6677TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6678 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6679 .Authorization(TAG_NO_AUTH_REQUIRED)
6680 .AesEncryptionKey(128)
6681 .BlockMode(BlockMode::GCM)
6682 .Padding(PaddingMode::NONE)
6683 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6684
6685 string message = "12345678901234567890123456789012";
6686 auto begin_params = AuthorizationSetBuilder()
6687 .BlockMode(BlockMode::GCM)
6688 .Padding(PaddingMode::NONE)
6689 .Authorization(TAG_MAC_LENGTH, 128);
6690
Selene Huang31ab4042020-04-29 04:22:39 -07006691 // Encrypt
6692 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006693 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006694 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006695 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006696 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006697
6698 // Grab nonce
6699 begin_params.push_back(begin_out_params);
6700
Selene Huang31ab4042020-04-29 04:22:39 -07006701 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006702 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006703 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006704 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006705 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006706}
6707
6708/*
6709 * EncryptionOperationsTest.AesGcmWrongNonce
6710 *
6711 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6712 */
6713TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6714 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6715 .Authorization(TAG_NO_AUTH_REQUIRED)
6716 .AesEncryptionKey(128)
6717 .BlockMode(BlockMode::GCM)
6718 .Padding(PaddingMode::NONE)
6719 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6720
6721 string message = "12345678901234567890123456789012";
6722 auto begin_params = AuthorizationSetBuilder()
6723 .BlockMode(BlockMode::GCM)
6724 .Padding(PaddingMode::NONE)
6725 .Authorization(TAG_MAC_LENGTH, 128);
6726
Selene Huang31ab4042020-04-29 04:22:39 -07006727 // Encrypt
6728 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006729 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006730 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006731 string ciphertext;
6732 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006733 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006734
6735 // Wrong nonce
6736 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6737
6738 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006739 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006740 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006741 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006742 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006743
6744 // With wrong nonce, should have gotten garbage plaintext (or none).
6745 EXPECT_NE(message, plaintext);
6746}
6747
6748/*
6749 * EncryptionOperationsTest.AesGcmCorruptTag
6750 *
6751 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6752 */
6753TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6754 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6755 .Authorization(TAG_NO_AUTH_REQUIRED)
6756 .AesEncryptionKey(128)
6757 .BlockMode(BlockMode::GCM)
6758 .Padding(PaddingMode::NONE)
6759 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6760
6761 string aad = "1234567890123456";
6762 string message = "123456789012345678901234567890123456";
6763
6764 auto params = AuthorizationSetBuilder()
6765 .BlockMode(BlockMode::GCM)
6766 .Padding(PaddingMode::NONE)
6767 .Authorization(TAG_MAC_LENGTH, 128);
6768
Selene Huang31ab4042020-04-29 04:22:39 -07006769 // Encrypt
6770 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006771 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006772 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006773 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006774 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006775
6776 // Corrupt tag
6777 ++(*ciphertext.rbegin());
6778
6779 // Grab nonce
6780 params.push_back(begin_out_params);
6781
6782 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006783 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006784 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006785 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006786 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006787}
6788
6789/*
6790 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
6791 *
6792 * Verifies that 3DES is basically functional.
6793 */
6794TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
6795 auto auths = AuthorizationSetBuilder()
6796 .TripleDesEncryptionKey(168)
6797 .BlockMode(BlockMode::ECB)
6798 .Authorization(TAG_NO_AUTH_REQUIRED)
6799 .Padding(PaddingMode::NONE);
6800
6801 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
6802 // Two-block message.
6803 string message = "1234567890123456";
6804 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6805 string ciphertext1 = EncryptMessage(message, inParams);
6806 EXPECT_EQ(message.size(), ciphertext1.size());
6807
6808 string ciphertext2 = EncryptMessage(string(message), inParams);
6809 EXPECT_EQ(message.size(), ciphertext2.size());
6810
6811 // ECB is deterministic.
6812 EXPECT_EQ(ciphertext1, ciphertext2);
6813
6814 string plaintext = DecryptMessage(ciphertext1, inParams);
6815 EXPECT_EQ(message, plaintext);
6816}
6817
6818/*
6819 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
6820 *
6821 * Verifies that CBC keys reject ECB usage.
6822 */
6823TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
6824 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6825 .TripleDesEncryptionKey(168)
6826 .BlockMode(BlockMode::CBC)
6827 .Authorization(TAG_NO_AUTH_REQUIRED)
6828 .Padding(PaddingMode::NONE)));
6829
6830 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6831 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
6832}
6833
6834/*
6835 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
6836 *
6837 * Tests ECB mode with PKCS#7 padding, various message sizes.
6838 */
6839TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
6840 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6841 .TripleDesEncryptionKey(168)
6842 .BlockMode(BlockMode::ECB)
6843 .Authorization(TAG_NO_AUTH_REQUIRED)
6844 .Padding(PaddingMode::PKCS7)));
6845
6846 for (size_t i = 0; i < 32; ++i) {
6847 string message(i, 'a');
6848 auto inParams =
6849 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6850 string ciphertext = EncryptMessage(message, inParams);
6851 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6852 string plaintext = DecryptMessage(ciphertext, inParams);
6853 EXPECT_EQ(message, plaintext);
6854 }
6855}
6856
6857/*
6858 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
6859 *
6860 * Verifies that keys configured for no padding reject PKCS7 padding
6861 */
6862TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
6863 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6864 .TripleDesEncryptionKey(168)
6865 .BlockMode(BlockMode::ECB)
6866 .Authorization(TAG_NO_AUTH_REQUIRED)
6867 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00006868 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6869 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07006870}
6871
6872/*
6873 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
6874 *
6875 * Verifies that corrupted padding is detected.
6876 */
6877TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
6878 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6879 .TripleDesEncryptionKey(168)
6880 .BlockMode(BlockMode::ECB)
6881 .Authorization(TAG_NO_AUTH_REQUIRED)
6882 .Padding(PaddingMode::PKCS7)));
6883
6884 string message = "a";
6885 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
6886 EXPECT_EQ(8U, ciphertext.size());
6887 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006888
6889 AuthorizationSetBuilder begin_params;
6890 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
6891 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07006892
6893 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
6894 ++ciphertext[ciphertext.size() / 2];
6895
David Drysdale7fc26b92022-05-13 09:54:24 +01006896 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07006897 string plaintext;
6898 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6899 ErrorCode error = Finish(&plaintext);
6900 if (error == ErrorCode::INVALID_ARGUMENT) {
6901 // This is the expected error, we can exit the test now.
6902 return;
6903 } else {
6904 // Very small chance we got valid decryption, so try again.
6905 ASSERT_EQ(error, ErrorCode::OK);
6906 }
6907 }
6908 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006909}
6910
6911struct TripleDesTestVector {
6912 const char* name;
6913 const KeyPurpose purpose;
6914 const BlockMode block_mode;
6915 const PaddingMode padding_mode;
6916 const char* key;
6917 const char* iv;
6918 const char* input;
6919 const char* output;
6920};
6921
6922// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
6923// of the NIST vectors are multiples of the block size.
6924static const TripleDesTestVector kTripleDesTestVectors[] = {
6925 {
6926 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6927 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
6928 "", // IV
6929 "329d86bdf1bc5af4", // input
6930 "d946c2756d78633f", // output
6931 },
6932 {
6933 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6934 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
6935 "", // IV
6936 "6b1540781b01ce1997adae102dbf3c5b", // input
6937 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
6938 },
6939 {
6940 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6941 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
6942 "", // IV
6943 "6daad94ce08acfe7", // input
6944 "660e7d32dcc90e79", // output
6945 },
6946 {
6947 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6948 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
6949 "", // IV
6950 "e9653a0a1f05d31b9acd12d73aa9879d", // input
6951 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
6952 },
6953 {
6954 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6955 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
6956 "43f791134c5647ba", // IV
6957 "dcc153cef81d6f24", // input
6958 "92538bd8af18d3ba", // output
6959 },
6960 {
6961 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6962 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6963 "c2e999cb6249023c", // IV
6964 "c689aee38a301bb316da75db36f110b5", // input
6965 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
6966 },
6967 {
6968 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
6969 PaddingMode::PKCS7,
6970 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6971 "c2e999cb6249023c", // IV
6972 "c689aee38a301bb316da75db36f110b500", // input
6973 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
6974 },
6975 {
6976 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
6977 PaddingMode::PKCS7,
6978 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6979 "c2e999cb6249023c", // IV
6980 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
6981 "c689aee38a301bb316da75db36f110b500", // output
6982 },
6983 {
6984 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6985 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
6986 "41746c7e442d3681", // IV
6987 "c53a7b0ec40600fe", // input
6988 "d4f00eb455de1034", // output
6989 },
6990 {
6991 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6992 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
6993 "3982bc02c3727d45", // IV
6994 "6006f10adef52991fcc777a1238bbb65", // input
6995 "edae09288e9e3bc05746d872b48e3b29", // output
6996 },
6997};
6998
6999/*
7000 * EncryptionOperationsTest.TripleDesTestVector
7001 *
7002 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7003 */
7004TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7005 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7006 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7007 SCOPED_TRACE(test->name);
7008 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7009 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7010 hex2str(test->output));
7011 }
7012}
7013
7014/*
7015 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7016 *
7017 * Validates CBC mode functionality.
7018 */
7019TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7020 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7021 .TripleDesEncryptionKey(168)
7022 .BlockMode(BlockMode::CBC)
7023 .Authorization(TAG_NO_AUTH_REQUIRED)
7024 .Padding(PaddingMode::NONE)));
7025
7026 ASSERT_GT(key_blob_.size(), 0U);
7027
Brian J Murray734c8412022-01-13 14:55:30 -08007028 // Four-block message.
7029 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007030 vector<uint8_t> iv1;
7031 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7032 EXPECT_EQ(message.size(), ciphertext1.size());
7033
7034 vector<uint8_t> iv2;
7035 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7036 EXPECT_EQ(message.size(), ciphertext2.size());
7037
7038 // IVs should be random, so ciphertexts should differ.
7039 EXPECT_NE(iv1, iv2);
7040 EXPECT_NE(ciphertext1, ciphertext2);
7041
7042 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7043 EXPECT_EQ(message, plaintext);
7044}
7045
7046/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007047 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7048 *
7049 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7050 */
7051TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7052 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7053 .TripleDesEncryptionKey(168)
7054 .BlockMode(BlockMode::CBC)
7055 .Authorization(TAG_NO_AUTH_REQUIRED)
7056 .Authorization(TAG_CALLER_NONCE)
7057 .Padding(PaddingMode::NONE)));
7058 auto params = AuthorizationSetBuilder()
7059 .BlockMode(BlockMode::CBC)
7060 .Padding(PaddingMode::NONE)
7061 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7062 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7063}
7064
7065/*
Selene Huang31ab4042020-04-29 04:22:39 -07007066 * EncryptionOperationsTest.TripleDesCallerIv
7067 *
7068 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7069 */
7070TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7071 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7072 .TripleDesEncryptionKey(168)
7073 .BlockMode(BlockMode::CBC)
7074 .Authorization(TAG_NO_AUTH_REQUIRED)
7075 .Authorization(TAG_CALLER_NONCE)
7076 .Padding(PaddingMode::NONE)));
7077 string message = "1234567890123456";
7078 vector<uint8_t> iv;
7079 // Don't specify IV, should get a random one.
7080 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7081 EXPECT_EQ(message.size(), ciphertext1.size());
7082 EXPECT_EQ(8U, iv.size());
7083
7084 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7085 EXPECT_EQ(message, plaintext);
7086
7087 // Now specify an IV, should also work.
7088 iv = AidlBuf("abcdefgh");
7089 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7090
7091 // Decrypt with correct IV.
7092 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7093 EXPECT_EQ(message, plaintext);
7094
7095 // Now try with wrong IV.
7096 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7097 EXPECT_NE(message, plaintext);
7098}
7099
7100/*
7101 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7102 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007103 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007104 */
7105TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7106 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7107 .TripleDesEncryptionKey(168)
7108 .BlockMode(BlockMode::CBC)
7109 .Authorization(TAG_NO_AUTH_REQUIRED)
7110 .Padding(PaddingMode::NONE)));
7111
7112 string message = "12345678901234567890123456789012";
7113 vector<uint8_t> iv;
7114 // Don't specify nonce, should get a random one.
7115 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7116 EXPECT_EQ(message.size(), ciphertext1.size());
7117 EXPECT_EQ(8U, iv.size());
7118
7119 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7120 EXPECT_EQ(message, plaintext);
7121
7122 // Now specify a nonce, should fail.
7123 auto input_params = AuthorizationSetBuilder()
7124 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7125 .BlockMode(BlockMode::CBC)
7126 .Padding(PaddingMode::NONE);
7127 AuthorizationSet output_params;
7128 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7129 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7130}
7131
7132/*
7133 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7134 *
7135 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7136 */
7137TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7138 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7139 .TripleDesEncryptionKey(168)
7140 .BlockMode(BlockMode::ECB)
7141 .Authorization(TAG_NO_AUTH_REQUIRED)
7142 .Padding(PaddingMode::NONE)));
7143 // Two-block message.
7144 string message = "1234567890123456";
7145 auto begin_params =
7146 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7147 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7148}
7149
7150/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007151 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007152 *
7153 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7154 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007155TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7156 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
7157 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7158 .TripleDesEncryptionKey(168)
7159 .BlockMode(blockMode)
7160 .Authorization(TAG_NO_AUTH_REQUIRED)
7161 .Padding(PaddingMode::NONE)));
7162 // Message is slightly shorter than two blocks.
7163 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007164
David Drysdaled2cc8c22021-04-15 13:29:45 +01007165 auto begin_params =
7166 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7167 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007168 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007169 string ciphertext;
7170 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7171
7172 CheckedDeleteKey();
7173 }
Selene Huang31ab4042020-04-29 04:22:39 -07007174}
7175
7176/*
7177 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7178 *
7179 * Verifies that PKCS7 padding works correctly in CBC mode.
7180 */
7181TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7182 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7183 .TripleDesEncryptionKey(168)
7184 .BlockMode(BlockMode::CBC)
7185 .Authorization(TAG_NO_AUTH_REQUIRED)
7186 .Padding(PaddingMode::PKCS7)));
7187
7188 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007189 for (size_t i = 0; i <= 32; i++) {
7190 SCOPED_TRACE(testing::Message() << "i = " << i);
7191 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7192 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007193 vector<uint8_t> iv;
7194 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7195 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7196 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7197 EXPECT_EQ(message, plaintext);
7198 }
7199}
7200
7201/*
7202 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7203 *
7204 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7205 */
7206TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7207 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7208 .TripleDesEncryptionKey(168)
7209 .BlockMode(BlockMode::CBC)
7210 .Authorization(TAG_NO_AUTH_REQUIRED)
7211 .Padding(PaddingMode::NONE)));
7212
7213 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007214 for (size_t i = 0; i <= 32; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07007215 auto begin_params =
7216 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7217 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7218 }
7219}
7220
7221/*
7222 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7223 *
7224 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7225 */
7226TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7227 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7228 .TripleDesEncryptionKey(168)
7229 .BlockMode(BlockMode::CBC)
7230 .Authorization(TAG_NO_AUTH_REQUIRED)
7231 .Padding(PaddingMode::PKCS7)));
7232
7233 string message = "a";
7234 vector<uint8_t> iv;
7235 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7236 EXPECT_EQ(8U, ciphertext.size());
7237 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007238
7239 auto begin_params = AuthorizationSetBuilder()
7240 .BlockMode(BlockMode::CBC)
7241 .Padding(PaddingMode::PKCS7)
7242 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007243
7244 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007245 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007246 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007247 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007248 string plaintext;
7249 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7250 ErrorCode error = Finish(&plaintext);
7251 if (error == ErrorCode::INVALID_ARGUMENT) {
7252 // This is the expected error, we can exit the test now.
7253 return;
7254 } else {
7255 // Very small chance we got valid decryption, so try again.
7256 ASSERT_EQ(error, ErrorCode::OK);
7257 }
7258 }
7259 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007260}
7261
7262/*
7263 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7264 *
7265 * Verifies that 3DES CBC works with many different input sizes.
7266 */
7267TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7268 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7269 .TripleDesEncryptionKey(168)
7270 .BlockMode(BlockMode::CBC)
7271 .Authorization(TAG_NO_AUTH_REQUIRED)
7272 .Padding(PaddingMode::NONE)));
7273
7274 int increment = 7;
7275 string message(240, 'a');
7276 AuthorizationSet input_params =
7277 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7278 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007279 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007280
7281 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007282 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007283 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007284 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7285 EXPECT_EQ(message.size(), ciphertext.size());
7286
7287 // Move TAG_NONCE into input_params
7288 input_params = output_params;
7289 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7290 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7291 output_params.Clear();
7292
David Drysdale7fc26b92022-05-13 09:54:24 +01007293 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007294 string plaintext;
7295 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007296 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007297 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7298 EXPECT_EQ(ciphertext.size(), plaintext.size());
7299 EXPECT_EQ(message, plaintext);
7300}
7301
7302INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7303
7304typedef KeyMintAidlTestBase MaxOperationsTest;
7305
7306/*
7307 * MaxOperationsTest.TestLimitAes
7308 *
7309 * Verifies that the max uses per boot tag works correctly with AES keys.
7310 */
7311TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007312 if (SecLevel() == SecurityLevel::STRONGBOX) {
7313 GTEST_SKIP() << "Test not applicable to StrongBox device";
7314 }
Selene Huang31ab4042020-04-29 04:22:39 -07007315
7316 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7317 .Authorization(TAG_NO_AUTH_REQUIRED)
7318 .AesEncryptionKey(128)
7319 .EcbMode()
7320 .Padding(PaddingMode::NONE)
7321 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7322
7323 string message = "1234567890123456";
7324
7325 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7326
7327 EncryptMessage(message, params);
7328 EncryptMessage(message, params);
7329 EncryptMessage(message, params);
7330
7331 // Fourth time should fail.
7332 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7333}
7334
7335/*
Qi Wud22ec842020-11-26 13:27:53 +08007336 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007337 *
7338 * Verifies that the max uses per boot tag works correctly with RSA keys.
7339 */
7340TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007341 if (SecLevel() == SecurityLevel::STRONGBOX) {
7342 GTEST_SKIP() << "Test not applicable to StrongBox device";
7343 }
Selene Huang31ab4042020-04-29 04:22:39 -07007344
7345 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7346 .Authorization(TAG_NO_AUTH_REQUIRED)
7347 .RsaSigningKey(1024, 65537)
7348 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007349 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7350 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007351
7352 string message = "1234567890123456";
7353
7354 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7355
7356 SignMessage(message, params);
7357 SignMessage(message, params);
7358 SignMessage(message, params);
7359
7360 // Fourth time should fail.
7361 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7362}
7363
7364INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7365
Qi Wud22ec842020-11-26 13:27:53 +08007366typedef KeyMintAidlTestBase UsageCountLimitTest;
7367
7368/*
Qi Wubeefae42021-01-28 23:16:37 +08007369 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007370 *
Qi Wubeefae42021-01-28 23:16:37 +08007371 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007372 */
Qi Wubeefae42021-01-28 23:16:37 +08007373TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007374 if (SecLevel() == SecurityLevel::STRONGBOX) {
7375 GTEST_SKIP() << "Test not applicable to StrongBox device";
7376 }
Qi Wud22ec842020-11-26 13:27:53 +08007377
7378 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7379 .Authorization(TAG_NO_AUTH_REQUIRED)
7380 .AesEncryptionKey(128)
7381 .EcbMode()
7382 .Padding(PaddingMode::NONE)
7383 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7384
7385 // Check the usage count limit tag appears in the authorizations.
7386 AuthorizationSet auths;
7387 for (auto& entry : key_characteristics_) {
7388 auths.push_back(AuthorizationSet(entry.authorizations));
7389 }
7390 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7391 << "key usage count limit " << 1U << " missing";
7392
7393 string message = "1234567890123456";
7394 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7395
Qi Wubeefae42021-01-28 23:16:37 +08007396 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7397 AuthorizationSet keystore_auths =
7398 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7399
Qi Wud22ec842020-11-26 13:27:53 +08007400 // First usage of AES key should work.
7401 EncryptMessage(message, params);
7402
Qi Wud22ec842020-11-26 13:27:53 +08007403 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7404 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7405 // must be invalidated from secure storage (such as RPMB partition).
7406 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7407 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007408 // Usage count limit tag is enforced by keystore, keymint does nothing.
7409 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007410 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007411 }
7412}
7413
7414/*
Qi Wubeefae42021-01-28 23:16:37 +08007415 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007416 *
Qi Wubeefae42021-01-28 23:16:37 +08007417 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007418 */
Qi Wubeefae42021-01-28 23:16:37 +08007419TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007420 if (SecLevel() == SecurityLevel::STRONGBOX) {
7421 GTEST_SKIP() << "Test not applicable to StrongBox device";
7422 }
Qi Wubeefae42021-01-28 23:16:37 +08007423
7424 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7425 .Authorization(TAG_NO_AUTH_REQUIRED)
7426 .AesEncryptionKey(128)
7427 .EcbMode()
7428 .Padding(PaddingMode::NONE)
7429 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7430
7431 // Check the usage count limit tag appears in the authorizations.
7432 AuthorizationSet auths;
7433 for (auto& entry : key_characteristics_) {
7434 auths.push_back(AuthorizationSet(entry.authorizations));
7435 }
7436 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7437 << "key usage count limit " << 3U << " missing";
7438
7439 string message = "1234567890123456";
7440 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7441
7442 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7443 AuthorizationSet keystore_auths =
7444 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7445
7446 EncryptMessage(message, params);
7447 EncryptMessage(message, params);
7448 EncryptMessage(message, params);
7449
7450 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7451 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7452 // must be invalidated from secure storage (such as RPMB partition).
7453 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7454 } else {
7455 // Usage count limit tag is enforced by keystore, keymint does nothing.
7456 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007457 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007458 }
7459}
7460
7461/*
7462 * UsageCountLimitTest.TestSingleUseRsa
7463 *
7464 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7465 */
7466TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007467 if (SecLevel() == SecurityLevel::STRONGBOX) {
7468 GTEST_SKIP() << "Test not applicable to StrongBox device";
7469 }
Qi Wud22ec842020-11-26 13:27:53 +08007470
7471 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7472 .Authorization(TAG_NO_AUTH_REQUIRED)
7473 .RsaSigningKey(1024, 65537)
7474 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007475 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7476 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007477
7478 // Check the usage count limit tag appears in the authorizations.
7479 AuthorizationSet auths;
7480 for (auto& entry : key_characteristics_) {
7481 auths.push_back(AuthorizationSet(entry.authorizations));
7482 }
7483 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7484 << "key usage count limit " << 1U << " missing";
7485
7486 string message = "1234567890123456";
7487 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7488
Qi Wubeefae42021-01-28 23:16:37 +08007489 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7490 AuthorizationSet keystore_auths =
7491 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7492
Qi Wud22ec842020-11-26 13:27:53 +08007493 // First usage of RSA key should work.
7494 SignMessage(message, params);
7495
Qi Wud22ec842020-11-26 13:27:53 +08007496 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7497 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7498 // must be invalidated from secure storage (such as RPMB partition).
7499 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7500 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007501 // Usage count limit tag is enforced by keystore, keymint does nothing.
7502 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007503 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007504 }
7505}
7506
7507/*
7508 * UsageCountLimitTest.TestLimitUseRsa
7509 *
7510 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7511 */
7512TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007513 if (SecLevel() == SecurityLevel::STRONGBOX) {
7514 GTEST_SKIP() << "Test not applicable to StrongBox device";
7515 }
Qi Wubeefae42021-01-28 23:16:37 +08007516
7517 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7518 .Authorization(TAG_NO_AUTH_REQUIRED)
7519 .RsaSigningKey(1024, 65537)
7520 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007521 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7522 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007523
7524 // Check the usage count limit tag appears in the authorizations.
7525 AuthorizationSet auths;
7526 for (auto& entry : key_characteristics_) {
7527 auths.push_back(AuthorizationSet(entry.authorizations));
7528 }
7529 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7530 << "key usage count limit " << 3U << " missing";
7531
7532 string message = "1234567890123456";
7533 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7534
7535 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7536 AuthorizationSet keystore_auths =
7537 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7538
7539 SignMessage(message, params);
7540 SignMessage(message, params);
7541 SignMessage(message, params);
7542
7543 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7544 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7545 // must be invalidated from secure storage (such as RPMB partition).
7546 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7547 } else {
7548 // Usage count limit tag is enforced by keystore, keymint does nothing.
7549 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007550 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007551 }
7552}
7553
Qi Wu8e727f72021-02-11 02:49:33 +08007554/*
7555 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7556 *
7557 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7558 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7559 * in hardware.
7560 */
7561TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01007562 if (SecLevel() == SecurityLevel::STRONGBOX) {
7563 GTEST_SKIP() << "Test not applicable to StrongBox device";
7564 }
Qi Wu8e727f72021-02-11 02:49:33 +08007565
7566 auto error = GenerateKey(AuthorizationSetBuilder()
7567 .RsaSigningKey(2048, 65537)
7568 .Digest(Digest::NONE)
7569 .Padding(PaddingMode::NONE)
7570 .Authorization(TAG_NO_AUTH_REQUIRED)
7571 .Authorization(TAG_ROLLBACK_RESISTANCE)
7572 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007573 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7574 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007575 }
David Drysdale513bf122021-10-06 11:53:13 +01007576
7577 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7578 ASSERT_EQ(ErrorCode::OK, error);
7579 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7580 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7581 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7582
7583 // The KeyMint should also enforce single use key in hardware when it supports rollback
7584 // resistance.
7585 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7586 .Authorization(TAG_NO_AUTH_REQUIRED)
7587 .RsaSigningKey(1024, 65537)
7588 .NoDigestOrPadding()
7589 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7590 .SetDefaultValidity()));
7591
7592 // Check the usage count limit tag appears in the hardware authorizations.
7593 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7594 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7595 << "key usage count limit " << 1U << " missing";
7596
7597 string message = "1234567890123456";
7598 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7599
7600 // First usage of RSA key should work.
7601 SignMessage(message, params);
7602
7603 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7604 // must be invalidated from secure storage (such as RPMB partition).
7605 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007606}
7607
Qi Wud22ec842020-11-26 13:27:53 +08007608INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7609
David Drysdale7de9feb2021-03-05 14:56:19 +00007610typedef KeyMintAidlTestBase GetHardwareInfoTest;
7611
7612TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7613 // Retrieving hardware info should give the same result each time.
7614 KeyMintHardwareInfo info;
7615 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7616 KeyMintHardwareInfo info2;
7617 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7618 EXPECT_EQ(info, info2);
7619}
7620
7621INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7622
Selene Huang31ab4042020-04-29 04:22:39 -07007623typedef KeyMintAidlTestBase AddEntropyTest;
7624
7625/*
7626 * AddEntropyTest.AddEntropy
7627 *
7628 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7629 * is actually added.
7630 */
7631TEST_P(AddEntropyTest, AddEntropy) {
7632 string data = "foo";
7633 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7634}
7635
7636/*
7637 * AddEntropyTest.AddEmptyEntropy
7638 *
7639 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7640 */
7641TEST_P(AddEntropyTest, AddEmptyEntropy) {
7642 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7643}
7644
7645/*
7646 * AddEntropyTest.AddLargeEntropy
7647 *
7648 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7649 */
7650TEST_P(AddEntropyTest, AddLargeEntropy) {
7651 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7652}
7653
David Drysdalebb3d85e2021-04-13 11:15:51 +01007654/*
7655 * AddEntropyTest.AddTooLargeEntropy
7656 *
7657 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7658 */
7659TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7660 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7661 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7662}
7663
Selene Huang31ab4042020-04-29 04:22:39 -07007664INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7665
Selene Huang31ab4042020-04-29 04:22:39 -07007666typedef KeyMintAidlTestBase KeyDeletionTest;
7667
7668/**
7669 * KeyDeletionTest.DeleteKey
7670 *
7671 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7672 * valid key blob.
7673 */
7674TEST_P(KeyDeletionTest, DeleteKey) {
7675 auto error = GenerateKey(AuthorizationSetBuilder()
7676 .RsaSigningKey(2048, 65537)
7677 .Digest(Digest::NONE)
7678 .Padding(PaddingMode::NONE)
7679 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007680 .Authorization(TAG_ROLLBACK_RESISTANCE)
7681 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007682 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7683 GTEST_SKIP() << "Rollback resistance not supported";
7684 }
Selene Huang31ab4042020-04-29 04:22:39 -07007685
7686 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007687 ASSERT_EQ(ErrorCode::OK, error);
7688 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7689 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007690
David Drysdale513bf122021-10-06 11:53:13 +01007691 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007692
David Drysdale513bf122021-10-06 11:53:13 +01007693 string message = "12345678901234567890123456789012";
7694 AuthorizationSet begin_out_params;
7695 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7696 Begin(KeyPurpose::SIGN, key_blob_,
7697 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7698 &begin_out_params));
7699 AbortIfNeeded();
7700 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007701}
7702
7703/**
7704 * KeyDeletionTest.DeleteInvalidKey
7705 *
7706 * This test checks that the HAL excepts invalid key blobs..
7707 */
7708TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7709 // Generate key just to check if rollback protection is implemented
7710 auto error = GenerateKey(AuthorizationSetBuilder()
7711 .RsaSigningKey(2048, 65537)
7712 .Digest(Digest::NONE)
7713 .Padding(PaddingMode::NONE)
7714 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007715 .Authorization(TAG_ROLLBACK_RESISTANCE)
7716 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007717 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7718 GTEST_SKIP() << "Rollback resistance not supported";
7719 }
Selene Huang31ab4042020-04-29 04:22:39 -07007720
7721 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007722 ASSERT_EQ(ErrorCode::OK, error);
7723 AuthorizationSet enforced(SecLevelAuthorizations());
7724 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007725
David Drysdale513bf122021-10-06 11:53:13 +01007726 // Delete the key we don't care about the result at this point.
7727 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007728
David Drysdale513bf122021-10-06 11:53:13 +01007729 // Now create an invalid key blob and delete it.
7730 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007731
David Drysdale513bf122021-10-06 11:53:13 +01007732 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007733}
7734
7735/**
7736 * KeyDeletionTest.DeleteAllKeys
7737 *
7738 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7739 *
7740 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7741 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7742 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7743 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7744 * credentials stored in Keystore/Keymint.
7745 */
7746TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007747 if (!arm_deleteAllKeys) {
7748 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7749 return;
7750 }
Selene Huang31ab4042020-04-29 04:22:39 -07007751 auto error = GenerateKey(AuthorizationSetBuilder()
7752 .RsaSigningKey(2048, 65537)
7753 .Digest(Digest::NONE)
7754 .Padding(PaddingMode::NONE)
7755 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007756 .Authorization(TAG_ROLLBACK_RESISTANCE)
7757 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007758 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7759 GTEST_SKIP() << "Rollback resistance not supported";
7760 }
Selene Huang31ab4042020-04-29 04:22:39 -07007761
7762 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007763 ASSERT_EQ(ErrorCode::OK, error);
7764 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7765 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007766
David Drysdale513bf122021-10-06 11:53:13 +01007767 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007768
David Drysdale513bf122021-10-06 11:53:13 +01007769 string message = "12345678901234567890123456789012";
7770 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07007771
David Drysdale513bf122021-10-06 11:53:13 +01007772 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7773 Begin(KeyPurpose::SIGN, key_blob_,
7774 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7775 &begin_out_params));
7776 AbortIfNeeded();
7777 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007778}
7779
7780INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
7781
David Drysdaled2cc8c22021-04-15 13:29:45 +01007782typedef KeyMintAidlTestBase KeyUpgradeTest;
7783
7784/**
7785 * KeyUpgradeTest.UpgradeInvalidKey
7786 *
7787 * This test checks that the HAL excepts invalid key blobs..
7788 */
7789TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
7790 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
7791
7792 std::vector<uint8_t> new_blob;
7793 Status result = keymint_->upgradeKey(key_blob,
7794 AuthorizationSetBuilder()
7795 .Authorization(TAG_APPLICATION_ID, "clientid")
7796 .Authorization(TAG_APPLICATION_DATA, "appdata")
7797 .vector_data(),
7798 &new_blob);
7799 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
7800}
7801
7802INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
7803
Selene Huang31ab4042020-04-29 04:22:39 -07007804using UpgradeKeyTest = KeyMintAidlTestBase;
7805
7806/*
7807 * UpgradeKeyTest.UpgradeKey
7808 *
7809 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
7810 */
7811TEST_P(UpgradeKeyTest, UpgradeKey) {
7812 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7813 .AesEncryptionKey(128)
7814 .Padding(PaddingMode::NONE)
7815 .Authorization(TAG_NO_AUTH_REQUIRED)));
7816
7817 auto result = UpgradeKey(key_blob_);
7818
7819 // Key doesn't need upgrading. Should get okay, but no new key blob.
7820 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
7821}
7822
7823INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
7824
7825using ClearOperationsTest = KeyMintAidlTestBase;
7826
7827/*
7828 * ClearSlotsTest.TooManyOperations
7829 *
7830 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
7831 * operations are started without being finished or aborted. Also verifies
7832 * that aborting the operations clears the operations.
7833 *
7834 */
7835TEST_P(ClearOperationsTest, TooManyOperations) {
7836 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7837 .Authorization(TAG_NO_AUTH_REQUIRED)
7838 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08007839 .Padding(PaddingMode::NONE)
7840 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007841
7842 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
7843 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08007844 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07007845 AuthorizationSet out_params;
7846 ErrorCode result;
7847 size_t i;
7848
7849 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00007850 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07007851 if (ErrorCode::OK != result) {
7852 break;
7853 }
7854 }
7855 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
7856 // Try again just in case there's a weird overflow bug
7857 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00007858 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007859 for (size_t j = 0; j < i; j++) {
7860 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
7861 << "Aboort failed for i = " << j << std::endl;
7862 }
David Drysdale7fc26b92022-05-13 09:54:24 +01007863 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007864 AbortIfNeeded();
7865}
7866
7867INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
7868
7869typedef KeyMintAidlTestBase TransportLimitTest;
7870
7871/*
David Drysdale7de9feb2021-03-05 14:56:19 +00007872 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07007873 *
7874 * Verifies that passing input data to finish succeeds as expected.
7875 */
7876TEST_P(TransportLimitTest, LargeFinishInput) {
7877 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7878 .Authorization(TAG_NO_AUTH_REQUIRED)
7879 .AesEncryptionKey(128)
7880 .BlockMode(BlockMode::ECB)
7881 .Padding(PaddingMode::NONE)));
7882
7883 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
7884 auto cipher_params =
7885 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7886
7887 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007888 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007889
7890 string plain_message = std::string(1 << msg_size, 'x');
7891 string encrypted_message;
7892 auto rc = Finish(plain_message, &encrypted_message);
7893
7894 EXPECT_EQ(ErrorCode::OK, rc);
7895 EXPECT_EQ(plain_message.size(), encrypted_message.size())
7896 << "Encrypt finish returned OK, but did not consume all of the given input";
7897 cipher_params.push_back(out_params);
7898
David Drysdale7fc26b92022-05-13 09:54:24 +01007899 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007900
7901 string decrypted_message;
7902 rc = Finish(encrypted_message, &decrypted_message);
7903 EXPECT_EQ(ErrorCode::OK, rc);
7904 EXPECT_EQ(plain_message.size(), decrypted_message.size())
7905 << "Decrypt finish returned OK, did not consume all of the given input";
7906 }
7907}
7908
7909INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
7910
Seth Moored79a0ec2021-12-13 20:03:33 +00007911static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05007912 switch (curve) {
7913 case EcCurve::P_224:
7914 return NID_secp224r1;
7915 case EcCurve::P_256:
7916 return NID_X9_62_prime256v1;
7917 case EcCurve::P_384:
7918 return NID_secp384r1;
7919 case EcCurve::P_521:
7920 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00007921 case EcCurve::CURVE_25519:
7922 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05007923 }
7924}
7925
David Drysdale42fe1892021-10-14 14:43:46 +01007926class KeyAgreementTest : public KeyMintAidlTestBase {
7927 protected:
7928 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
7929 std::vector<uint8_t>* localPublicKey) {
7930 // Generate EC key locally (with access to private key material)
7931 if (localCurve == EcCurve::CURVE_25519) {
7932 uint8_t privKeyData[32];
7933 uint8_t pubKeyData[32];
7934 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01007935 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
7936 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
7937 } else {
7938 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
7939 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
7940 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
7941 ASSERT_NE(group, nullptr);
7942 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
7943 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
7944 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
7945 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01007946 }
David Drysdalea410b772022-05-09 16:44:13 +01007947
7948 // Get encoded form of the public part of the locally generated key...
7949 unsigned char* p = nullptr;
7950 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
7951 ASSERT_GT(localPublicKeySize, 0);
7952 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
7953 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
7954 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01007955 }
7956
7957 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
7958 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00007959 auto builder = AuthorizationSetBuilder()
7960 .Authorization(TAG_NO_AUTH_REQUIRED)
7961 .Authorization(TAG_EC_CURVE, curve)
7962 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7963 .Authorization(TAG_ALGORITHM, Algorithm::EC)
7964 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
7965 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
7966 .SetDefaultValidity();
7967 ErrorCode result = GenerateKey(builder);
7968
7969 if (SecLevel() == SecurityLevel::STRONGBOX) {
7970 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
7971 result = GenerateKeyWithSelfSignedAttestKey(
7972 AuthorizationSetBuilder()
7973 .EcdsaKey(EcCurve::P_256)
7974 .AttestKey()
7975 .SetDefaultValidity(), /* attest key params */
7976 builder, &key_blob_, &key_characteristics_, &cert_chain_);
7977 }
7978 }
David Drysdale42fe1892021-10-14 14:43:46 +01007979 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
7980 ASSERT_GT(cert_chain_.size(), 0);
7981 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7982 ASSERT_NE(kmKeyCert, nullptr);
7983 // Check that keyAgreement (bit 4) is set in KeyUsage
7984 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
7985 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
7986 ASSERT_NE(*kmPubKey, nullptr);
7987 if (dump_Attestations) {
7988 for (size_t n = 0; n < cert_chain_.size(); n++) {
7989 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
7990 }
7991 }
7992 }
7993
7994 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
7995 const std::vector<uint8_t>& localPublicKey) {
7996 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7997 string ZabFromKeyMintStr;
7998 ASSERT_EQ(ErrorCode::OK,
7999 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8000 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8001 vector<uint8_t> ZabFromTest;
8002
8003 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8004 size_t kmPubKeySize = 32;
8005 uint8_t kmPubKeyData[32];
8006 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8007 ASSERT_EQ(kmPubKeySize, 32);
8008
8009 uint8_t localPrivKeyData[32];
8010 size_t localPrivKeySize = 32;
8011 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8012 &localPrivKeySize));
8013 ASSERT_EQ(localPrivKeySize, 32);
8014
8015 uint8_t sharedKey[32];
8016 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8017 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8018 } else {
8019 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8020 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8021 ASSERT_NE(ctx, nullptr);
8022 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8023 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8024 size_t ZabFromTestLen = 0;
8025 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8026 ZabFromTest.resize(ZabFromTestLen);
8027 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8028 }
8029 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8030 }
8031};
8032
David Zeuthene0c40892021-01-08 12:54:11 -05008033/*
8034 * KeyAgreementTest.Ecdh
8035 *
David Drysdale42fe1892021-10-14 14:43:46 +01008036 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008037 */
8038TEST_P(KeyAgreementTest, Ecdh) {
8039 // Because it's possible to use this API with keys on different curves, we
8040 // check all N^2 combinations where N is the number of supported
8041 // curves.
8042 //
8043 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8044 // lot more curves we can be smart about things and just pick |otherCurve| so
8045 // it's not |curve| and that way we end up with only 2*N runs
8046 //
8047 for (auto curve : ValidCurves()) {
8048 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008049 SCOPED_TRACE(testing::Message()
8050 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8051
David Zeuthene0c40892021-01-08 12:54:11 -05008052 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008053 EVP_PKEY_Ptr localPrivKey;
8054 vector<uint8_t> localPublicKey;
8055 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008056
8057 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008058 EVP_PKEY_Ptr kmPubKey;
8059 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008060
8061 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8062 if (curve != localCurve) {
8063 // If the keys are using different curves KeyMint should fail with
8064 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008065 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008066 string ZabFromKeyMintStr;
8067 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008068 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008069 &ZabFromKeyMintStr));
8070
8071 } else {
8072 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008073 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008074 }
8075
8076 CheckedDeleteKey();
8077 }
8078 }
8079}
8080
David Drysdale42fe1892021-10-14 14:43:46 +01008081/*
8082 * KeyAgreementTest.EcdhCurve25519
8083 *
8084 * Verifies that ECDH works for curve25519. This is also covered by the general
8085 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8086 * KeyMint 1.0.
8087 */
8088TEST_P(KeyAgreementTest, EcdhCurve25519) {
8089 if (!Curve25519Supported()) {
8090 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8091 }
8092
8093 // Generate EC key in KeyMint (only access to public key material)
8094 EcCurve curve = EcCurve::CURVE_25519;
8095 EVP_PKEY_Ptr kmPubKey = nullptr;
8096 GenerateKeyMintEcKey(curve, &kmPubKey);
8097
8098 // Generate EC key on same curve locally (with access to private key material).
8099 EVP_PKEY_Ptr privKey;
8100 vector<uint8_t> encodedPublicKey;
8101 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8102
8103 // Agree on a key between local and KeyMint and check it.
8104 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8105
8106 CheckedDeleteKey();
8107}
8108
8109/*
8110 * KeyAgreementTest.EcdhCurve25519Imported
8111 *
8112 * Verifies that ECDH works for an imported curve25519 key.
8113 */
8114TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8115 if (!Curve25519Supported()) {
8116 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8117 }
8118
8119 // Import x25519 key into KeyMint.
8120 EcCurve curve = EcCurve::CURVE_25519;
8121 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8122 .Authorization(TAG_NO_AUTH_REQUIRED)
8123 .EcdsaKey(EcCurve::CURVE_25519)
8124 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8125 .SetDefaultValidity(),
8126 KeyFormat::PKCS8, x25519_pkcs8_key));
8127 ASSERT_GT(cert_chain_.size(), 0);
8128 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8129 ASSERT_NE(kmKeyCert, nullptr);
8130 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8131 ASSERT_NE(kmPubKey.get(), nullptr);
8132
8133 // Expect the import to emit corresponding public key data.
8134 size_t kmPubKeySize = 32;
8135 uint8_t kmPubKeyData[32];
8136 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8137 ASSERT_EQ(kmPubKeySize, 32);
8138 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8139 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8140
8141 // Generate EC key on same curve locally (with access to private key material).
8142 EVP_PKEY_Ptr privKey;
8143 vector<uint8_t> encodedPublicKey;
8144 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8145
8146 // Agree on a key between local and KeyMint and check it.
8147 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8148
8149 CheckedDeleteKey();
8150}
8151
8152/*
8153 * KeyAgreementTest.EcdhCurve25519InvalidSize
8154 *
8155 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8156 */
8157TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8158 if (!Curve25519Supported()) {
8159 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8160 }
8161
8162 // Generate EC key in KeyMint (only access to public key material)
8163 EcCurve curve = EcCurve::CURVE_25519;
8164 EVP_PKEY_Ptr kmPubKey = nullptr;
8165 GenerateKeyMintEcKey(curve, &kmPubKey);
8166
8167 // Generate EC key on same curve locally (with access to private key material).
8168 EVP_PKEY_Ptr privKey;
8169 vector<uint8_t> encodedPublicKey;
8170 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8171
8172 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8173 string ZabFromKeyMintStr;
8174 // Send in an incomplete public key.
8175 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8176 &ZabFromKeyMintStr));
8177
8178 CheckedDeleteKey();
8179}
8180
8181/*
8182 * KeyAgreementTest.EcdhCurve25519Mismatch
8183 *
8184 * Verifies that ECDH fails between curve25519 and other curves.
8185 */
8186TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8187 if (!Curve25519Supported()) {
8188 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8189 }
8190
8191 // Generate EC key in KeyMint (only access to public key material)
8192 EcCurve curve = EcCurve::CURVE_25519;
8193 EVP_PKEY_Ptr kmPubKey = nullptr;
8194 GenerateKeyMintEcKey(curve, &kmPubKey);
8195
8196 for (auto localCurve : ValidCurves()) {
8197 if (localCurve == curve) {
8198 continue;
8199 }
8200 // Generate EC key on a different curve locally (with access to private key material).
8201 EVP_PKEY_Ptr privKey;
8202 vector<uint8_t> encodedPublicKey;
8203 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8204
David Drysdale7fc26b92022-05-13 09:54:24 +01008205 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008206 string ZabFromKeyMintStr;
8207 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8208 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8209 &ZabFromKeyMintStr));
8210 }
8211
8212 CheckedDeleteKey();
8213}
8214
David Zeuthene0c40892021-01-08 12:54:11 -05008215INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8216
David Drysdaled2cc8c22021-04-15 13:29:45 +01008217using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8218
8219// This is a problematic test, as it can render the device under test permanently unusable.
8220// Re-enable and run at your own risk.
8221TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8222 auto result = DestroyAttestationIds();
8223 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8224}
8225
8226INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8227
Shawn Willdend659c7c2021-02-19 14:51:51 -07008228using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008229
David Drysdaledb0dcf52021-05-18 11:43:31 +01008230/*
8231 * EarlyBootKeyTest.CreateEarlyBootKeys
8232 *
8233 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8234 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008235TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008236 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008237 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8238 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8239
David Drysdaleadfe6112021-05-27 12:00:53 +01008240 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8241 ASSERT_GT(keyData.blob.size(), 0U);
8242 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8243 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8244 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008245 CheckedDeleteKey(&aesKeyData.blob);
8246 CheckedDeleteKey(&hmacKeyData.blob);
8247 CheckedDeleteKey(&rsaKeyData.blob);
8248 CheckedDeleteKey(&ecdsaKeyData.blob);
8249}
8250
David Drysdaledb0dcf52021-05-18 11:43:31 +01008251/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008252 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8253 *
8254 * Verifies that creating an early boot key with attestation succeeds.
8255 */
8256TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8257 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8258 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8259 builder->AttestationChallenge("challenge");
8260 builder->AttestationApplicationId("app_id");
8261 });
8262
8263 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008264 // Strongbox may not support factory attestation. Key creation might fail with
8265 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8266 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8267 continue;
8268 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008269 ASSERT_GT(keyData.blob.size(), 0U);
8270 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8271 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8272 }
8273 CheckedDeleteKey(&aesKeyData.blob);
8274 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00008275 if (rsaKeyData.blob.size() != 0U) {
8276 CheckedDeleteKey(&rsaKeyData.blob);
8277 }
8278 if (ecdsaKeyData.blob.size() != 0U) {
8279 CheckedDeleteKey(&ecdsaKeyData.blob);
8280 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008281}
8282
8283/*
8284 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008285 *
8286 * Verifies that using early boot keys at a later stage fails.
8287 */
8288TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8289 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8290 .Authorization(TAG_NO_AUTH_REQUIRED)
8291 .Authorization(TAG_EARLY_BOOT_ONLY)
8292 .HmacKey(128)
8293 .Digest(Digest::SHA_2_256)
8294 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8295 AuthorizationSet output_params;
8296 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8297 AuthorizationSetBuilder()
8298 .Digest(Digest::SHA_2_256)
8299 .Authorization(TAG_MAC_LENGTH, 256),
8300 &output_params));
8301}
8302
8303/*
8304 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8305 *
8306 * Verifies that importing early boot keys fails.
8307 */
8308TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8309 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8310 .Authorization(TAG_NO_AUTH_REQUIRED)
8311 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008312 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008313 .Digest(Digest::SHA_2_256)
8314 .SetDefaultValidity(),
8315 KeyFormat::PKCS8, ec_256_key));
8316}
8317
David Drysdaled2cc8c22021-04-15 13:29:45 +01008318// 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 +00008319// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8320// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8321// early boot, so you'll have to reboot between runs.
8322TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8323 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8324 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8325 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8326 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8327 EXPECT_TRUE(
8328 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8329 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8330 EXPECT_TRUE(
8331 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8332
8333 // Should be able to use keys, since early boot has not ended
8334 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8335 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8336 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8337 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8338
8339 // End early boot
8340 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8341 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8342
8343 // Should not be able to use already-created keys.
8344 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8345 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8346 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8347 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8348
8349 CheckedDeleteKey(&aesKeyData.blob);
8350 CheckedDeleteKey(&hmacKeyData.blob);
8351 CheckedDeleteKey(&rsaKeyData.blob);
8352 CheckedDeleteKey(&ecdsaKeyData.blob);
8353
8354 // Should not be able to create new keys
8355 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
8356 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
8357
8358 CheckedDeleteKey(&aesKeyData.blob);
8359 CheckedDeleteKey(&hmacKeyData.blob);
8360 CheckedDeleteKey(&rsaKeyData.blob);
8361 CheckedDeleteKey(&ecdsaKeyData.blob);
8362}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008363
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008364INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8365
Shawn Willdend659c7c2021-02-19 14:51:51 -07008366using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008367
8368// This may be a problematic test. It can't be run repeatedly without unlocking the device in
8369// between runs... and on most test devices there are no enrolled credentials so it can't be
8370// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8371// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8372// a manual test process, which includes unlocking between runs, which is why it's included here.
8373// Well, that and the fact that it's the only test we can do without also making calls into the
8374// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8375// implications might be, so that may or may not be a solution.
8376TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8377 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8378 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
8379
8380 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8381 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8382 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8383 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8384
8385 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008386 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008387 ASSERT_EQ(ErrorCode::OK, rc);
8388 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8389 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8390 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8391 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
8392
8393 CheckedDeleteKey(&aesKeyData.blob);
8394 CheckedDeleteKey(&hmacKeyData.blob);
8395 CheckedDeleteKey(&rsaKeyData.blob);
8396 CheckedDeleteKey(&ecdsaKeyData.blob);
8397}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008398
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008399INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8400
Shawn Willden22fb9c12022-06-02 14:04:33 -06008401using VsrRequirementTest = KeyMintAidlTestBase;
8402
8403TEST_P(VsrRequirementTest, Vsr13Test) {
8404 int vsr_api_level = get_vsr_api_level();
8405 if (vsr_api_level < 33) {
8406 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8407 }
8408 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8409}
8410
8411INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8412
Janis Danisevskis24c04702020-12-16 18:28:39 -08008413} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008414
8415int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008416 std::cout << "Testing ";
8417 auto halInstances =
8418 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8419 std::cout << "HAL instances:\n";
8420 for (auto& entry : halInstances) {
8421 std::cout << " " << entry << '\n';
8422 }
8423
Selene Huang31ab4042020-04-29 04:22:39 -07008424 ::testing::InitGoogleTest(&argc, argv);
8425 for (int i = 1; i < argc; ++i) {
8426 if (argv[i][0] == '-') {
8427 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008428 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8429 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008430 }
8431 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008432 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8433 dump_Attestations = true;
8434 } else {
8435 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008436 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008437 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8438 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8439 // be run in emulated environments that don't have the normal bootloader
8440 // interactions.
8441 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8442 }
Selene Huang31ab4042020-04-29 04:22:39 -07008443 }
8444 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008445 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008446}