blob: 4f5d82168410e4abbcfdde8956ff915e01db22ce [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)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100744 SCOPED_TRACE(testing::Message() << "AES-unknown-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000745 vector<uint8_t> key_blob;
746 vector<KeyCharacteristics> key_characteristics;
747 // No key size specified
748 auto builder = AuthorizationSetBuilder()
749 .Authorization(TAG_ALGORITHM, Algorithm::AES)
750 .BlockMode(block_mode)
751 .Padding(padding_mode)
752 .SetDefaultValidity();
753 if (block_mode == BlockMode::GCM) {
754 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
755 }
756 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
757 GenerateKey(builder, &key_blob, &key_characteristics));
758 }
759 }
760}
761
762/*
763 * NewKeyGenerationTest.AesInvalidPadding
764 *
765 * Verifies that specifying an invalid padding on AES keys gives a failure
766 * somewhere along the way.
767 */
768TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
769 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
770 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
771 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
772 SCOPED_TRACE(testing::Message()
773 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000774 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800775 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000776 .AesEncryptionKey(key_size)
777 .BlockMode(block_mode)
778 .Padding(padding_mode)
779 .SetDefaultValidity();
780 if (block_mode == BlockMode::GCM) {
781 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
782 }
783
Tommy Chiu3950b452021-05-03 22:01:46 +0800784 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000785 if (result == ErrorCode::OK) {
786 // Key creation was OK but has generated a key that cannot be used.
787 auto params =
788 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800789 if (block_mode == BlockMode::GCM) {
790 params.Authorization(TAG_MAC_LENGTH, 128);
791 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000792 auto result = Begin(KeyPurpose::ENCRYPT, params);
793 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100794 result == ErrorCode::INVALID_KEY_BLOB)
795 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000796 } else {
797 // The KeyMint implementation detected that the generated key
798 // is unusable.
799 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
800 }
801 }
802 }
803 }
804}
805
806/*
807 * NewKeyGenerationTest.AesGcmMissingMinMac
808 *
809 * Verifies that specifying an invalid key size for AES key generation returns
810 * UNSUPPORTED_KEY_SIZE.
811 */
812TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
813 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
814 BlockMode block_mode = BlockMode::GCM;
815 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
816 SCOPED_TRACE(testing::Message()
817 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
818 vector<uint8_t> key_blob;
819 vector<KeyCharacteristics> key_characteristics;
820 // No MIN_MAC_LENGTH provided.
821 auto builder = AuthorizationSetBuilder()
822 .AesEncryptionKey(key_size)
823 .BlockMode(block_mode)
824 .Padding(padding_mode)
825 .SetDefaultValidity();
826 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
827 GenerateKey(builder, &key_blob, &key_characteristics));
828 }
829 }
830}
831
832/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100833 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
834 *
835 * Verifies that specifying an invalid min MAC size for AES key generation returns
836 * UNSUPPORTED_MIN_MAC_LENGTH.
837 */
838TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
839 for (size_t min_mac_len : {88, 136}) {
840 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
841 BlockMode block_mode = BlockMode::GCM;
842 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
843 SCOPED_TRACE(testing::Message()
844 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
845 vector<uint8_t> key_blob;
846 vector<KeyCharacteristics> key_characteristics;
847 auto builder = AuthorizationSetBuilder()
848 .AesEncryptionKey(key_size)
849 .BlockMode(block_mode)
850 .Padding(padding_mode)
851 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
852 .SetDefaultValidity();
853 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
854 GenerateKey(builder, &key_blob, &key_characteristics));
855 }
856 }
857 }
858}
859
860/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000861 * NewKeyGenerationTest.TripleDes
862 *
863 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
864 * have correct characteristics.
865 */
866TEST_P(NewKeyGenerationTest, TripleDes) {
867 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
868 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
869 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
870 SCOPED_TRACE(testing::Message()
871 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
872 vector<uint8_t> key_blob;
873 vector<KeyCharacteristics> key_characteristics;
874 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
875 .TripleDesEncryptionKey(key_size)
876 .BlockMode(block_mode)
877 .Padding(padding_mode)
878 .Authorization(TAG_NO_AUTH_REQUIRED)
879 .SetDefaultValidity(),
880 &key_blob, &key_characteristics));
881
882 EXPECT_GT(key_blob.size(), 0U);
883 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100884 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000885
886 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
887
888 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
889 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
890 << "Key size " << key_size << "missing";
891
892 CheckedDeleteKey(&key_blob);
893 }
894 }
895 }
896}
897
898/*
899 * NewKeyGenerationTest.TripleDesWithAttestation
900 *
901 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
902 * have correct characteristics.
903 *
904 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
905 * put in a certificate) but which isn't an error.
906 */
907TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
908 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
909 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
910 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
911 SCOPED_TRACE(testing::Message()
912 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
913
914 auto challenge = "hello";
915 auto app_id = "foo";
916
917 vector<uint8_t> key_blob;
918 vector<KeyCharacteristics> key_characteristics;
919 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
920 .TripleDesEncryptionKey(key_size)
921 .BlockMode(block_mode)
922 .Padding(padding_mode)
923 .Authorization(TAG_NO_AUTH_REQUIRED)
924 .AttestationChallenge(challenge)
925 .AttestationApplicationId(app_id)
926 .SetDefaultValidity(),
927 &key_blob, &key_characteristics));
928
929 EXPECT_GT(key_blob.size(), 0U);
930 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100931 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000932
933 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
934
935 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
936 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
937 << "Key size " << key_size << "missing";
938
939 CheckedDeleteKey(&key_blob);
940 }
941 }
942 }
943}
944
945/*
946 * NewKeyGenerationTest.TripleDesInvalidSize
947 *
948 * Verifies that specifying an invalid key size for 3-DES key generation returns
949 * UNSUPPORTED_KEY_SIZE.
950 */
951TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
952 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
953 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
954 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
955 SCOPED_TRACE(testing::Message()
956 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
957 vector<uint8_t> key_blob;
958 vector<KeyCharacteristics> key_characteristics;
959 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
960 GenerateKey(AuthorizationSetBuilder()
961 .TripleDesEncryptionKey(key_size)
962 .BlockMode(block_mode)
963 .Padding(padding_mode)
964 .Authorization(TAG_NO_AUTH_REQUIRED)
965 .SetDefaultValidity(),
966 &key_blob, &key_characteristics));
967 }
968 }
969 }
970
971 // Omitting the key size fails.
972 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
973 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
974 SCOPED_TRACE(testing::Message()
975 << "3DES-default-" << block_mode << "-" << padding_mode);
976 vector<uint8_t> key_blob;
977 vector<KeyCharacteristics> key_characteristics;
978 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
979 GenerateKey(AuthorizationSetBuilder()
980 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
981 .BlockMode(block_mode)
982 .Padding(padding_mode)
983 .Authorization(TAG_NO_AUTH_REQUIRED)
984 .SetDefaultValidity(),
985 &key_blob, &key_characteristics));
986 }
987 }
988}
989
990/*
Selene Huang31ab4042020-04-29 04:22:39 -0700991 * NewKeyGenerationTest.Rsa
992 *
993 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
994 * have correct characteristics.
995 */
996TEST_P(NewKeyGenerationTest, Rsa) {
997 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100998 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -0700999 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001000 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001001 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1002 .RsaSigningKey(key_size, 65537)
1003 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001004 .Padding(PaddingMode::NONE)
1005 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001006 &key_blob, &key_characteristics));
1007
1008 ASSERT_GT(key_blob.size(), 0U);
1009 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001010 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001011
Shawn Willden7f424372021-01-10 18:06:50 -07001012 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001013
1014 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1015 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1016 << "Key size " << key_size << "missing";
1017 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1018
1019 CheckedDeleteKey(&key_blob);
1020 }
1021}
1022
1023/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001024 * NewKeyGenerationTest.RsaWithMissingValidity
1025 *
1026 * Verifies that keymint returns an error while generating asymmetric key
1027 * without providing NOT_BEFORE and NOT_AFTER parameters.
1028 */
1029TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
1030 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1031 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1032 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1033
1034 vector<uint8_t> key_blob;
1035 vector<KeyCharacteristics> key_characteristics;
1036 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1037 GenerateKey(AuthorizationSetBuilder()
1038 .RsaSigningKey(2048, 65537)
1039 .Digest(Digest::NONE)
1040 .Padding(PaddingMode::NONE)
1041 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1042 kUndefinedExpirationDateTime),
1043 &key_blob, &key_characteristics));
1044
1045 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1046 GenerateKey(AuthorizationSetBuilder()
1047 .RsaSigningKey(2048, 65537)
1048 .Digest(Digest::NONE)
1049 .Padding(PaddingMode::NONE)
1050 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1051 &key_blob, &key_characteristics));
1052}
1053
1054/*
Qi Wud22ec842020-11-26 13:27:53 +08001055 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001056 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001057 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1058 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001059 */
1060TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001061 auto challenge = "hello";
1062 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001063
Selene Huang6e46f142021-04-20 19:20:11 -07001064 auto subject = "cert subj 2";
1065 vector<uint8_t> subject_der(make_name_from_str(subject));
1066
1067 uint64_t serial_int = 66;
1068 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1069
Selene Huang4f64c222021-04-13 19:54:36 -07001070 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001071 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001072 vector<uint8_t> key_blob;
1073 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001074 auto builder = AuthorizationSetBuilder()
1075 .RsaSigningKey(key_size, 65537)
1076 .Digest(Digest::NONE)
1077 .Padding(PaddingMode::NONE)
1078 .AttestationChallenge(challenge)
1079 .AttestationApplicationId(app_id)
1080 .Authorization(TAG_NO_AUTH_REQUIRED)
1081 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1082 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1083 .SetDefaultValidity();
1084
1085 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001086 // Strongbox may not support factory provisioned attestation key.
1087 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001088 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1089 result = GenerateKeyWithSelfSignedAttestKey(
1090 AuthorizationSetBuilder()
1091 .RsaKey(key_size, 65537)
1092 .AttestKey()
1093 .SetDefaultValidity(), /* attest key params */
1094 builder, &key_blob, &key_characteristics);
1095 }
subrahmanyaman05642492022-02-05 07:10:56 +00001096 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001097 ASSERT_EQ(ErrorCode::OK, result);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001098 ASSERT_GT(key_blob.size(), 0U);
1099 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001100 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001101
1102 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1103
1104 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1105 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1106 << "Key size " << key_size << "missing";
1107 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1108
David Drysdalea8a888e2022-06-08 12:43:56 +01001109 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001110 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001111 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001112
1113 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1114 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001115 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001116 sw_enforced, hw_enforced, SecLevel(),
1117 cert_chain_[0].encodedCertificate));
1118
1119 CheckedDeleteKey(&key_blob);
1120 }
1121}
1122
1123/*
David Drysdale4dc01072021-04-01 12:17:35 +01001124 * NewKeyGenerationTest.RsaWithRpkAttestation
1125 *
1126 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
1127 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale0fce69d2021-04-13 17:22:13 +01001128 *
1129 * This test is disabled because the KeyMint specification does not require that implementations
1130 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
1131 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +01001132 */
David Drysdale0fce69d2021-04-13 17:22:13 +01001133TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +01001134 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
1135 // instance.
1136 std::shared_ptr<IRemotelyProvisionedComponent> rp;
1137 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
1138 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
1139
1140 // Generate a P-256 keypair to use as an attestation key.
1141 MacedPublicKey macedPubKey;
1142 std::vector<uint8_t> privateKeyBlob;
1143 auto status =
1144 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1145 ASSERT_TRUE(status.isOk());
1146 vector<uint8_t> coseKeyData;
1147 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1148
1149 AttestationKey attestation_key;
1150 attestation_key.keyBlob = std::move(privateKeyBlob);
1151 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1152
1153 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001154 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdale4dc01072021-04-01 12:17:35 +01001155 auto challenge = "hello";
1156 auto app_id = "foo";
1157
1158 vector<uint8_t> key_blob;
1159 vector<KeyCharacteristics> key_characteristics;
1160 ASSERT_EQ(ErrorCode::OK,
1161 GenerateKey(AuthorizationSetBuilder()
1162 .RsaSigningKey(key_size, 65537)
1163 .Digest(Digest::NONE)
1164 .Padding(PaddingMode::NONE)
1165 .AttestationChallenge(challenge)
1166 .AttestationApplicationId(app_id)
1167 .Authorization(TAG_NO_AUTH_REQUIRED)
1168 .SetDefaultValidity(),
1169 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1170
1171 ASSERT_GT(key_blob.size(), 0U);
1172 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001173 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001174
1175 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1176
1177 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1178 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1179 << "Key size " << key_size << "missing";
1180 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1181
1182 // Attestation by itself is not valid (last entry is not self-signed).
1183 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1184
1185 // The signature over the attested key should correspond to the P256 public key.
David Drysdalea8a888e2022-06-08 12:43:56 +01001186 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale4dc01072021-04-01 12:17:35 +01001187 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1188 ASSERT_TRUE(key_cert.get());
1189 EVP_PKEY_Ptr signing_pubkey;
1190 p256_pub_key(coseKeyData, &signing_pubkey);
1191 ASSERT_TRUE(signing_pubkey.get());
1192
1193 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1194 << "Verification of attested certificate failed "
1195 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1196
1197 CheckedDeleteKey(&key_blob);
1198 }
1199}
1200
1201/*
Selene Huang4f64c222021-04-13 19:54:36 -07001202 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1203 *
1204 * Verifies that keymint attestation for RSA encryption keys with challenge and
1205 * app id is also successful.
1206 */
1207TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1208 auto key_size = 2048;
1209 auto challenge = "hello";
1210 auto app_id = "foo";
1211
Selene Huang6e46f142021-04-20 19:20:11 -07001212 auto subject = "subj 2";
1213 vector<uint8_t> subject_der(make_name_from_str(subject));
1214
1215 uint64_t serial_int = 111166;
1216 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1217
Selene Huang4f64c222021-04-13 19:54:36 -07001218 vector<uint8_t> key_blob;
1219 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001220 auto builder = AuthorizationSetBuilder()
1221 .RsaEncryptionKey(key_size, 65537)
1222 .Padding(PaddingMode::NONE)
1223 .AttestationChallenge(challenge)
1224 .AttestationApplicationId(app_id)
1225 .Authorization(TAG_NO_AUTH_REQUIRED)
1226 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1227 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1228 .SetDefaultValidity();
1229
1230 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001231 // Strongbox may not support factory provisioned attestation key.
1232 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001233 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1234 result = GenerateKeyWithSelfSignedAttestKey(
1235 AuthorizationSetBuilder()
1236 .RsaKey(key_size, 65537)
1237 .AttestKey()
1238 .SetDefaultValidity(), /* attest key params */
1239 builder, &key_blob, &key_characteristics);
1240 }
subrahmanyaman05642492022-02-05 07:10:56 +00001241 }
1242 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001243
1244 ASSERT_GT(key_blob.size(), 0U);
1245 AuthorizationSet auths;
1246 for (auto& entry : key_characteristics) {
1247 auths.push_back(AuthorizationSet(entry.authorizations));
1248 }
1249
1250 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1251 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1252
1253 // Verify that App data and ROT are NOT included.
1254 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1255 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1256
1257 // Check that some unexpected tags/values are NOT present.
1258 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1259 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1260
1261 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1262
1263 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1264 ASSERT_TRUE(os_ver);
1265 EXPECT_EQ(*os_ver, os_version());
1266
1267 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1268
1269 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1270 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1271 << "Key size " << key_size << "missing";
1272 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1273
David Drysdalea8a888e2022-06-08 12:43:56 +01001274 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001275 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001276 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001277
1278 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1279 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001280 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001281 sw_enforced, hw_enforced, SecLevel(),
1282 cert_chain_[0].encodedCertificate));
1283
1284 CheckedDeleteKey(&key_blob);
1285}
1286
1287/*
1288 * NewKeyGenerationTest.RsaWithSelfSign
1289 *
1290 * Verifies that attesting to RSA key generation is successful, and returns
1291 * self signed certificate if no challenge is provided. And signing etc
1292 * works as expected.
1293 */
1294TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001295 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1296 vector<uint8_t> subject_der(make_name_from_str(subject));
1297
1298 uint64_t serial_int = 0;
1299 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1300
Selene Huang4f64c222021-04-13 19:54:36 -07001301 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001302 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang4f64c222021-04-13 19:54:36 -07001303 vector<uint8_t> key_blob;
1304 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001305 ASSERT_EQ(ErrorCode::OK,
1306 GenerateKey(AuthorizationSetBuilder()
1307 .RsaSigningKey(key_size, 65537)
1308 .Digest(Digest::NONE)
1309 .Padding(PaddingMode::NONE)
1310 .Authorization(TAG_NO_AUTH_REQUIRED)
1311 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1312 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1313 .SetDefaultValidity(),
1314 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001315
1316 ASSERT_GT(key_blob.size(), 0U);
1317 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001318 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001319
1320 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1321
1322 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1323 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1324 << "Key size " << key_size << "missing";
1325 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1326
David Drysdalea8a888e2022-06-08 12:43:56 +01001327 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang6e46f142021-04-20 19:20:11 -07001328 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001329 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001330
1331 CheckedDeleteKey(&key_blob);
1332 }
1333}
1334
1335/*
1336 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1337 *
1338 * Verifies that attesting to RSA checks for missing app ID.
1339 */
1340TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1341 auto challenge = "hello";
1342 vector<uint8_t> key_blob;
1343 vector<KeyCharacteristics> key_characteristics;
1344
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001345 auto builder = AuthorizationSetBuilder()
1346 .RsaSigningKey(2048, 65537)
1347 .Digest(Digest::NONE)
1348 .Padding(PaddingMode::NONE)
1349 .AttestationChallenge(challenge)
1350 .Authorization(TAG_NO_AUTH_REQUIRED)
1351 .SetDefaultValidity();
1352
1353 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001354 // Strongbox may not support factory provisioned attestation key.
1355 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001356 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1357 result = GenerateKeyWithSelfSignedAttestKey(
1358 AuthorizationSetBuilder()
1359 .RsaKey(2048, 65537)
1360 .AttestKey()
1361 .SetDefaultValidity(), /* attest key params */
1362 builder, &key_blob, &key_characteristics);
1363 }
subrahmanyaman05642492022-02-05 07:10:56 +00001364 }
1365 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001366}
1367
1368/*
1369 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1370 *
1371 * Verifies that attesting to RSA ignores app id if challenge is missing.
1372 */
1373TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1374 auto key_size = 2048;
1375 auto app_id = "foo";
1376
Selene Huang6e46f142021-04-20 19:20:11 -07001377 auto subject = "cert subj 2";
1378 vector<uint8_t> subject_der(make_name_from_str(subject));
1379
1380 uint64_t serial_int = 1;
1381 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1382
Selene Huang4f64c222021-04-13 19:54:36 -07001383 vector<uint8_t> key_blob;
1384 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001385 ASSERT_EQ(ErrorCode::OK,
1386 GenerateKey(AuthorizationSetBuilder()
1387 .RsaSigningKey(key_size, 65537)
1388 .Digest(Digest::NONE)
1389 .Padding(PaddingMode::NONE)
1390 .AttestationApplicationId(app_id)
1391 .Authorization(TAG_NO_AUTH_REQUIRED)
1392 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1393 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1394 .SetDefaultValidity(),
1395 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001396
1397 ASSERT_GT(key_blob.size(), 0U);
1398 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001399 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001400
1401 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1402
1403 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1404 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1405 << "Key size " << key_size << "missing";
1406 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1407
David Drysdalea8a888e2022-06-08 12:43:56 +01001408 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001409 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001410 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1411 ASSERT_EQ(cert_chain_.size(), 1);
1412
1413 CheckedDeleteKey(&key_blob);
1414}
1415
1416/*
Qi Wud22ec842020-11-26 13:27:53 +08001417 * NewKeyGenerationTest.LimitedUsageRsa
1418 *
1419 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1420 * resulting keys have correct characteristics.
1421 */
1422TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1423 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001424 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wud22ec842020-11-26 13:27:53 +08001425 vector<uint8_t> key_blob;
1426 vector<KeyCharacteristics> key_characteristics;
1427 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1428 .RsaSigningKey(key_size, 65537)
1429 .Digest(Digest::NONE)
1430 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001431 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1432 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001433 &key_blob, &key_characteristics));
1434
1435 ASSERT_GT(key_blob.size(), 0U);
1436 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001437 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001438
1439 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1440
1441 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1442 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1443 << "Key size " << key_size << "missing";
1444 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1445
1446 // Check the usage count limit tag appears in the authorizations.
1447 AuthorizationSet auths;
1448 for (auto& entry : key_characteristics) {
1449 auths.push_back(AuthorizationSet(entry.authorizations));
1450 }
1451 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1452 << "key usage count limit " << 1U << " missing";
1453
1454 CheckedDeleteKey(&key_blob);
1455 }
1456}
1457
1458/*
Qi Wubeefae42021-01-28 23:16:37 +08001459 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1460 *
1461 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1462 * resulting keys have correct characteristics and attestation.
1463 */
1464TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001465 auto challenge = "hello";
1466 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001467
Selene Huang6e46f142021-04-20 19:20:11 -07001468 auto subject = "cert subj 2";
1469 vector<uint8_t> subject_der(make_name_from_str(subject));
1470
1471 uint64_t serial_int = 66;
1472 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1473
Selene Huang4f64c222021-04-13 19:54:36 -07001474 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001475 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wubeefae42021-01-28 23:16:37 +08001476 vector<uint8_t> key_blob;
1477 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001478 auto builder = AuthorizationSetBuilder()
1479 .RsaSigningKey(key_size, 65537)
1480 .Digest(Digest::NONE)
1481 .Padding(PaddingMode::NONE)
1482 .AttestationChallenge(challenge)
1483 .AttestationApplicationId(app_id)
1484 .Authorization(TAG_NO_AUTH_REQUIRED)
1485 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1486 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1487 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1488 .SetDefaultValidity();
1489
1490 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001491 // Strongbox may not support factory provisioned attestation key.
1492 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001493 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1494 result = GenerateKeyWithSelfSignedAttestKey(
1495 AuthorizationSetBuilder()
1496 .RsaKey(key_size, 65537)
1497 .AttestKey()
1498 .SetDefaultValidity(), /* attest key params */
1499 builder, &key_blob, &key_characteristics);
1500 }
subrahmanyaman05642492022-02-05 07:10:56 +00001501 }
1502 ASSERT_EQ(ErrorCode::OK, result);
Qi Wubeefae42021-01-28 23:16:37 +08001503
1504 ASSERT_GT(key_blob.size(), 0U);
1505 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001506 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001507
1508 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1509
1510 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1511 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1512 << "Key size " << key_size << "missing";
1513 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1514
1515 // Check the usage count limit tag appears in the authorizations.
1516 AuthorizationSet auths;
1517 for (auto& entry : key_characteristics) {
1518 auths.push_back(AuthorizationSet(entry.authorizations));
1519 }
1520 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1521 << "key usage count limit " << 1U << " missing";
1522
1523 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001524 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001525 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001526 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001527
1528 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1529 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001530 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001531 sw_enforced, hw_enforced, SecLevel(),
1532 cert_chain_[0].encodedCertificate));
1533
1534 CheckedDeleteKey(&key_blob);
1535 }
1536}
1537
1538/*
Selene Huang31ab4042020-04-29 04:22:39 -07001539 * NewKeyGenerationTest.NoInvalidRsaSizes
1540 *
1541 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1542 */
1543TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1544 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001545 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07001546 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001547 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001548 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1549 GenerateKey(AuthorizationSetBuilder()
1550 .RsaSigningKey(key_size, 65537)
1551 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001552 .Padding(PaddingMode::NONE)
1553 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001554 &key_blob, &key_characteristics));
1555 }
1556}
1557
1558/*
1559 * NewKeyGenerationTest.RsaNoDefaultSize
1560 *
1561 * Verifies that failing to specify a key size for RSA key generation returns
1562 * UNSUPPORTED_KEY_SIZE.
1563 */
1564TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1565 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1566 GenerateKey(AuthorizationSetBuilder()
1567 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1568 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001569 .SigningKey()
1570 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001571}
1572
1573/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001574 * NewKeyGenerationTest.RsaMissingParams
1575 *
1576 * Verifies that omitting optional tags works.
1577 */
1578TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1579 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001580 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdaled2cc8c22021-04-15 13:29:45 +01001581 ASSERT_EQ(ErrorCode::OK,
1582 GenerateKey(
1583 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1584 CheckedDeleteKey();
1585 }
1586}
1587
1588/*
Selene Huang31ab4042020-04-29 04:22:39 -07001589 * NewKeyGenerationTest.Ecdsa
1590 *
David Drysdale42fe1892021-10-14 14:43:46 +01001591 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001592 * have correct characteristics.
1593 */
1594TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001595 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001596 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07001597 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001598 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001599 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001600 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001601 .Digest(Digest::NONE)
1602 .SetDefaultValidity(),
1603 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001604 ASSERT_GT(key_blob.size(), 0U);
1605 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001606 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001607
Shawn Willden7f424372021-01-10 18:06:50 -07001608 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001609
1610 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001611 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001612
1613 CheckedDeleteKey(&key_blob);
1614 }
1615}
1616
1617/*
David Drysdale42fe1892021-10-14 14:43:46 +01001618 * NewKeyGenerationTest.EcdsaCurve25519
1619 *
1620 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1621 * has correct characteristics.
1622 */
1623TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1624 if (!Curve25519Supported()) {
1625 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1626 }
1627
1628 EcCurve curve = EcCurve::CURVE_25519;
1629 vector<uint8_t> key_blob;
1630 vector<KeyCharacteristics> key_characteristics;
1631 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1632 .EcdsaSigningKey(curve)
1633 .Digest(Digest::NONE)
1634 .SetDefaultValidity(),
1635 &key_blob, &key_characteristics);
1636 ASSERT_EQ(result, ErrorCode::OK);
1637 ASSERT_GT(key_blob.size(), 0U);
1638
1639 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1640 ASSERT_GT(cert_chain_.size(), 0);
1641
1642 CheckBaseParams(key_characteristics);
1643 CheckCharacteristics(key_blob, key_characteristics);
1644
1645 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1646
1647 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1648 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1649
1650 CheckedDeleteKey(&key_blob);
1651}
1652
1653/*
1654 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1655 *
1656 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1657 * SIGN and AGREE_KEY.
1658 */
1659TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1660 if (!Curve25519Supported()) {
1661 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1662 }
1663
1664 EcCurve curve = EcCurve::CURVE_25519;
1665 vector<uint8_t> key_blob;
1666 vector<KeyCharacteristics> key_characteristics;
1667 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1668 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1669 .EcdsaSigningKey(curve)
1670 .Digest(Digest::NONE)
1671 .SetDefaultValidity(),
1672 &key_blob, &key_characteristics);
1673 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1674}
1675
1676/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001677 * NewKeyGenerationTest.EcdsaWithMissingValidity
1678 *
1679 * Verifies that keymint returns an error while generating asymmetric key
1680 * without providing NOT_BEFORE and NOT_AFTER parameters.
1681 */
1682TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
1683 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1684 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1685 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1686
1687 vector<uint8_t> key_blob;
1688 vector<KeyCharacteristics> key_characteristics;
1689 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1690 GenerateKey(AuthorizationSetBuilder()
1691 .EcdsaSigningKey(EcCurve::P_256)
1692 .Digest(Digest::NONE)
1693 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1694 kUndefinedExpirationDateTime),
1695 &key_blob, &key_characteristics));
1696
1697 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1698 GenerateKey(AuthorizationSetBuilder()
1699 .EcdsaSigningKey(EcCurve::P_256)
1700 .Digest(Digest::NONE)
1701 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1702 &key_blob, &key_characteristics));
1703}
1704
1705/*
Selene Huang4f64c222021-04-13 19:54:36 -07001706 * NewKeyGenerationTest.EcdsaAttestation
1707 *
1708 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1709 * an attestation will be generated.
1710 */
1711TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1712 auto challenge = "hello";
1713 auto app_id = "foo";
1714
Selene Huang6e46f142021-04-20 19:20:11 -07001715 auto subject = "cert subj 2";
1716 vector<uint8_t> subject_der(make_name_from_str(subject));
1717
1718 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1719 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1720
David Drysdaledf09e542021-06-08 15:46:11 +01001721 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001722 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07001723 vector<uint8_t> key_blob;
1724 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001725 auto builder = AuthorizationSetBuilder()
1726 .Authorization(TAG_NO_AUTH_REQUIRED)
1727 .EcdsaSigningKey(curve)
1728 .Digest(Digest::NONE)
1729 .AttestationChallenge(challenge)
1730 .AttestationApplicationId(app_id)
1731 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1732 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1733 .SetDefaultValidity();
1734
1735 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001736 // Strongbox may not support factory provisioned attestation key.
1737 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001738 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1739 result = GenerateKeyWithSelfSignedAttestKey(
1740 AuthorizationSetBuilder()
1741 .EcdsaKey(curve)
1742 .AttestKey()
1743 .SetDefaultValidity(), /* attest key params */
1744 builder, &key_blob, &key_characteristics);
1745 }
subrahmanyaman05642492022-02-05 07:10:56 +00001746 }
1747 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001748 ASSERT_GT(key_blob.size(), 0U);
1749 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001750 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001751
1752 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1753
1754 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001755 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001756
1757 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1758 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001759 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001760
1761 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1762 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001763 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001764 sw_enforced, hw_enforced, SecLevel(),
1765 cert_chain_[0].encodedCertificate));
1766
1767 CheckedDeleteKey(&key_blob);
1768 }
1769}
1770
1771/*
David Drysdale42fe1892021-10-14 14:43:46 +01001772 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1773 *
1774 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1775 * an attestation will be generated.
1776 */
1777TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1778 if (!Curve25519Supported()) {
1779 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1780 }
1781
1782 EcCurve curve = EcCurve::CURVE_25519;
1783 auto challenge = "hello";
1784 auto app_id = "foo";
1785
1786 auto subject = "cert subj 2";
1787 vector<uint8_t> subject_der(make_name_from_str(subject));
1788
1789 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1790 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1791
1792 vector<uint8_t> key_blob;
1793 vector<KeyCharacteristics> key_characteristics;
1794 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1795 .Authorization(TAG_NO_AUTH_REQUIRED)
1796 .EcdsaSigningKey(curve)
1797 .Digest(Digest::NONE)
1798 .AttestationChallenge(challenge)
1799 .AttestationApplicationId(app_id)
1800 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1801 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1802 .SetDefaultValidity(),
1803 &key_blob, &key_characteristics);
1804 ASSERT_EQ(ErrorCode::OK, result);
1805 ASSERT_GT(key_blob.size(), 0U);
1806 CheckBaseParams(key_characteristics);
1807 CheckCharacteristics(key_blob, key_characteristics);
1808
1809 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1810
1811 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1812 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1813
1814 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1815 ASSERT_GT(cert_chain_.size(), 0);
1816 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1817
1818 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1819 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1820 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1821 sw_enforced, hw_enforced, SecLevel(),
1822 cert_chain_[0].encodedCertificate));
1823
1824 CheckedDeleteKey(&key_blob);
1825}
1826
1827/*
David Drysdale37af4b32021-05-14 16:46:59 +01001828 * NewKeyGenerationTest.EcdsaAttestationTags
1829 *
1830 * Verifies that creation of an attested ECDSA key includes various tags in the
1831 * attestation extension.
1832 */
1833TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1834 auto challenge = "hello";
1835 auto app_id = "foo";
1836 auto subject = "cert subj 2";
1837 vector<uint8_t> subject_der(make_name_from_str(subject));
1838 uint64_t serial_int = 0x1010;
1839 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1840 const AuthorizationSetBuilder base_builder =
1841 AuthorizationSetBuilder()
1842 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001843 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001844 .Digest(Digest::NONE)
1845 .AttestationChallenge(challenge)
1846 .AttestationApplicationId(app_id)
1847 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1848 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1849 .SetDefaultValidity();
1850
1851 // Various tags that map to fields in the attestation extension ASN.1 schema.
1852 auto extra_tags = AuthorizationSetBuilder()
1853 .Authorization(TAG_ROLLBACK_RESISTANCE)
1854 .Authorization(TAG_EARLY_BOOT_ONLY)
1855 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1856 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1857 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1858 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1859 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1860 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1861 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1862 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1863 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1864 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001865
David Drysdale37af4b32021-05-14 16:46:59 +01001866 for (const KeyParameter& tag : extra_tags) {
1867 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1868 vector<uint8_t> key_blob;
1869 vector<KeyCharacteristics> key_characteristics;
1870 AuthorizationSetBuilder builder = base_builder;
1871 builder.push_back(tag);
1872 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1873 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1874 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1875 continue;
1876 }
Seth Mooreb393b082021-07-12 14:18:28 -07001877 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1878 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001879 continue;
1880 }
subrahmanyaman05642492022-02-05 07:10:56 +00001881 // Strongbox may not support factory provisioned attestation key.
1882 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001883 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1884 result = GenerateKeyWithSelfSignedAttestKey(
1885 AuthorizationSetBuilder()
1886 .EcdsaKey(EcCurve::P_256)
1887 .AttestKey()
1888 .SetDefaultValidity(), /* attest key params */
1889 builder, &key_blob, &key_characteristics);
1890 }
subrahmanyaman05642492022-02-05 07:10:56 +00001891 }
David Drysdale37af4b32021-05-14 16:46:59 +01001892 ASSERT_EQ(result, ErrorCode::OK);
1893 ASSERT_GT(key_blob.size(), 0U);
1894
1895 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1896 ASSERT_GT(cert_chain_.size(), 0);
1897 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1898
1899 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1900 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001901 // Some tags are optional, so don't require them to be in the enforcements.
1902 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001903 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1904 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1905 }
1906
1907 // Verifying the attestation record will check for the specific tag because
1908 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001909 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1910 hw_enforced, SecLevel(),
1911 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01001912
1913 CheckedDeleteKey(&key_blob);
1914 }
1915
David Drysdalec53b7d92021-10-11 12:35:58 +01001916 // Collection of invalid attestation ID tags.
1917 auto invalid_tags =
1918 AuthorizationSetBuilder()
1919 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1920 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1921 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1922 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1923 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
1924 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
1925 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
1926 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01001927 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01001928 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01001929 vector<uint8_t> key_blob;
1930 vector<KeyCharacteristics> key_characteristics;
1931 AuthorizationSetBuilder builder =
1932 AuthorizationSetBuilder()
1933 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001934 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001935 .Digest(Digest::NONE)
1936 .AttestationChallenge(challenge)
1937 .AttestationApplicationId(app_id)
1938 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1939 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1940 .SetDefaultValidity();
1941 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001942
1943 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
1944 // Strongbox may not support factory provisioned attestation key.
1945 if (SecLevel() == SecurityLevel::STRONGBOX) {
1946 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1947 error = GenerateKeyWithSelfSignedAttestKey(
1948 AuthorizationSetBuilder()
1949 .EcdsaKey(EcCurve::P_256)
1950 .AttestKey()
1951 .SetDefaultValidity(), /* attest key params */
1952 builder, &key_blob, &key_characteristics);
1953 }
1954 }
1955 ASSERT_EQ(error, ErrorCode::CANNOT_ATTEST_IDS);
David Drysdale37af4b32021-05-14 16:46:59 +01001956 }
1957}
1958
1959/*
David Drysdalec53b7d92021-10-11 12:35:58 +01001960 * NewKeyGenerationTest.EcdsaAttestationIdTags
1961 *
1962 * Verifies that creation of an attested ECDSA key includes various ID tags in the
1963 * attestation extension.
1964 */
1965TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
David Drysdale555ba002022-05-03 18:48:57 +01001966 if (is_gsi_image()) {
1967 // GSI sets up a standard set of device identifiers that may not match
1968 // the device identifiers held by the device.
1969 GTEST_SKIP() << "Test not applicable under GSI";
1970 }
David Drysdalec53b7d92021-10-11 12:35:58 +01001971 auto challenge = "hello";
1972 auto app_id = "foo";
1973 auto subject = "cert subj 2";
1974 vector<uint8_t> subject_der(make_name_from_str(subject));
1975 uint64_t serial_int = 0x1010;
1976 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1977 const AuthorizationSetBuilder base_builder =
1978 AuthorizationSetBuilder()
1979 .Authorization(TAG_NO_AUTH_REQUIRED)
1980 .EcdsaSigningKey(EcCurve::P_256)
1981 .Digest(Digest::NONE)
1982 .AttestationChallenge(challenge)
1983 .AttestationApplicationId(app_id)
1984 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1985 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1986 .SetDefaultValidity();
1987
1988 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
1989 auto extra_tags = AuthorizationSetBuilder();
1990 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
1991 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
1992 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
1993 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
1994 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
1995 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
1996
1997 for (const KeyParameter& tag : extra_tags) {
1998 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1999 vector<uint8_t> key_blob;
2000 vector<KeyCharacteristics> key_characteristics;
2001 AuthorizationSetBuilder builder = base_builder;
2002 builder.push_back(tag);
2003 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002004 // Strongbox may not support factory provisioned attestation key.
2005 if (SecLevel() == SecurityLevel::STRONGBOX) {
2006 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2007 }
Prashant Patil88ad1892022-03-15 16:31:02 +00002008 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2009 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01002010 continue;
2011 }
2012 ASSERT_EQ(result, ErrorCode::OK);
2013 ASSERT_GT(key_blob.size(), 0U);
2014
2015 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2016 ASSERT_GT(cert_chain_.size(), 0);
2017 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2018
2019 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2020 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2021
2022 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2023 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2024 // attestation extension should contain them, so make sure the extra tag is added.
2025 hw_enforced.push_back(tag);
2026
2027 // Verifying the attestation record will check for the specific tag because
2028 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002029 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2030 hw_enforced, SecLevel(),
2031 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002032
2033 CheckedDeleteKey(&key_blob);
2034 }
2035}
2036
2037/*
David Drysdale565ccc72021-10-11 12:49:50 +01002038 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2039 *
2040 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2041 */
2042TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2043 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002044 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002045 auto challenge = "hello";
2046 auto subject = "cert subj 2";
2047 vector<uint8_t> subject_der(make_name_from_str(subject));
2048 uint64_t serial_int = 0x1010;
2049 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002050 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002051 AuthorizationSetBuilder()
2052 .Authorization(TAG_NO_AUTH_REQUIRED)
2053 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2054 .EcdsaSigningKey(EcCurve::P_256)
2055 .Digest(Digest::NONE)
2056 .AttestationChallenge(challenge)
2057 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2058 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2059 .AttestationApplicationId(app_id)
2060 .Authorization(TAG_CREATION_DATETIME, datetime)
2061 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002062 if (reset) {
2063 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2064 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002065 auto result = GenerateKey(builder);
2066 if (SecLevel() == SecurityLevel::STRONGBOX) {
2067 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2068 result = GenerateKeyWithSelfSignedAttestKey(
2069 AuthorizationSetBuilder()
2070 .EcdsaKey(EcCurve::P_256)
2071 .AttestKey()
2072 .SetDefaultValidity(), /* attest key params */
2073 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2074 }
2075 }
2076 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002077 ASSERT_GT(key_blob_.size(), 0U);
2078
2079 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2080 ASSERT_GT(cert_chain_.size(), 0);
2081 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2082
2083 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2084 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2085
2086 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002087 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2088 hw_enforced, SecLevel(),
2089 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002090 EXPECT_GT(unique_id->size(), 0);
2091 CheckedDeleteKey();
2092 };
2093
2094 // Generate unique ID
2095 auto app_id = "foo";
2096 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2097 vector<uint8_t> unique_id;
2098 get_unique_id(app_id, cert_date, &unique_id);
2099
2100 // Generating a new key with the same parameters should give the same unique ID.
2101 vector<uint8_t> unique_id2;
2102 get_unique_id(app_id, cert_date, &unique_id2);
2103 EXPECT_EQ(unique_id, unique_id2);
2104
2105 // Generating a new key with a slightly different date should give the same unique ID.
2106 uint64_t rounded_date = cert_date / 2592000000LLU;
2107 uint64_t min_date = rounded_date * 2592000000LLU;
2108 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2109
2110 vector<uint8_t> unique_id3;
2111 get_unique_id(app_id, min_date, &unique_id3);
2112 EXPECT_EQ(unique_id, unique_id3);
2113
2114 vector<uint8_t> unique_id4;
2115 get_unique_id(app_id, max_date, &unique_id4);
2116 EXPECT_EQ(unique_id, unique_id4);
2117
2118 // A different attestation application ID should yield a different unique ID.
2119 auto app_id2 = "different_foo";
2120 vector<uint8_t> unique_id5;
2121 get_unique_id(app_id2, cert_date, &unique_id5);
2122 EXPECT_NE(unique_id, unique_id5);
2123
2124 // A radically different date should yield a different unique ID.
2125 vector<uint8_t> unique_id6;
2126 get_unique_id(app_id, 1611621648000, &unique_id6);
2127 EXPECT_NE(unique_id, unique_id6);
2128
2129 vector<uint8_t> unique_id7;
2130 get_unique_id(app_id, max_date + 1, &unique_id7);
2131 EXPECT_NE(unique_id, unique_id7);
2132
2133 vector<uint8_t> unique_id8;
2134 get_unique_id(app_id, min_date - 1, &unique_id8);
2135 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002136
2137 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2138 vector<uint8_t> unique_id9;
2139 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2140 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002141}
2142
2143/*
David Drysdale37af4b32021-05-14 16:46:59 +01002144 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2145 *
2146 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2147 */
2148TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2149 auto challenge = "hello";
2150 auto attest_app_id = "foo";
2151 auto subject = "cert subj 2";
2152 vector<uint8_t> subject_der(make_name_from_str(subject));
2153 uint64_t serial_int = 0x1010;
2154 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2155
2156 // Earlier versions of the attestation extension schema included a slot:
2157 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2158 // This should never have been included, and should never be filled in.
2159 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2160 // to confirm that this field never makes it into the attestation extension.
2161 vector<uint8_t> key_blob;
2162 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002163 auto builder = AuthorizationSetBuilder()
2164 .Authorization(TAG_NO_AUTH_REQUIRED)
2165 .EcdsaSigningKey(EcCurve::P_256)
2166 .Digest(Digest::NONE)
2167 .AttestationChallenge(challenge)
2168 .AttestationApplicationId(attest_app_id)
2169 .Authorization(TAG_APPLICATION_ID, "client_id")
2170 .Authorization(TAG_APPLICATION_DATA, "appdata")
2171 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2172 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2173 .SetDefaultValidity();
2174
2175 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002176 // Strongbox may not support factory provisioned attestation key.
2177 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002178 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2179 result = GenerateKeyWithSelfSignedAttestKey(
2180 AuthorizationSetBuilder()
2181 .EcdsaKey(EcCurve::P_256)
2182 .AttestKey()
2183 .SetDefaultValidity(), /* attest key params */
2184 builder, &key_blob, &key_characteristics);
2185 }
subrahmanyaman05642492022-02-05 07:10:56 +00002186 }
David Drysdale37af4b32021-05-14 16:46:59 +01002187 ASSERT_EQ(result, ErrorCode::OK);
2188 ASSERT_GT(key_blob.size(), 0U);
2189
2190 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2191 ASSERT_GT(cert_chain_.size(), 0);
2192 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2193
2194 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2195 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002196 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2197 hw_enforced, SecLevel(),
2198 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002199
2200 // Check that the app id is not in the cert.
2201 string app_id = "clientid";
2202 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2203 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2204 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2205 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2206 cert_chain_[0].encodedCertificate.end());
2207
2208 CheckedDeleteKey(&key_blob);
2209}
2210
2211/*
Selene Huang4f64c222021-04-13 19:54:36 -07002212 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2213 *
2214 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2215 * the key will generate a self signed attestation.
2216 */
2217TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002218 auto subject = "cert subj 2";
2219 vector<uint8_t> subject_der(make_name_from_str(subject));
2220
2221 uint64_t serial_int = 0x123456FFF1234;
2222 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2223
David Drysdaledf09e542021-06-08 15:46:11 +01002224 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002225 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002226 vector<uint8_t> key_blob;
2227 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002228 ASSERT_EQ(ErrorCode::OK,
2229 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002230 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002231 .Digest(Digest::NONE)
2232 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2233 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2234 .SetDefaultValidity(),
2235 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002236 ASSERT_GT(key_blob.size(), 0U);
2237 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002238 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002239
2240 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2241
2242 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002243 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002244
2245 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2246 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002247 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002248
2249 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2250 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2251
2252 CheckedDeleteKey(&key_blob);
2253 }
2254}
2255
2256/*
2257 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2258 *
2259 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2260 * app id must also be provided or else it will fail.
2261 */
2262TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2263 auto challenge = "hello";
2264 vector<uint8_t> key_blob;
2265 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002266 auto builder = AuthorizationSetBuilder()
2267 .EcdsaSigningKey(EcCurve::P_256)
2268 .Digest(Digest::NONE)
2269 .AttestationChallenge(challenge)
2270 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002271
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002272 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002273 // Strongbox may not support factory provisioned attestation key.
2274 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002275 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2276 result = GenerateKeyWithSelfSignedAttestKey(
2277 AuthorizationSetBuilder()
2278 .EcdsaKey(EcCurve::P_256)
2279 .AttestKey()
2280 .SetDefaultValidity(), /* attest key params */
2281 builder, &key_blob, &key_characteristics);
2282 }
subrahmanyaman05642492022-02-05 07:10:56 +00002283 }
2284 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002285}
2286
2287/*
2288 * NewKeyGenerationTest.EcdsaIgnoreAppId
2289 *
2290 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2291 * any appid will be ignored, and keymint will generate a self sign certificate.
2292 */
2293TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2294 auto app_id = "foo";
2295
David Drysdaledf09e542021-06-08 15:46:11 +01002296 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002297 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002298 vector<uint8_t> key_blob;
2299 vector<KeyCharacteristics> key_characteristics;
2300 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002301 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002302 .Digest(Digest::NONE)
2303 .AttestationApplicationId(app_id)
2304 .SetDefaultValidity(),
2305 &key_blob, &key_characteristics));
2306
2307 ASSERT_GT(key_blob.size(), 0U);
2308 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002309 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002310
2311 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2312
2313 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002314 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002315
2316 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2317 ASSERT_EQ(cert_chain_.size(), 1);
2318
2319 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2320 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2321
2322 CheckedDeleteKey(&key_blob);
2323 }
2324}
2325
2326/*
2327 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2328 *
2329 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2330 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2331 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2332 * to specify how many following bytes will be used to encode the length.
2333 */
2334TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2335 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002336 std::vector<uint32_t> app_id_lengths{143, 258};
2337
2338 for (uint32_t length : app_id_lengths) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002339 SCOPED_TRACE(testing::Message() << "app_id_len=" << length);
Selene Huang4f64c222021-04-13 19:54:36 -07002340 const string app_id(length, 'a');
2341 vector<uint8_t> key_blob;
2342 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002343 auto builder = AuthorizationSetBuilder()
2344 .Authorization(TAG_NO_AUTH_REQUIRED)
2345 .EcdsaSigningKey(EcCurve::P_256)
2346 .Digest(Digest::NONE)
2347 .AttestationChallenge(challenge)
2348 .AttestationApplicationId(app_id)
2349 .SetDefaultValidity();
2350
2351 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002352 // Strongbox may not support factory provisioned attestation key.
2353 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002354 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2355 result = GenerateKeyWithSelfSignedAttestKey(
2356 AuthorizationSetBuilder()
2357 .EcdsaKey(EcCurve::P_256)
2358 .AttestKey()
2359 .SetDefaultValidity(), /* attest key params */
2360 builder, &key_blob, &key_characteristics);
2361 }
subrahmanyaman05642492022-02-05 07:10:56 +00002362 }
2363 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002364 ASSERT_GT(key_blob.size(), 0U);
2365 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002366 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002367
2368 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2369
2370 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002371 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002372
2373 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2374 ASSERT_GT(cert_chain_.size(), 0);
2375
2376 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2377 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002378 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002379 sw_enforced, hw_enforced, SecLevel(),
2380 cert_chain_[0].encodedCertificate));
2381
2382 CheckedDeleteKey(&key_blob);
2383 }
2384}
2385
2386/*
Qi Wud22ec842020-11-26 13:27:53 +08002387 * NewKeyGenerationTest.LimitedUsageEcdsa
2388 *
2389 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2390 * resulting keys have correct characteristics.
2391 */
2392TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002393 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002394 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Qi Wud22ec842020-11-26 13:27:53 +08002395 vector<uint8_t> key_blob;
2396 vector<KeyCharacteristics> key_characteristics;
2397 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002398 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002399 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002400 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2401 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002402 &key_blob, &key_characteristics));
2403
2404 ASSERT_GT(key_blob.size(), 0U);
2405 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002406 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002407
2408 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2409
2410 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002411 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002412
2413 // Check the usage count limit tag appears in the authorizations.
2414 AuthorizationSet auths;
2415 for (auto& entry : key_characteristics) {
2416 auths.push_back(AuthorizationSet(entry.authorizations));
2417 }
2418 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2419 << "key usage count limit " << 1U << " missing";
2420
2421 CheckedDeleteKey(&key_blob);
2422 }
2423}
2424
2425/*
Selene Huang31ab4042020-04-29 04:22:39 -07002426 * NewKeyGenerationTest.EcdsaDefaultSize
2427 *
David Drysdaledf09e542021-06-08 15:46:11 +01002428 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002429 * UNSUPPORTED_KEY_SIZE.
2430 */
2431TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2432 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2433 GenerateKey(AuthorizationSetBuilder()
2434 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2435 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002436 .Digest(Digest::NONE)
2437 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002438}
2439
2440/*
David Drysdale42fe1892021-10-14 14:43:46 +01002441 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002442 *
David Drysdale42fe1892021-10-14 14:43:46 +01002443 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002444 * UNSUPPORTED_KEY_SIZE.
2445 */
David Drysdale42fe1892021-10-14 14:43:46 +01002446TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002447 for (auto curve : InvalidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002448 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07002449 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002450 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002451 auto result = GenerateKey(AuthorizationSetBuilder()
2452 .EcdsaSigningKey(curve)
2453 .Digest(Digest::NONE)
2454 .SetDefaultValidity(),
2455 &key_blob, &key_characteristics);
2456 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2457 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002458 }
2459
David Drysdaledf09e542021-06-08 15:46:11 +01002460 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2461 GenerateKey(AuthorizationSetBuilder()
2462 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2463 .Authorization(TAG_KEY_SIZE, 190)
2464 .SigningKey()
2465 .Digest(Digest::NONE)
2466 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002467}
2468
2469/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002470 * NewKeyGenerationTest.EcdsaMissingCurve
2471 *
2472 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
2473 */
2474TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2475 if (AidlVersion() < 2) {
2476 /*
2477 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2478 * However, this was not checked at the time so we can only be strict about checking this
2479 * for implementations of KeyMint version 2 and above.
2480 */
2481 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
2482 }
2483 /* If EC_CURVE not provided, generateKey
2484 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2485 */
2486 auto result = GenerateKey(
2487 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2488 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2489 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2490}
2491
2492/*
Selene Huang31ab4042020-04-29 04:22:39 -07002493 * NewKeyGenerationTest.EcdsaMismatchKeySize
2494 *
2495 * Verifies that specifying mismatched key size and curve for EC key generation returns
2496 * INVALID_ARGUMENT.
2497 */
2498TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002499 if (SecLevel() == SecurityLevel::STRONGBOX) {
2500 GTEST_SKIP() << "Test not applicable to StrongBox device";
2501 }
Selene Huang31ab4042020-04-29 04:22:39 -07002502
David Drysdaledf09e542021-06-08 15:46:11 +01002503 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002504 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002505 .Authorization(TAG_KEY_SIZE, 224)
2506 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002507 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002508 .Digest(Digest::NONE)
2509 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002510 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002511}
2512
2513/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002514 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002515 *
2516 * Verifies that keymint does not support any curve designated as unsupported.
2517 */
2518TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2519 Digest digest;
2520 if (SecLevel() == SecurityLevel::STRONGBOX) {
2521 digest = Digest::SHA_2_256;
2522 } else {
2523 digest = Digest::SHA_2_512;
2524 }
2525 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002526 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Janis Danisevskis164bb872021-02-09 11:30:25 -08002527 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2528 .EcdsaSigningKey(curve)
2529 .Digest(digest)
2530 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002531 << "Failed to generate key on curve: " << curve;
2532 CheckedDeleteKey();
2533 }
2534}
2535
2536/*
2537 * NewKeyGenerationTest.Hmac
2538 *
2539 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2540 * characteristics.
2541 */
2542TEST_P(NewKeyGenerationTest, Hmac) {
2543 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002544 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07002545 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002546 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002547 constexpr size_t key_size = 128;
2548 ASSERT_EQ(ErrorCode::OK,
2549 GenerateKey(
2550 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2551 TAG_MIN_MAC_LENGTH, 128),
2552 &key_blob, &key_characteristics));
2553
2554 ASSERT_GT(key_blob.size(), 0U);
2555 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002556 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002557
Shawn Willden7f424372021-01-10 18:06:50 -07002558 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2559 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2560 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2561 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002562
2563 CheckedDeleteKey(&key_blob);
2564 }
2565}
2566
2567/*
Selene Huang4f64c222021-04-13 19:54:36 -07002568 * NewKeyGenerationTest.HmacNoAttestation
2569 *
2570 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2571 * and app id are provided.
2572 */
2573TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2574 auto challenge = "hello";
2575 auto app_id = "foo";
2576
2577 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002578 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang4f64c222021-04-13 19:54:36 -07002579 vector<uint8_t> key_blob;
2580 vector<KeyCharacteristics> key_characteristics;
2581 constexpr size_t key_size = 128;
2582 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2583 .HmacKey(key_size)
2584 .Digest(digest)
2585 .AttestationChallenge(challenge)
2586 .AttestationApplicationId(app_id)
2587 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2588 &key_blob, &key_characteristics));
2589
2590 ASSERT_GT(key_blob.size(), 0U);
2591 ASSERT_EQ(cert_chain_.size(), 0);
2592 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002593 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002594
2595 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2596 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2597 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2598 << "Key size " << key_size << "missing";
2599
2600 CheckedDeleteKey(&key_blob);
2601 }
2602}
2603
2604/*
Qi Wud22ec842020-11-26 13:27:53 +08002605 * NewKeyGenerationTest.LimitedUsageHmac
2606 *
2607 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2608 * resulting keys have correct characteristics.
2609 */
2610TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2611 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002612 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Qi Wud22ec842020-11-26 13:27:53 +08002613 vector<uint8_t> key_blob;
2614 vector<KeyCharacteristics> key_characteristics;
2615 constexpr size_t key_size = 128;
2616 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2617 .HmacKey(key_size)
2618 .Digest(digest)
2619 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2620 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2621 &key_blob, &key_characteristics));
2622
2623 ASSERT_GT(key_blob.size(), 0U);
2624 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002625 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002626
2627 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2628 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2629 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2630 << "Key size " << key_size << "missing";
2631
2632 // Check the usage count limit tag appears in the authorizations.
2633 AuthorizationSet auths;
2634 for (auto& entry : key_characteristics) {
2635 auths.push_back(AuthorizationSet(entry.authorizations));
2636 }
2637 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2638 << "key usage count limit " << 1U << " missing";
2639
2640 CheckedDeleteKey(&key_blob);
2641 }
2642}
2643
2644/*
Selene Huang31ab4042020-04-29 04:22:39 -07002645 * NewKeyGenerationTest.HmacCheckKeySizes
2646 *
2647 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2648 */
2649TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2650 for (size_t key_size = 0; key_size <= 512; ++key_size) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002651 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002652 if (key_size < 64 || key_size % 8 != 0) {
2653 // To keep this test from being very slow, we only test a random fraction of
2654 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2655 // them, we expect to run ~40 of them in each run.
2656 if (key_size % 8 == 0 || random() % 10 == 0) {
2657 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2658 GenerateKey(AuthorizationSetBuilder()
2659 .HmacKey(key_size)
2660 .Digest(Digest::SHA_2_256)
2661 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2662 << "HMAC key size " << key_size << " invalid";
2663 }
2664 } else {
2665 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2666 .HmacKey(key_size)
2667 .Digest(Digest::SHA_2_256)
2668 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2669 << "Failed to generate HMAC key of size " << key_size;
2670 CheckedDeleteKey();
2671 }
2672 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002673 if (SecLevel() == SecurityLevel::STRONGBOX) {
2674 // STRONGBOX devices must not support keys larger than 512 bits.
2675 size_t key_size = 520;
2676 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2677 GenerateKey(AuthorizationSetBuilder()
2678 .HmacKey(key_size)
2679 .Digest(Digest::SHA_2_256)
2680 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2681 << "HMAC key size " << key_size << " unexpectedly valid";
2682 }
Selene Huang31ab4042020-04-29 04:22:39 -07002683}
2684
2685/*
2686 * NewKeyGenerationTest.HmacCheckMinMacLengths
2687 *
2688 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2689 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2690 * specific MAC length that failed, so reproducing a failed run will be easy.
2691 */
2692TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2693 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002694 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
Selene Huang31ab4042020-04-29 04:22:39 -07002695 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2696 // To keep this test from being very long, we only test a random fraction of
2697 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2698 // we expect to run ~17 of them in each run.
2699 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2700 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2701 GenerateKey(AuthorizationSetBuilder()
2702 .HmacKey(128)
2703 .Digest(Digest::SHA_2_256)
2704 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2705 << "HMAC min mac length " << min_mac_length << " invalid.";
2706 }
2707 } else {
2708 EXPECT_EQ(ErrorCode::OK,
2709 GenerateKey(AuthorizationSetBuilder()
2710 .HmacKey(128)
2711 .Digest(Digest::SHA_2_256)
2712 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2713 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2714 CheckedDeleteKey();
2715 }
2716 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002717
2718 // Minimum MAC length must be no more than 512 bits.
2719 size_t min_mac_length = 520;
2720 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2721 GenerateKey(AuthorizationSetBuilder()
2722 .HmacKey(128)
2723 .Digest(Digest::SHA_2_256)
2724 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2725 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002726}
2727
2728/*
2729 * NewKeyGenerationTest.HmacMultipleDigests
2730 *
2731 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2732 */
2733TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002734 if (SecLevel() == SecurityLevel::STRONGBOX) {
2735 GTEST_SKIP() << "Test not applicable to StrongBox device";
2736 }
Selene Huang31ab4042020-04-29 04:22:39 -07002737
2738 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2739 GenerateKey(AuthorizationSetBuilder()
2740 .HmacKey(128)
2741 .Digest(Digest::SHA1)
2742 .Digest(Digest::SHA_2_256)
2743 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2744}
2745
2746/*
2747 * NewKeyGenerationTest.HmacDigestNone
2748 *
2749 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2750 */
2751TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2752 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2753 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2754 128)));
2755
2756 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2757 GenerateKey(AuthorizationSetBuilder()
2758 .HmacKey(128)
2759 .Digest(Digest::NONE)
2760 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2761}
2762
Selene Huang4f64c222021-04-13 19:54:36 -07002763/*
2764 * NewKeyGenerationTest.AesNoAttestation
2765 *
2766 * Verifies that attestation parameters to AES keys are ignored and generateKey
2767 * will succeed.
2768 */
2769TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2770 auto challenge = "hello";
2771 auto app_id = "foo";
2772
2773 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2774 .Authorization(TAG_NO_AUTH_REQUIRED)
2775 .AesEncryptionKey(128)
2776 .EcbMode()
2777 .Padding(PaddingMode::PKCS7)
2778 .AttestationChallenge(challenge)
2779 .AttestationApplicationId(app_id)));
2780
2781 ASSERT_EQ(cert_chain_.size(), 0);
2782}
2783
2784/*
2785 * NewKeyGenerationTest.TripleDesNoAttestation
2786 *
2787 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2788 * will be successful. No attestation should be generated.
2789 */
2790TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2791 auto challenge = "hello";
2792 auto app_id = "foo";
2793
2794 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2795 .TripleDesEncryptionKey(168)
2796 .BlockMode(BlockMode::ECB)
2797 .Authorization(TAG_NO_AUTH_REQUIRED)
2798 .Padding(PaddingMode::NONE)
2799 .AttestationChallenge(challenge)
2800 .AttestationApplicationId(app_id)));
2801 ASSERT_EQ(cert_chain_.size(), 0);
2802}
2803
Selene Huang31ab4042020-04-29 04:22:39 -07002804INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2805
2806typedef KeyMintAidlTestBase SigningOperationsTest;
2807
2808/*
2809 * SigningOperationsTest.RsaSuccess
2810 *
2811 * Verifies that raw RSA signature operations succeed.
2812 */
2813TEST_P(SigningOperationsTest, RsaSuccess) {
2814 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2815 .RsaSigningKey(2048, 65537)
2816 .Digest(Digest::NONE)
2817 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002818 .Authorization(TAG_NO_AUTH_REQUIRED)
2819 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002820 string message = "12345678901234567890123456789012";
2821 string signature = SignMessage(
2822 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002823 LocalVerifyMessage(message, signature,
2824 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2825}
2826
2827/*
2828 * SigningOperationsTest.RsaAllPaddingsAndDigests
2829 *
2830 * Verifies RSA signature/verification for all padding modes and digests.
2831 */
2832TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2833 auto authorizations = AuthorizationSetBuilder()
2834 .Authorization(TAG_NO_AUTH_REQUIRED)
2835 .RsaSigningKey(2048, 65537)
2836 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2837 .Padding(PaddingMode::NONE)
2838 .Padding(PaddingMode::RSA_PSS)
2839 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2840 .SetDefaultValidity();
2841
2842 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2843
2844 string message(128, 'a');
2845 string corrupt_message(message);
2846 ++corrupt_message[corrupt_message.size() / 2];
2847
2848 for (auto padding :
2849 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2850 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002851 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002852 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2853 // Digesting only makes sense with padding.
2854 continue;
2855 }
2856
2857 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2858 // PSS requires digesting.
2859 continue;
2860 }
2861
2862 string signature =
2863 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2864 LocalVerifyMessage(message, signature,
2865 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2866 }
2867 }
Selene Huang31ab4042020-04-29 04:22:39 -07002868}
2869
2870/*
2871 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2872 *
Shawn Willden7f424372021-01-10 18:06:50 -07002873 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002874 */
2875TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2876 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2877 .Authorization(TAG_NO_AUTH_REQUIRED)
2878 .RsaSigningKey(2048, 65537)
2879 .Digest(Digest::NONE)
2880 .Padding(PaddingMode::NONE)
2881 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002882 .Authorization(TAG_APPLICATION_DATA, "appdata")
2883 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002884
2885 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2886
Selene Huang31ab4042020-04-29 04:22:39 -07002887 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2888 Begin(KeyPurpose::SIGN,
2889 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2890 AbortIfNeeded();
2891 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2892 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2893 .Digest(Digest::NONE)
2894 .Padding(PaddingMode::NONE)
2895 .Authorization(TAG_APPLICATION_ID, "clientid")));
2896 AbortIfNeeded();
2897 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2898 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2899 .Digest(Digest::NONE)
2900 .Padding(PaddingMode::NONE)
2901 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2902 AbortIfNeeded();
2903 EXPECT_EQ(ErrorCode::OK,
2904 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2905 .Digest(Digest::NONE)
2906 .Padding(PaddingMode::NONE)
2907 .Authorization(TAG_APPLICATION_DATA, "appdata")
2908 .Authorization(TAG_APPLICATION_ID, "clientid")));
2909 AbortIfNeeded();
2910}
2911
2912/*
2913 * SigningOperationsTest.RsaPssSha256Success
2914 *
2915 * Verifies that RSA-PSS signature operations succeed.
2916 */
2917TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2918 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2919 .RsaSigningKey(2048, 65537)
2920 .Digest(Digest::SHA_2_256)
2921 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002922 .Authorization(TAG_NO_AUTH_REQUIRED)
2923 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002924 // Use large message, which won't work without digesting.
2925 string message(1024, 'a');
2926 string signature = SignMessage(
2927 message,
2928 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2929}
2930
2931/*
2932 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2933 *
2934 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2935 * supports only unpadded operations.
2936 */
2937TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2938 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2939 .RsaSigningKey(2048, 65537)
2940 .Digest(Digest::NONE)
2941 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002942 .Padding(PaddingMode::NONE)
2943 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002944 string message = "12345678901234567890123456789012";
2945 string signature;
2946
2947 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2948 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2949 .Digest(Digest::NONE)
2950 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2951}
2952
2953/*
2954 * SigningOperationsTest.NoUserConfirmation
2955 *
2956 * Verifies that keymint rejects signing operations for keys with
2957 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2958 * presented.
2959 */
2960TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002961 if (SecLevel() == SecurityLevel::STRONGBOX) {
2962 GTEST_SKIP() << "Test not applicable to StrongBox device";
2963 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002964 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2965 .RsaSigningKey(1024, 65537)
2966 .Digest(Digest::NONE)
2967 .Padding(PaddingMode::NONE)
2968 .Authorization(TAG_NO_AUTH_REQUIRED)
2969 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2970 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002971
2972 const string message = "12345678901234567890123456789012";
2973 EXPECT_EQ(ErrorCode::OK,
2974 Begin(KeyPurpose::SIGN,
2975 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2976 string signature;
2977 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2978}
2979
2980/*
2981 * SigningOperationsTest.RsaPkcs1Sha256Success
2982 *
2983 * Verifies that digested RSA-PKCS1 signature operations succeed.
2984 */
2985TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2986 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2987 .RsaSigningKey(2048, 65537)
2988 .Digest(Digest::SHA_2_256)
2989 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002990 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2991 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002992 string message(1024, 'a');
2993 string signature = SignMessage(message, AuthorizationSetBuilder()
2994 .Digest(Digest::SHA_2_256)
2995 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2996}
2997
2998/*
2999 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3000 *
3001 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3002 */
3003TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3004 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3005 .RsaSigningKey(2048, 65537)
3006 .Digest(Digest::NONE)
3007 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003008 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3009 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003010 string message(53, 'a');
3011 string signature = SignMessage(message, AuthorizationSetBuilder()
3012 .Digest(Digest::NONE)
3013 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3014}
3015
3016/*
3017 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3018 *
3019 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3020 * given a too-long message.
3021 */
3022TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3023 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3024 .RsaSigningKey(2048, 65537)
3025 .Digest(Digest::NONE)
3026 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003027 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3028 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003029 string message(257, 'a');
3030
3031 EXPECT_EQ(ErrorCode::OK,
3032 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3033 .Digest(Digest::NONE)
3034 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3035 string signature;
3036 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3037}
3038
3039/*
3040 * SigningOperationsTest.RsaPssSha512TooSmallKey
3041 *
3042 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3043 * used with a key that is too small for the message.
3044 *
3045 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3046 * keymint specification requires that salt_size == digest_size, so the message will be
3047 * digest_size * 2 +
3048 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3049 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3050 * for a 1024-bit key.
3051 */
3052TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003053 if (SecLevel() == SecurityLevel::STRONGBOX) {
3054 GTEST_SKIP() << "Test not applicable to StrongBox device";
3055 }
Selene Huang31ab4042020-04-29 04:22:39 -07003056 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3057 .RsaSigningKey(1024, 65537)
3058 .Digest(Digest::SHA_2_512)
3059 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003060 .Padding(PaddingMode::RSA_PSS)
3061 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003062 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3063 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3064 .Digest(Digest::SHA_2_512)
3065 .Padding(PaddingMode::RSA_PSS)));
3066}
3067
3068/*
3069 * SigningOperationsTest.RsaNoPaddingTooLong
3070 *
3071 * Verifies that raw RSA signature operations fail with the correct error code when
3072 * given a too-long message.
3073 */
3074TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3075 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3076 .RsaSigningKey(2048, 65537)
3077 .Digest(Digest::NONE)
3078 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003079 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3080 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003081 // One byte too long
3082 string message(2048 / 8 + 1, 'a');
3083 ASSERT_EQ(ErrorCode::OK,
3084 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3085 .Digest(Digest::NONE)
3086 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3087 string result;
3088 ErrorCode finish_error_code = Finish(message, &result);
3089 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3090 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3091
3092 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3093 message = string(128 * 1024, 'a');
3094 ASSERT_EQ(ErrorCode::OK,
3095 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3096 .Digest(Digest::NONE)
3097 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3098 finish_error_code = Finish(message, &result);
3099 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3100 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3101}
3102
3103/*
3104 * SigningOperationsTest.RsaAbort
3105 *
3106 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3107 * test, but the behavior should be algorithm and purpose-independent.
3108 */
3109TEST_P(SigningOperationsTest, RsaAbort) {
3110 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3111 .RsaSigningKey(2048, 65537)
3112 .Digest(Digest::NONE)
3113 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003114 .Padding(PaddingMode::NONE)
3115 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003116
3117 ASSERT_EQ(ErrorCode::OK,
3118 Begin(KeyPurpose::SIGN,
3119 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3120 EXPECT_EQ(ErrorCode::OK, Abort());
3121
3122 // Another abort should fail
3123 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3124
3125 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003126 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003127}
3128
3129/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003130 * SigningOperationsTest.RsaNonUniqueParams
3131 *
3132 * Verifies that an operation with multiple padding modes is rejected.
3133 */
3134TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3135 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3136 .RsaSigningKey(2048, 65537)
3137 .Digest(Digest::NONE)
3138 .Digest(Digest::SHA1)
3139 .Authorization(TAG_NO_AUTH_REQUIRED)
3140 .Padding(PaddingMode::NONE)
3141 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3142 .SetDefaultValidity()));
3143
3144 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3145 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3146 .Digest(Digest::NONE)
3147 .Padding(PaddingMode::NONE)
3148 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3149
Tommy Chiuc93c4392021-05-11 18:36:50 +08003150 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3151 .Digest(Digest::NONE)
3152 .Digest(Digest::SHA1)
3153 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3154 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003155
3156 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3157 Begin(KeyPurpose::SIGN,
3158 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3159}
3160
3161/*
Selene Huang31ab4042020-04-29 04:22:39 -07003162 * SigningOperationsTest.RsaUnsupportedPadding
3163 *
3164 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3165 * with a padding mode inappropriate for RSA.
3166 */
3167TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3168 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3169 .RsaSigningKey(2048, 65537)
3170 .Authorization(TAG_NO_AUTH_REQUIRED)
3171 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003172 .Padding(PaddingMode::PKCS7)
3173 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003174 ASSERT_EQ(
3175 ErrorCode::UNSUPPORTED_PADDING_MODE,
3176 Begin(KeyPurpose::SIGN,
3177 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003178 CheckedDeleteKey();
3179
3180 ASSERT_EQ(ErrorCode::OK,
3181 GenerateKey(
3182 AuthorizationSetBuilder()
3183 .RsaSigningKey(2048, 65537)
3184 .Authorization(TAG_NO_AUTH_REQUIRED)
3185 .Digest(Digest::SHA_2_256 /* supported digest */)
3186 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3187 .SetDefaultValidity()));
3188 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3189 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3190 .Digest(Digest::SHA_2_256)
3191 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003192}
3193
3194/*
3195 * SigningOperationsTest.RsaPssNoDigest
3196 *
3197 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3198 */
3199TEST_P(SigningOperationsTest, RsaNoDigest) {
3200 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3201 .RsaSigningKey(2048, 65537)
3202 .Authorization(TAG_NO_AUTH_REQUIRED)
3203 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003204 .Padding(PaddingMode::RSA_PSS)
3205 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003206 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3207 Begin(KeyPurpose::SIGN,
3208 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3209
3210 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3211 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3212}
3213
3214/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003215 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003216 *
3217 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3218 * supported in some cases (as validated in other tests), but a mode must be specified.
3219 */
3220TEST_P(SigningOperationsTest, RsaNoPadding) {
3221 // Padding must be specified
3222 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3223 .RsaKey(2048, 65537)
3224 .Authorization(TAG_NO_AUTH_REQUIRED)
3225 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003226 .Digest(Digest::NONE)
3227 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003228 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3229 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3230}
3231
3232/*
3233 * SigningOperationsTest.RsaShortMessage
3234 *
3235 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3236 */
3237TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3238 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3239 .Authorization(TAG_NO_AUTH_REQUIRED)
3240 .RsaSigningKey(2048, 65537)
3241 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003242 .Padding(PaddingMode::NONE)
3243 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003244
3245 // Barely shorter
3246 string message(2048 / 8 - 1, 'a');
3247 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3248
3249 // Much shorter
3250 message = "a";
3251 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3252}
3253
3254/*
3255 * SigningOperationsTest.RsaSignWithEncryptionKey
3256 *
3257 * Verifies that RSA encryption keys cannot be used to sign.
3258 */
3259TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3260 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3261 .Authorization(TAG_NO_AUTH_REQUIRED)
3262 .RsaEncryptionKey(2048, 65537)
3263 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003264 .Padding(PaddingMode::NONE)
3265 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003266 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3267 Begin(KeyPurpose::SIGN,
3268 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3269}
3270
3271/*
3272 * SigningOperationsTest.RsaSignTooLargeMessage
3273 *
3274 * Verifies that attempting a raw signature of a message which is the same length as the key,
3275 * but numerically larger than the public modulus, fails with the correct error.
3276 */
3277TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3278 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3279 .Authorization(TAG_NO_AUTH_REQUIRED)
3280 .RsaSigningKey(2048, 65537)
3281 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003282 .Padding(PaddingMode::NONE)
3283 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003284
3285 // Largest possible message will always be larger than the public modulus.
3286 string message(2048 / 8, static_cast<char>(0xff));
3287 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3288 .Authorization(TAG_NO_AUTH_REQUIRED)
3289 .Digest(Digest::NONE)
3290 .Padding(PaddingMode::NONE)));
3291 string signature;
3292 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3293}
3294
3295/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003296 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3297 *
David Drysdale42fe1892021-10-14 14:43:46 +01003298 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003299 */
3300TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003301
3302 string message = "1234567890";
3303 string corrupt_message = "2234567890";
3304 for (auto curve : ValidCurves()) {
3305 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003306 // Ed25519 only allows Digest::NONE.
3307 auto digests = (curve == EcCurve::CURVE_25519)
3308 ? std::vector<Digest>(1, Digest::NONE)
3309 : ValidDigests(true /* withNone */, false /* withMD5 */);
3310
David Drysdaledf8f52e2021-05-06 08:10:58 +01003311 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3312 .Authorization(TAG_NO_AUTH_REQUIRED)
3313 .EcdsaSigningKey(curve)
3314 .Digest(digests)
3315 .SetDefaultValidity());
3316 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3317 if (error != ErrorCode::OK) {
3318 continue;
3319 }
3320
3321 for (auto digest : digests) {
3322 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3323 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3324 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3325 }
3326
3327 auto rc = DeleteKey();
3328 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3329 }
3330}
3331
3332/*
Selene Huang31ab4042020-04-29 04:22:39 -07003333 * SigningOperationsTest.EcdsaAllCurves
3334 *
David Drysdale42fe1892021-10-14 14:43:46 +01003335 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003336 */
3337TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3338 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003339 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3340 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003341 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3342 .Authorization(TAG_NO_AUTH_REQUIRED)
3343 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003344 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003345 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003346 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3347 if (error != ErrorCode::OK) continue;
3348
3349 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003350 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003351 CheckedDeleteKey();
3352 }
3353}
3354
3355/*
David Drysdale42fe1892021-10-14 14:43:46 +01003356 * SigningOperationsTest.EcdsaCurve25519
3357 *
3358 * Verifies that ECDSA operations succeed with curve25519.
3359 */
3360TEST_P(SigningOperationsTest, EcdsaCurve25519) {
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 string message(1024, 'a');
3374 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3375 CheckedDeleteKey();
3376}
3377
3378/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003379 * SigningOperationsTest.EcdsaCurve25519MaxSize
3380 *
3381 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3382 */
3383TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3384 if (!Curve25519Supported()) {
3385 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3386 }
3387
3388 EcCurve curve = EcCurve::CURVE_25519;
3389 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3390 .Authorization(TAG_NO_AUTH_REQUIRED)
3391 .EcdsaSigningKey(curve)
3392 .Digest(Digest::NONE)
3393 .SetDefaultValidity());
3394 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3395
3396 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3397
3398 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3399 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3400 string message(msg_size, 'a');
3401
3402 // Attempt to sign via Begin+Finish.
3403 AuthorizationSet out_params;
3404 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3405 EXPECT_TRUE(out_params.empty());
3406 string signature;
3407 auto result = Finish(message, &signature);
3408 EXPECT_EQ(result, ErrorCode::OK);
3409 LocalVerifyMessage(message, signature, params);
3410
3411 // Attempt to sign via Begin+Update+Finish
3412 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3413 EXPECT_TRUE(out_params.empty());
3414 string output;
3415 result = Update(message, &output);
3416 EXPECT_EQ(result, ErrorCode::OK);
3417 EXPECT_EQ(output.size(), 0);
3418 string signature2;
3419 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3420 LocalVerifyMessage(message, signature2, params);
3421 }
3422
3423 CheckedDeleteKey();
3424}
3425
3426/*
3427 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3428 *
3429 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3430 */
3431TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3432 if (!Curve25519Supported()) {
3433 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3434 }
3435
3436 EcCurve curve = EcCurve::CURVE_25519;
3437 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3438 .Authorization(TAG_NO_AUTH_REQUIRED)
3439 .EcdsaSigningKey(curve)
3440 .Digest(Digest::NONE)
3441 .SetDefaultValidity());
3442 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3443
3444 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3445
3446 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3447 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3448 string message(msg_size, 'a');
3449
3450 // Attempt to sign via Begin+Finish.
3451 AuthorizationSet out_params;
3452 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3453 EXPECT_TRUE(out_params.empty());
3454 string signature;
3455 auto result = Finish(message, &signature);
3456 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3457
3458 // Attempt to sign via Begin+Update (but never get to Finish)
3459 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3460 EXPECT_TRUE(out_params.empty());
3461 string output;
3462 result = Update(message, &output);
3463 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3464 }
3465
3466 CheckedDeleteKey();
3467}
3468
3469/*
Selene Huang31ab4042020-04-29 04:22:39 -07003470 * SigningOperationsTest.EcdsaNoDigestHugeData
3471 *
3472 * Verifies that ECDSA operations support very large messages, even without digesting. This
3473 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3474 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3475 * the framework.
3476 */
3477TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3478 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3479 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003480 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003481 .Digest(Digest::NONE)
3482 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003483 string message(1 * 1024, 'a');
3484 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3485}
3486
3487/*
3488 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3489 *
3490 * Verifies that using an EC key requires the correct app ID/data.
3491 */
3492TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3493 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3494 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003495 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003496 .Digest(Digest::NONE)
3497 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003498 .Authorization(TAG_APPLICATION_DATA, "appdata")
3499 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003500
3501 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3502
Selene Huang31ab4042020-04-29 04:22:39 -07003503 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3504 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3505 AbortIfNeeded();
3506 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3507 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3508 .Digest(Digest::NONE)
3509 .Authorization(TAG_APPLICATION_ID, "clientid")));
3510 AbortIfNeeded();
3511 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3512 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3513 .Digest(Digest::NONE)
3514 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3515 AbortIfNeeded();
3516 EXPECT_EQ(ErrorCode::OK,
3517 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3518 .Digest(Digest::NONE)
3519 .Authorization(TAG_APPLICATION_DATA, "appdata")
3520 .Authorization(TAG_APPLICATION_ID, "clientid")));
3521 AbortIfNeeded();
3522}
3523
3524/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003525 * SigningOperationsTest.EcdsaIncompatibleDigest
3526 *
3527 * Verifies that using an EC key requires compatible digest.
3528 */
3529TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3530 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3531 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003532 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003533 .Digest(Digest::NONE)
3534 .Digest(Digest::SHA1)
3535 .SetDefaultValidity()));
3536 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3537 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3538 AbortIfNeeded();
3539}
3540
3541/*
Selene Huang31ab4042020-04-29 04:22:39 -07003542 * SigningOperationsTest.AesEcbSign
3543 *
3544 * Verifies that attempts to use AES keys to sign fail in the correct way.
3545 */
3546TEST_P(SigningOperationsTest, AesEcbSign) {
3547 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3548 .Authorization(TAG_NO_AUTH_REQUIRED)
3549 .SigningKey()
3550 .AesEncryptionKey(128)
3551 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3552
3553 AuthorizationSet out_params;
3554 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3555 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3556 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3557 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3558}
3559
3560/*
3561 * SigningOperationsTest.HmacAllDigests
3562 *
3563 * Verifies that HMAC works with all digests.
3564 */
3565TEST_P(SigningOperationsTest, HmacAllDigests) {
3566 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003567 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003568 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3569 .Authorization(TAG_NO_AUTH_REQUIRED)
3570 .HmacKey(128)
3571 .Digest(digest)
3572 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3573 << "Failed to create HMAC key with digest " << digest;
3574 string message = "12345678901234567890123456789012";
3575 string signature = MacMessage(message, digest, 160);
3576 EXPECT_EQ(160U / 8U, signature.size())
3577 << "Failed to sign with HMAC key with digest " << digest;
3578 CheckedDeleteKey();
3579 }
3580}
3581
3582/*
3583 * SigningOperationsTest.HmacSha256TooLargeMacLength
3584 *
3585 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3586 * digest size.
3587 */
3588TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3589 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3590 .Authorization(TAG_NO_AUTH_REQUIRED)
3591 .HmacKey(128)
3592 .Digest(Digest::SHA_2_256)
3593 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3594 AuthorizationSet output_params;
3595 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3596 AuthorizationSetBuilder()
3597 .Digest(Digest::SHA_2_256)
3598 .Authorization(TAG_MAC_LENGTH, 264),
3599 &output_params));
3600}
3601
3602/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003603 * SigningOperationsTest.HmacSha256InvalidMacLength
3604 *
3605 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3606 * not a multiple of 8.
3607 */
3608TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3609 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3610 .Authorization(TAG_NO_AUTH_REQUIRED)
3611 .HmacKey(128)
3612 .Digest(Digest::SHA_2_256)
3613 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3614 AuthorizationSet output_params;
3615 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3616 AuthorizationSetBuilder()
3617 .Digest(Digest::SHA_2_256)
3618 .Authorization(TAG_MAC_LENGTH, 161),
3619 &output_params));
3620}
3621
3622/*
Selene Huang31ab4042020-04-29 04:22:39 -07003623 * SigningOperationsTest.HmacSha256TooSmallMacLength
3624 *
3625 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3626 * specified minimum MAC length.
3627 */
3628TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3629 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3630 .Authorization(TAG_NO_AUTH_REQUIRED)
3631 .HmacKey(128)
3632 .Digest(Digest::SHA_2_256)
3633 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3634 AuthorizationSet output_params;
3635 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3636 AuthorizationSetBuilder()
3637 .Digest(Digest::SHA_2_256)
3638 .Authorization(TAG_MAC_LENGTH, 120),
3639 &output_params));
3640}
3641
3642/*
3643 * SigningOperationsTest.HmacRfc4231TestCase3
3644 *
3645 * Validates against the test vectors from RFC 4231 test case 3.
3646 */
3647TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3648 string key(20, 0xaa);
3649 string message(50, 0xdd);
3650 uint8_t sha_224_expected[] = {
3651 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3652 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3653 };
3654 uint8_t sha_256_expected[] = {
3655 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3656 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3657 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3658 };
3659 uint8_t sha_384_expected[] = {
3660 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3661 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3662 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3663 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3664 };
3665 uint8_t sha_512_expected[] = {
3666 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3667 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3668 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3669 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3670 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3671 };
3672
3673 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3674 if (SecLevel() != SecurityLevel::STRONGBOX) {
3675 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3676 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3677 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3678 }
3679}
3680
3681/*
3682 * SigningOperationsTest.HmacRfc4231TestCase5
3683 *
3684 * Validates against the test vectors from RFC 4231 test case 5.
3685 */
3686TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3687 string key(20, 0x0c);
3688 string message = "Test With Truncation";
3689
3690 uint8_t sha_224_expected[] = {
3691 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3692 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3693 };
3694 uint8_t sha_256_expected[] = {
3695 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3696 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3697 };
3698 uint8_t sha_384_expected[] = {
3699 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3700 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3701 };
3702 uint8_t sha_512_expected[] = {
3703 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3704 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3705 };
3706
3707 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3708 if (SecLevel() != SecurityLevel::STRONGBOX) {
3709 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3710 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3711 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3712 }
3713}
3714
3715INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3716
3717typedef KeyMintAidlTestBase VerificationOperationsTest;
3718
3719/*
Selene Huang31ab4042020-04-29 04:22:39 -07003720 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3721 *
3722 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3723 */
3724TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3725 string key_material = "HelloThisIsAKey";
3726
3727 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003728 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003729 EXPECT_EQ(ErrorCode::OK,
3730 ImportKey(AuthorizationSetBuilder()
3731 .Authorization(TAG_NO_AUTH_REQUIRED)
3732 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3733 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3734 .Digest(Digest::SHA_2_256)
3735 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3736 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3737 EXPECT_EQ(ErrorCode::OK,
3738 ImportKey(AuthorizationSetBuilder()
3739 .Authorization(TAG_NO_AUTH_REQUIRED)
3740 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3741 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3742 .Digest(Digest::SHA_2_256)
3743 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3744 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3745
3746 string message = "This is a message.";
3747 string signature = SignMessage(
3748 signing_key, message,
3749 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3750
3751 // Signing key should not work.
3752 AuthorizationSet out_params;
3753 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3754 Begin(KeyPurpose::VERIFY, signing_key,
3755 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3756
3757 // Verification key should work.
3758 VerifyMessage(verification_key, message, signature,
3759 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3760
3761 CheckedDeleteKey(&signing_key);
3762 CheckedDeleteKey(&verification_key);
3763}
3764
Prashant Patildec9fdc2021-12-08 15:25:47 +00003765/*
3766 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3767 *
3768 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3769 */
3770TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3771 string key_material = "HelloThisIsAKey";
3772
3773 vector<uint8_t> signing_key, verification_key;
3774 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3775 EXPECT_EQ(ErrorCode::OK,
3776 ImportKey(AuthorizationSetBuilder()
3777 .Authorization(TAG_NO_AUTH_REQUIRED)
3778 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3779 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3780 .Digest(Digest::SHA_2_256)
3781 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3782 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3783 EXPECT_EQ(ErrorCode::OK,
3784 ImportKey(AuthorizationSetBuilder()
3785 .Authorization(TAG_NO_AUTH_REQUIRED)
3786 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3787 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3788 .Digest(Digest::SHA_2_256)
3789 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3790 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3791
3792 string message = "This is a message.";
3793 string signature = SignMessage(
3794 signing_key, message,
3795 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3796
3797 AuthorizationSet begin_out_params;
3798 ASSERT_EQ(ErrorCode::OK,
3799 Begin(KeyPurpose::VERIFY, verification_key,
3800 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3801
3802 string corruptMessage = "This is b message."; // Corrupted message
3803 string output;
3804 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3805
3806 ASSERT_EQ(ErrorCode::OK,
3807 Begin(KeyPurpose::VERIFY, verification_key,
3808 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3809
3810 signature[0] += 1; // Corrupt a signature
3811 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3812
3813 CheckedDeleteKey(&signing_key);
3814 CheckedDeleteKey(&verification_key);
3815}
3816
Selene Huang31ab4042020-04-29 04:22:39 -07003817INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3818
3819typedef KeyMintAidlTestBase ExportKeyTest;
3820
3821/*
3822 * ExportKeyTest.RsaUnsupportedKeyFormat
3823 *
3824 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3825 */
3826// TODO(seleneh) add ExportKey to GenerateKey
3827// check result
3828
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003829class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003830 public:
3831 template <TagType tag_type, Tag tag, typename ValueT>
3832 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3833 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003834 for (auto& entry : key_characteristics_) {
3835 if (entry.securityLevel == SecLevel()) {
3836 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3837 << "Tag " << tag << " with value " << expected
3838 << " not found at security level" << entry.securityLevel;
3839 } else {
3840 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3841 << "Tag " << tag << " found at security level " << entry.securityLevel;
3842 }
Selene Huang31ab4042020-04-29 04:22:39 -07003843 }
3844 }
3845
3846 void CheckOrigin() {
3847 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003848 // Origin isn't a crypto param, but it always lives with them.
3849 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003850 }
3851};
3852
3853/*
3854 * ImportKeyTest.RsaSuccess
3855 *
3856 * Verifies that importing and using an RSA key pair works correctly.
3857 */
3858TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003859 uint32_t key_size;
3860 string key;
3861
3862 if (SecLevel() == SecurityLevel::STRONGBOX) {
3863 key_size = 2048;
3864 key = rsa_2048_key;
3865 } else {
3866 key_size = 1024;
3867 key = rsa_key;
3868 }
3869
Selene Huang31ab4042020-04-29 04:22:39 -07003870 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3871 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003872 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003873 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003874 .Padding(PaddingMode::RSA_PSS)
3875 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003876 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003877
3878 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003879 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003880 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3881 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3882 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3883 CheckOrigin();
3884
3885 string message(1024 / 8, 'a');
3886 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3887 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003888 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003889}
3890
3891/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003892 * ImportKeyTest.RsaSuccessWithoutParams
3893 *
3894 * Verifies that importing and using an RSA key pair without specifying parameters
3895 * works correctly.
3896 */
3897TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3898 uint32_t key_size;
3899 string key;
3900
3901 if (SecLevel() == SecurityLevel::STRONGBOX) {
3902 key_size = 2048;
3903 key = rsa_2048_key;
3904 } else {
3905 key_size = 1024;
3906 key = rsa_key;
3907 }
3908
3909 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3910 .Authorization(TAG_NO_AUTH_REQUIRED)
3911 .SigningKey()
3912 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3913 .Digest(Digest::SHA_2_256)
3914 .Padding(PaddingMode::RSA_PSS)
3915 .SetDefaultValidity(),
3916 KeyFormat::PKCS8, key));
3917
3918 // Key size and public exponent are determined from the imported key material.
3919 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3920 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3921
3922 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3923 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3924 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3925 CheckOrigin();
3926
3927 string message(1024 / 8, 'a');
3928 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3929 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003930 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003931}
3932
3933/*
Selene Huang31ab4042020-04-29 04:22:39 -07003934 * ImportKeyTest.RsaKeySizeMismatch
3935 *
3936 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3937 * correct way.
3938 */
3939TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3940 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3941 ImportKey(AuthorizationSetBuilder()
3942 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3943 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003944 .Padding(PaddingMode::NONE)
3945 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003946 KeyFormat::PKCS8, rsa_key));
3947}
3948
3949/*
3950 * ImportKeyTest.RsaPublicExponentMismatch
3951 *
3952 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3953 * fails in the correct way.
3954 */
3955TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3956 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3957 ImportKey(AuthorizationSetBuilder()
3958 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3959 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003960 .Padding(PaddingMode::NONE)
3961 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003962 KeyFormat::PKCS8, rsa_key));
3963}
3964
3965/*
David Drysdalee60248c2021-10-04 12:54:13 +01003966 * ImportKeyTest.RsaAttestMultiPurposeFail
3967 *
3968 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
3969 */
3970TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00003971 if (AidlVersion() < 2) {
3972 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
3973 // with other key purposes. However, this was not checked at the time
3974 // so we can only be strict about checking this for implementations of KeyMint
3975 // version 2 and above.
3976 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
3977 }
David Drysdalee60248c2021-10-04 12:54:13 +01003978 uint32_t key_size = 2048;
3979 string key = rsa_2048_key;
3980
3981 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3982 ImportKey(AuthorizationSetBuilder()
3983 .Authorization(TAG_NO_AUTH_REQUIRED)
3984 .RsaSigningKey(key_size, 65537)
3985 .AttestKey()
3986 .Digest(Digest::SHA_2_256)
3987 .Padding(PaddingMode::RSA_PSS)
3988 .SetDefaultValidity(),
3989 KeyFormat::PKCS8, key));
3990}
3991
3992/*
Selene Huang31ab4042020-04-29 04:22:39 -07003993 * ImportKeyTest.EcdsaSuccess
3994 *
3995 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3996 */
3997TEST_P(ImportKeyTest, EcdsaSuccess) {
3998 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3999 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004000 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004001 .Digest(Digest::SHA_2_256)
4002 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004003 KeyFormat::PKCS8, ec_256_key));
4004
4005 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004006 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4007 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4008
4009 CheckOrigin();
4010
4011 string message(32, 'a');
4012 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4013 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004014 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004015}
4016
4017/*
4018 * ImportKeyTest.EcdsaP256RFC5915Success
4019 *
4020 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4021 * correctly.
4022 */
4023TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4024 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4025 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004026 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004027 .Digest(Digest::SHA_2_256)
4028 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004029 KeyFormat::PKCS8, ec_256_key_rfc5915));
4030
4031 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004032 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4033 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4034
4035 CheckOrigin();
4036
4037 string message(32, 'a');
4038 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4039 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004040 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004041}
4042
4043/*
4044 * ImportKeyTest.EcdsaP256SEC1Success
4045 *
4046 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4047 */
4048TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4049 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4050 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004051 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004052 .Digest(Digest::SHA_2_256)
4053 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004054 KeyFormat::PKCS8, ec_256_key_sec1));
4055
4056 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004057 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4058 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4059
4060 CheckOrigin();
4061
4062 string message(32, 'a');
4063 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4064 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004065 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004066}
4067
4068/*
4069 * ImportKeyTest.Ecdsa521Success
4070 *
4071 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4072 */
4073TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004074 if (SecLevel() == SecurityLevel::STRONGBOX) {
4075 GTEST_SKIP() << "Test not applicable to StrongBox device";
4076 }
Selene Huang31ab4042020-04-29 04:22:39 -07004077 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4078 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004079 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004080 .Digest(Digest::SHA_2_256)
4081 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004082 KeyFormat::PKCS8, ec_521_key));
4083
4084 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004085 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4086 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4087 CheckOrigin();
4088
4089 string message(32, 'a');
4090 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4091 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004092 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004093}
4094
4095/*
Selene Huang31ab4042020-04-29 04:22:39 -07004096 * ImportKeyTest.EcdsaCurveMismatch
4097 *
4098 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4099 * the correct way.
4100 */
4101TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4102 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4103 ImportKey(AuthorizationSetBuilder()
4104 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004105 .Digest(Digest::NONE)
4106 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004107 KeyFormat::PKCS8, ec_256_key));
4108}
4109
4110/*
David Drysdalee60248c2021-10-04 12:54:13 +01004111 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4112 *
4113 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4114 */
4115TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004116 if (AidlVersion() < 2) {
4117 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4118 // with other key purposes. However, this was not checked at the time
4119 // so we can only be strict about checking this for implementations of KeyMint
4120 // version 2 and above.
4121 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4122 }
David Drysdalee60248c2021-10-04 12:54:13 +01004123 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4124 ImportKey(AuthorizationSetBuilder()
4125 .Authorization(TAG_NO_AUTH_REQUIRED)
4126 .EcdsaSigningKey(EcCurve::P_256)
4127 .AttestKey()
4128 .Digest(Digest::SHA_2_256)
4129 .SetDefaultValidity(),
4130 KeyFormat::PKCS8, ec_256_key));
4131}
4132
4133/*
David Drysdale42fe1892021-10-14 14:43:46 +01004134 * ImportKeyTest.Ed25519RawSuccess
4135 *
4136 * Verifies that importing and using a raw Ed25519 private key works correctly.
4137 */
4138TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4139 if (!Curve25519Supported()) {
4140 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4141 }
4142
4143 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4144 .Authorization(TAG_NO_AUTH_REQUIRED)
4145 .EcdsaSigningKey(EcCurve::CURVE_25519)
4146 .Digest(Digest::NONE)
4147 .SetDefaultValidity(),
4148 KeyFormat::RAW, ed25519_key));
4149 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4150 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4151 CheckOrigin();
4152
4153 // The returned cert should hold the correct public key.
4154 ASSERT_GT(cert_chain_.size(), 0);
4155 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4156 ASSERT_NE(kmKeyCert, nullptr);
4157 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4158 ASSERT_NE(kmPubKey.get(), nullptr);
4159 size_t kmPubKeySize = 32;
4160 uint8_t kmPubKeyData[32];
4161 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4162 ASSERT_EQ(kmPubKeySize, 32);
4163 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4164
4165 string message(32, 'a');
4166 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4167 string signature = SignMessage(message, params);
4168 LocalVerifyMessage(message, signature, params);
4169}
4170
4171/*
4172 * ImportKeyTest.Ed25519Pkcs8Success
4173 *
4174 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4175 */
4176TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4177 if (!Curve25519Supported()) {
4178 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4179 }
4180
4181 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4182 .Authorization(TAG_NO_AUTH_REQUIRED)
4183 .EcdsaSigningKey(EcCurve::CURVE_25519)
4184 .Digest(Digest::NONE)
4185 .SetDefaultValidity(),
4186 KeyFormat::PKCS8, ed25519_pkcs8_key));
4187 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4188 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4189 CheckOrigin();
4190
4191 // The returned cert should hold the correct public key.
4192 ASSERT_GT(cert_chain_.size(), 0);
4193 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4194 ASSERT_NE(kmKeyCert, nullptr);
4195 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4196 ASSERT_NE(kmPubKey.get(), nullptr);
4197 size_t kmPubKeySize = 32;
4198 uint8_t kmPubKeyData[32];
4199 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4200 ASSERT_EQ(kmPubKeySize, 32);
4201 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4202
4203 string message(32, 'a');
4204 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4205 string signature = SignMessage(message, params);
4206 LocalVerifyMessage(message, signature, params);
4207}
4208
4209/*
4210 * ImportKeyTest.Ed25519CurveMismatch
4211 *
4212 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4213 * the correct way.
4214 */
4215TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4216 if (!Curve25519Supported()) {
4217 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4218 }
4219
4220 ASSERT_NE(ErrorCode::OK,
4221 ImportKey(AuthorizationSetBuilder()
4222 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4223 .Digest(Digest::NONE)
4224 .SetDefaultValidity(),
4225 KeyFormat::RAW, ed25519_key));
4226}
4227
4228/*
4229 * ImportKeyTest.Ed25519FormatMismatch
4230 *
4231 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4232 */
4233TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4234 if (!Curve25519Supported()) {
4235 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4236 }
4237
4238 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4239 .EcdsaSigningKey(EcCurve::CURVE_25519)
4240 .Digest(Digest::NONE)
4241 .SetDefaultValidity(),
4242 KeyFormat::PKCS8, ed25519_key));
4243 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4244 .EcdsaSigningKey(EcCurve::CURVE_25519)
4245 .Digest(Digest::NONE)
4246 .SetDefaultValidity(),
4247 KeyFormat::RAW, ed25519_pkcs8_key));
4248}
4249
4250/*
4251 * ImportKeyTest.Ed25519PurposeMismatch
4252 *
4253 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4254 */
4255TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4256 if (!Curve25519Supported()) {
4257 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4258 }
4259
4260 // Can't have both SIGN and ATTEST_KEY
4261 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4262 .EcdsaSigningKey(EcCurve::CURVE_25519)
4263 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4264 .Digest(Digest::NONE)
4265 .SetDefaultValidity(),
4266 KeyFormat::RAW, ed25519_key));
4267 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4268 // PKCS#8 format and so includes an OID).
4269 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4270 .EcdsaKey(EcCurve::CURVE_25519)
4271 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4272 .Digest(Digest::NONE)
4273 .SetDefaultValidity(),
4274 KeyFormat::PKCS8, ed25519_pkcs8_key));
4275}
4276
4277/*
4278 * ImportKeyTest.X25519RawSuccess
4279 *
4280 * Verifies that importing and using a raw X25519 private key works correctly.
4281 */
4282TEST_P(ImportKeyTest, X25519RawSuccess) {
4283 if (!Curve25519Supported()) {
4284 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4285 }
4286
4287 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4288 .Authorization(TAG_NO_AUTH_REQUIRED)
4289 .EcdsaKey(EcCurve::CURVE_25519)
4290 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4291 .SetDefaultValidity(),
4292 KeyFormat::RAW, x25519_key));
4293
4294 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4295 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4296 CheckOrigin();
4297}
4298
4299/*
4300 * ImportKeyTest.X25519Pkcs8Success
4301 *
4302 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4303 */
4304TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4305 if (!Curve25519Supported()) {
4306 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4307 }
4308
4309 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4310 .Authorization(TAG_NO_AUTH_REQUIRED)
4311 .EcdsaKey(EcCurve::CURVE_25519)
4312 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4313 .SetDefaultValidity(),
4314 KeyFormat::PKCS8, x25519_pkcs8_key));
4315
4316 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4317 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4318 CheckOrigin();
4319}
4320
4321/*
4322 * ImportKeyTest.X25519CurveMismatch
4323 *
4324 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4325 * the correct way.
4326 */
4327TEST_P(ImportKeyTest, X25519CurveMismatch) {
4328 if (!Curve25519Supported()) {
4329 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4330 }
4331
4332 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4333 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4334 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4335 .SetDefaultValidity(),
4336 KeyFormat::RAW, x25519_key));
4337}
4338
4339/*
4340 * ImportKeyTest.X25519FormatMismatch
4341 *
4342 * Verifies that importing an X25519 key with an invalid format fails.
4343 */
4344TEST_P(ImportKeyTest, X25519FormatMismatch) {
4345 if (!Curve25519Supported()) {
4346 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4347 }
4348
4349 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4350 .EcdsaKey(EcCurve::CURVE_25519)
4351 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4352 .SetDefaultValidity(),
4353 KeyFormat::PKCS8, x25519_key));
4354 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4355 .EcdsaKey(EcCurve::CURVE_25519)
4356 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4357 .SetDefaultValidity(),
4358 KeyFormat::RAW, x25519_pkcs8_key));
4359}
4360
4361/*
4362 * ImportKeyTest.X25519PurposeMismatch
4363 *
4364 * Verifies that importing an X25519 key pair with an invalid format fails.
4365 */
4366TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4367 if (!Curve25519Supported()) {
4368 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4369 }
4370
4371 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4372 .EcdsaKey(EcCurve::CURVE_25519)
4373 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4374 .SetDefaultValidity(),
4375 KeyFormat::PKCS8, x25519_pkcs8_key));
4376 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4377 .EcdsaSigningKey(EcCurve::CURVE_25519)
4378 .SetDefaultValidity(),
4379 KeyFormat::PKCS8, x25519_pkcs8_key));
4380}
4381
4382/*
Selene Huang31ab4042020-04-29 04:22:39 -07004383 * ImportKeyTest.AesSuccess
4384 *
4385 * Verifies that importing and using an AES key works.
4386 */
4387TEST_P(ImportKeyTest, AesSuccess) {
4388 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4389 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4390 .Authorization(TAG_NO_AUTH_REQUIRED)
4391 .AesEncryptionKey(key.size() * 8)
4392 .EcbMode()
4393 .Padding(PaddingMode::PKCS7),
4394 KeyFormat::RAW, key));
4395
4396 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4397 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4398 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4399 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4400 CheckOrigin();
4401
4402 string message = "Hello World!";
4403 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4404 string ciphertext = EncryptMessage(message, params);
4405 string plaintext = DecryptMessage(ciphertext, params);
4406 EXPECT_EQ(message, plaintext);
4407}
4408
4409/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004410 * ImportKeyTest.AesFailure
4411 *
4412 * Verifies that importing an invalid AES key fails.
4413 */
4414TEST_P(ImportKeyTest, AesFailure) {
4415 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4416 uint32_t bitlen = key.size() * 8;
4417 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004418 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004419 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004420 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004421 .Authorization(TAG_NO_AUTH_REQUIRED)
4422 .AesEncryptionKey(key_size)
4423 .EcbMode()
4424 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004425 KeyFormat::RAW, key);
4426 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004427 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4428 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004429 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004430
4431 // Explicit key size matches that of the provided key, but it's not a valid size.
4432 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4433 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4434 ImportKey(AuthorizationSetBuilder()
4435 .Authorization(TAG_NO_AUTH_REQUIRED)
4436 .AesEncryptionKey(long_key.size() * 8)
4437 .EcbMode()
4438 .Padding(PaddingMode::PKCS7),
4439 KeyFormat::RAW, long_key));
4440 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4441 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4442 ImportKey(AuthorizationSetBuilder()
4443 .Authorization(TAG_NO_AUTH_REQUIRED)
4444 .AesEncryptionKey(short_key.size() * 8)
4445 .EcbMode()
4446 .Padding(PaddingMode::PKCS7),
4447 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004448}
4449
4450/*
4451 * ImportKeyTest.TripleDesSuccess
4452 *
4453 * Verifies that importing and using a 3DES key works.
4454 */
4455TEST_P(ImportKeyTest, TripleDesSuccess) {
4456 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4457 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4458 .Authorization(TAG_NO_AUTH_REQUIRED)
4459 .TripleDesEncryptionKey(168)
4460 .EcbMode()
4461 .Padding(PaddingMode::PKCS7),
4462 KeyFormat::RAW, key));
4463
4464 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4465 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4466 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4467 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4468 CheckOrigin();
4469
4470 string message = "Hello World!";
4471 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4472 string ciphertext = EncryptMessage(message, params);
4473 string plaintext = DecryptMessage(ciphertext, params);
4474 EXPECT_EQ(message, plaintext);
4475}
4476
4477/*
4478 * ImportKeyTest.TripleDesFailure
4479 *
4480 * Verifies that importing an invalid 3DES key fails.
4481 */
4482TEST_P(ImportKeyTest, TripleDesFailure) {
4483 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004484 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004485 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004486 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004487 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004488 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004489 .Authorization(TAG_NO_AUTH_REQUIRED)
4490 .TripleDesEncryptionKey(key_size)
4491 .EcbMode()
4492 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004493 KeyFormat::RAW, key);
4494 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004495 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4496 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004497 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004498 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004499 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004500 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4501 ImportKey(AuthorizationSetBuilder()
4502 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004503 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004504 .EcbMode()
4505 .Padding(PaddingMode::PKCS7),
4506 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004507 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004508 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4509 ImportKey(AuthorizationSetBuilder()
4510 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004511 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004512 .EcbMode()
4513 .Padding(PaddingMode::PKCS7),
4514 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004515}
4516
4517/*
4518 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004519 *
4520 * Verifies that importing and using an HMAC key works.
4521 */
4522TEST_P(ImportKeyTest, HmacKeySuccess) {
4523 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4524 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4525 .Authorization(TAG_NO_AUTH_REQUIRED)
4526 .HmacKey(key.size() * 8)
4527 .Digest(Digest::SHA_2_256)
4528 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4529 KeyFormat::RAW, key));
4530
4531 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4532 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4533 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4534 CheckOrigin();
4535
4536 string message = "Hello World!";
4537 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4538 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4539}
4540
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004541/*
4542 * ImportKeyTest.GetKeyCharacteristics
4543 *
4544 * Verifies that imported keys have the correct characteristics.
4545 */
4546TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4547 vector<uint8_t> key_blob;
4548 vector<KeyCharacteristics> key_characteristics;
4549 auto base_builder = AuthorizationSetBuilder()
4550 .Padding(PaddingMode::NONE)
4551 .Authorization(TAG_NO_AUTH_REQUIRED)
4552 .SetDefaultValidity();
4553 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4554 Algorithm::TRIPLE_DES};
4555 ErrorCode result;
4556 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4557 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4558 for (auto alg : algorithms) {
4559 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4560 AuthorizationSetBuilder builder(base_builder);
4561 switch (alg) {
4562 case Algorithm::RSA:
4563 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4564
4565 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4566 &key_characteristics);
4567 break;
4568 case Algorithm::EC:
4569 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4570 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4571 &key_characteristics);
4572 break;
4573 case Algorithm::HMAC:
4574 builder.HmacKey(128)
4575 .Digest(Digest::SHA_2_256)
4576 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4577 result =
4578 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4579 break;
4580 case Algorithm::AES:
4581 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4582 result =
4583 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4584 break;
4585 case Algorithm::TRIPLE_DES:
4586 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4587 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4588 &key_characteristics);
4589 break;
4590 default:
4591 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4592 continue;
4593 }
4594 ASSERT_EQ(ErrorCode::OK, result);
4595 CheckCharacteristics(key_blob, key_characteristics);
4596 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4597 }
4598}
4599
Selene Huang31ab4042020-04-29 04:22:39 -07004600INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4601
4602auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004603 // IKeyMintDevice.aidl
4604 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4605 "020100" // INTEGER length 1 value 0x00 (version)
4606 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4607 "934bf94e2aa28a3f83c9f79297250262"
4608 "fbe3276b5a1c91159bbfa3ef8957aac8"
4609 "4b59b30b455a79c2973480823d8b3863"
4610 "c3deef4a8e243590268d80e18751a0e1"
4611 "30f67ce6a1ace9f79b95e097474febc9"
4612 "81195b1d13a69086c0863f66a7b7fdb4"
4613 "8792227b1ac5e2489febdf087ab54864"
4614 "83033a6f001ca5d1ec1e27f5c30f4cec"
4615 "2642074a39ae68aee552e196627a8e3d"
4616 "867e67a8c01b11e75f13cca0a97ab668"
4617 "b50cda07a8ecb7cd8e3dd7009c963653"
4618 "4f6f239cffe1fc8daa466f78b676c711"
4619 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4620 "99b801597d5220e307eaa5bee507fb94"
4621 "d1fa69f9e519b2de315bac92c36f2ea1"
4622 "fa1df4478c0ddedeae8c70e0233cd098"
4623 "040c" // OCTET STRING length 0x0c (initializationVector)
4624 "d796b02c370f1fa4cc0124f1"
4625 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4626 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4627 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4628 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4629 "3106" // SET length 0x06
4630 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4631 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4632 // } end SET
4633 // } end [1]
4634 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4635 "020120" // INTEGER length 1 value 0x20 (AES)
4636 // } end [2]
4637 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4638 "02020100" // INTEGER length 2 value 0x100
4639 // } end [3]
4640 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4641 "3103" // SET length 0x03 {
4642 "020101" // INTEGER length 1 value 0x01 (ECB)
4643 // } end SET
4644 // } end [4]
4645 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4646 "3103" // SET length 0x03 {
4647 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4648 // } end SET
4649 // } end [5]
4650 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4651 // (noAuthRequired)
4652 "0500" // NULL
4653 // } end [503]
4654 // } end SEQUENCE (AuthorizationList)
4655 // } end SEQUENCE (KeyDescription)
4656 "0420" // OCTET STRING length 0x20 (encryptedKey)
4657 "ccd540855f833a5e1480bfd2d36faf3a"
4658 "eee15df5beabe2691bc82dde2a7aa910"
4659 "0410" // OCTET STRING length 0x10 (tag)
4660 "64c9f689c60ff6223ab6e6999e0eb6e5"
4661 // } SEQUENCE (SecureKeyWrapper)
4662);
Selene Huang31ab4042020-04-29 04:22:39 -07004663
4664auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004665 // IKeyMintDevice.aidl
4666 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4667 "020100" // INTEGER length 1 value 0x00 (version)
4668 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4669 "aad93ed5924f283b4bb5526fbe7a1412"
4670 "f9d9749ec30db9062b29e574a8546f33"
4671 "c88732452f5b8e6a391ee76c39ed1712"
4672 "c61d8df6213dec1cffbc17a8c6d04c7b"
4673 "30893d8daa9b2015213e219468215532"
4674 "07f8f9931c4caba23ed3bee28b36947e"
4675 "47f10e0a5c3dc51c988a628daad3e5e1"
4676 "f4005e79c2d5a96c284b4b8d7e4948f3"
4677 "31e5b85dd5a236f85579f3ea1d1b8484"
4678 "87470bdb0ab4f81a12bee42c99fe0df4"
4679 "bee3759453e69ad1d68a809ce06b949f"
4680 "7694a990429b2fe81e066ff43e56a216"
4681 "02db70757922a4bcc23ab89f1e35da77"
4682 "586775f423e519c2ea394caf48a28d0c"
4683 "8020f1dcf6b3a68ec246f615ae96dae9"
4684 "a079b1f6eb959033c1af5c125fd94168"
4685 "040c" // OCTET STRING length 0x0c (initializationVector)
4686 "6d9721d08589581ab49204a3"
4687 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4688 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4689 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4690 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4691 "3106" // SET length 0x06
4692 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4693 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4694 // } end SET
4695 // } end [1]
4696 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4697 "020120" // INTEGER length 1 value 0x20 (AES)
4698 // } end [2]
4699 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4700 "02020100" // INTEGER length 2 value 0x100
4701 // } end [3]
4702 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4703 "3103" // SET length 0x03 {
4704 "020101" // INTEGER length 1 value 0x01 (ECB)
4705 // } end SET
4706 // } end [4]
4707 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4708 "3103" // SET length 0x03 {
4709 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4710 // } end SET
4711 // } end [5]
4712 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4713 // (noAuthRequired)
4714 "0500" // NULL
4715 // } end [503]
4716 // } end SEQUENCE (AuthorizationList)
4717 // } end SEQUENCE (KeyDescription)
4718 "0420" // OCTET STRING length 0x20 (encryptedKey)
4719 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4720 "c20d1f99a9a024a76f35c8e2cab9b68d"
4721 "0410" // OCTET STRING length 0x10 (tag)
4722 "2560c70109ae67c030f00b98b512a670"
4723 // } SEQUENCE (SecureKeyWrapper)
4724);
Selene Huang31ab4042020-04-29 04:22:39 -07004725
4726auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004727 // RFC 5208 s5
4728 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4729 "020100" // INTEGER length 1 value 0x00 (version)
4730 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4731 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4732 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4733 "0500" // NULL (parameters)
4734 // } SEQUENCE (AlgorithmIdentifier)
4735 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4736 // RFC 8017 A.1.2
4737 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4738 "020100" // INTEGER length 1 value 0x00 (version)
4739 "02820101" // INTEGER length 0x0101 (modulus) value...
4740 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4741 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4742 "7b06e673a837313d56b1c725150a3fef" // 0x30
4743 "86acbddc41bb759c2854eae32d35841e" // 0x40
4744 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4745 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4746 "312d7bd5921ffaea1347c157406fef71" // 0x70
4747 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4748 "f4645c11f5c1374c3886427411c44979" // 0x90
4749 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4750 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4751 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4752 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4753 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4754 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4755 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4756 "55" // 0x101
4757 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4758 "02820100" // INTEGER length 0x100 (privateExponent) value...
4759 "431447b6251908112b1ee76f99f3711a" // 0x10
4760 "52b6630960046c2de70de188d833f8b8" // 0x20
4761 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4762 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4763 "e710b630a03adc683b5d2c43080e52be" // 0x50
4764 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4765 "822bccff087d63c940ba8a45f670feb2" // 0x70
4766 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4767 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4768 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4769 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4770 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4771 "52659d5a5ba05b663737a8696281865b" // 0xd0
4772 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4773 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4774 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4775 "028181" // INTEGER length 0x81 (prime1) value...
4776 "00de392e18d682c829266cc3454e1d61" // 0x10
4777 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4778 "ff841be5bac82a164c5970007047b8c5" // 0x30
4779 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4780 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4781 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4782 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4783 "9e91346130748a6e3c124f9149d71c74" // 0x80
4784 "35"
4785 "028181" // INTEGER length 0x81 (prime2) value...
4786 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4787 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4788 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4789 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4790 "9ed39a2d934c880440aed8832f984316" // 0x50
4791 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4792 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4793 "b880677c068e1be936e81288815252a8" // 0x80
4794 "a1"
4795 "028180" // INTEGER length 0x80 (exponent1) value...
4796 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4797 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4798 "5a063212a4f105a3764743e53281988a" // 0x30
4799 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4800 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4801 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4802 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4803 "4719d6e2b9439823719cd08bcd031781" // 0x80
4804 "028181" // INTEGER length 0x81 (exponent2) value...
4805 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4806 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4807 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4808 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4809 "1254186af30b22c10582a8a43e34fe94" // 0x50
4810 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4811 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4812 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4813 "61"
4814 "028181" // INTEGER length 0x81 (coefficient) value...
4815 "00c931617c77829dfb1270502be9195c" // 0x10
4816 "8f2830885f57dba869536811e6864236" // 0x20
4817 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4818 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4819 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4820 "959356210723287b0affcc9f727044d4" // 0x60
4821 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4822 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4823 "22"
4824 // } SEQUENCE
4825 // } SEQUENCE ()
4826);
Selene Huang31ab4042020-04-29 04:22:39 -07004827
4828string zero_masking_key =
4829 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4830string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4831
4832class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4833
4834TEST_P(ImportWrappedKeyTest, Success) {
4835 auto wrapping_key_desc = AuthorizationSetBuilder()
4836 .RsaEncryptionKey(2048, 65537)
4837 .Digest(Digest::SHA_2_256)
4838 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004839 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4840 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004841
4842 ASSERT_EQ(ErrorCode::OK,
4843 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4844 AuthorizationSetBuilder()
4845 .Digest(Digest::SHA_2_256)
4846 .Padding(PaddingMode::RSA_OAEP)));
4847
4848 string message = "Hello World!";
4849 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4850 string ciphertext = EncryptMessage(message, params);
4851 string plaintext = DecryptMessage(ciphertext, params);
4852 EXPECT_EQ(message, plaintext);
4853}
4854
David Drysdaled2cc8c22021-04-15 13:29:45 +01004855/*
4856 * ImportWrappedKeyTest.SuccessSidsIgnored
4857 *
4858 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
4859 * include Tag:USER_SECURE_ID.
4860 */
4861TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
4862 auto wrapping_key_desc = AuthorizationSetBuilder()
4863 .RsaEncryptionKey(2048, 65537)
4864 .Digest(Digest::SHA_2_256)
4865 .Padding(PaddingMode::RSA_OAEP)
4866 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4867 .SetDefaultValidity();
4868
4869 int64_t password_sid = 42;
4870 int64_t biometric_sid = 24;
4871 ASSERT_EQ(ErrorCode::OK,
4872 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4873 AuthorizationSetBuilder()
4874 .Digest(Digest::SHA_2_256)
4875 .Padding(PaddingMode::RSA_OAEP),
4876 password_sid, biometric_sid));
4877
4878 string message = "Hello World!";
4879 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4880 string ciphertext = EncryptMessage(message, params);
4881 string plaintext = DecryptMessage(ciphertext, params);
4882 EXPECT_EQ(message, plaintext);
4883}
4884
Selene Huang31ab4042020-04-29 04:22:39 -07004885TEST_P(ImportWrappedKeyTest, SuccessMasked) {
4886 auto wrapping_key_desc = AuthorizationSetBuilder()
4887 .RsaEncryptionKey(2048, 65537)
4888 .Digest(Digest::SHA_2_256)
4889 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004890 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4891 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004892
4893 ASSERT_EQ(ErrorCode::OK,
4894 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
4895 AuthorizationSetBuilder()
4896 .Digest(Digest::SHA_2_256)
4897 .Padding(PaddingMode::RSA_OAEP)));
4898}
4899
4900TEST_P(ImportWrappedKeyTest, WrongMask) {
4901 auto wrapping_key_desc = AuthorizationSetBuilder()
4902 .RsaEncryptionKey(2048, 65537)
4903 .Digest(Digest::SHA_2_256)
4904 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004905 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4906 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004907
4908 ASSERT_EQ(
4909 ErrorCode::VERIFICATION_FAILED,
4910 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4911 AuthorizationSetBuilder()
4912 .Digest(Digest::SHA_2_256)
4913 .Padding(PaddingMode::RSA_OAEP)));
4914}
4915
4916TEST_P(ImportWrappedKeyTest, WrongPurpose) {
4917 auto wrapping_key_desc = AuthorizationSetBuilder()
4918 .RsaEncryptionKey(2048, 65537)
4919 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004920 .Padding(PaddingMode::RSA_OAEP)
4921 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004922
4923 ASSERT_EQ(
4924 ErrorCode::INCOMPATIBLE_PURPOSE,
4925 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4926 AuthorizationSetBuilder()
4927 .Digest(Digest::SHA_2_256)
4928 .Padding(PaddingMode::RSA_OAEP)));
4929}
4930
David Drysdaled2cc8c22021-04-15 13:29:45 +01004931TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
4932 auto wrapping_key_desc = AuthorizationSetBuilder()
4933 .RsaEncryptionKey(2048, 65537)
4934 .Digest(Digest::SHA_2_256)
4935 .Padding(PaddingMode::RSA_PSS)
4936 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4937 .SetDefaultValidity();
4938
4939 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
4940 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4941 AuthorizationSetBuilder()
4942 .Digest(Digest::SHA_2_256)
4943 .Padding(PaddingMode::RSA_OAEP)));
4944}
4945
4946TEST_P(ImportWrappedKeyTest, WrongDigest) {
4947 auto wrapping_key_desc = AuthorizationSetBuilder()
4948 .RsaEncryptionKey(2048, 65537)
4949 .Digest(Digest::SHA_2_512)
4950 .Padding(PaddingMode::RSA_OAEP)
4951 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4952 .SetDefaultValidity();
4953
4954 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
4955 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4956 AuthorizationSetBuilder()
4957 .Digest(Digest::SHA_2_256)
4958 .Padding(PaddingMode::RSA_OAEP)));
4959}
4960
Selene Huang31ab4042020-04-29 04:22:39 -07004961INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
4962
4963typedef KeyMintAidlTestBase EncryptionOperationsTest;
4964
4965/*
4966 * EncryptionOperationsTest.RsaNoPaddingSuccess
4967 *
David Drysdale59cae642021-05-12 13:52:03 +01004968 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07004969 */
4970TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00004971 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004972 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004973 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4974 .Authorization(TAG_NO_AUTH_REQUIRED)
4975 .RsaEncryptionKey(2048, exponent)
4976 .Padding(PaddingMode::NONE)
4977 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004978
David Drysdaled2cc8c22021-04-15 13:29:45 +01004979 string message = string(2048 / 8, 'a');
4980 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004981 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004982 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004983
David Drysdale59cae642021-05-12 13:52:03 +01004984 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004985 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004986
David Drysdaled2cc8c22021-04-15 13:29:45 +01004987 // Unpadded RSA is deterministic
4988 EXPECT_EQ(ciphertext1, ciphertext2);
4989
4990 CheckedDeleteKey();
4991 }
Selene Huang31ab4042020-04-29 04:22:39 -07004992}
4993
4994/*
4995 * EncryptionOperationsTest.RsaNoPaddingShortMessage
4996 *
David Drysdale59cae642021-05-12 13:52:03 +01004997 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07004998 */
4999TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5000 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5001 .Authorization(TAG_NO_AUTH_REQUIRED)
5002 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005003 .Padding(PaddingMode::NONE)
5004 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005005
5006 string message = "1";
5007 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5008
David Drysdale59cae642021-05-12 13:52:03 +01005009 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005010 EXPECT_EQ(2048U / 8, ciphertext.size());
5011
5012 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5013 string plaintext = DecryptMessage(ciphertext, params);
5014
5015 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005016}
5017
5018/*
Selene Huang31ab4042020-04-29 04:22:39 -07005019 * EncryptionOperationsTest.RsaOaepSuccess
5020 *
David Drysdale59cae642021-05-12 13:52:03 +01005021 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005022 */
5023TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5024 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5025
5026 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01005027 ASSERT_EQ(ErrorCode::OK,
5028 GenerateKey(AuthorizationSetBuilder()
5029 .Authorization(TAG_NO_AUTH_REQUIRED)
5030 .RsaEncryptionKey(key_size, 65537)
5031 .Padding(PaddingMode::RSA_OAEP)
5032 .Digest(digests)
5033 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
5034 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005035
5036 string message = "Hello";
5037
5038 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005039 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5040
5041 auto params = AuthorizationSetBuilder()
5042 .Digest(digest)
5043 .Padding(PaddingMode::RSA_OAEP)
5044 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5045 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005046 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5047 EXPECT_EQ(key_size / 8, ciphertext1.size());
5048
David Drysdale59cae642021-05-12 13:52:03 +01005049 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005050 EXPECT_EQ(key_size / 8, ciphertext2.size());
5051
5052 // OAEP randomizes padding so every result should be different (with astronomically high
5053 // probability).
5054 EXPECT_NE(ciphertext1, ciphertext2);
5055
5056 string plaintext1 = DecryptMessage(ciphertext1, params);
5057 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5058 string plaintext2 = DecryptMessage(ciphertext2, params);
5059 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5060
5061 // Decrypting corrupted ciphertext should fail.
5062 size_t offset_to_corrupt = random() % ciphertext1.size();
5063 char corrupt_byte;
5064 do {
5065 corrupt_byte = static_cast<char>(random() % 256);
5066 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5067 ciphertext1[offset_to_corrupt] = corrupt_byte;
5068
5069 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5070 string result;
5071 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5072 EXPECT_EQ(0U, result.size());
5073 }
5074}
5075
5076/*
5077 * EncryptionOperationsTest.RsaOaepInvalidDigest
5078 *
David Drysdale59cae642021-05-12 13:52:03 +01005079 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005080 * without a digest.
5081 */
5082TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5083 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5084 .Authorization(TAG_NO_AUTH_REQUIRED)
5085 .RsaEncryptionKey(2048, 65537)
5086 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005087 .Digest(Digest::NONE)
5088 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005089
5090 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005091 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005092}
5093
5094/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005095 * EncryptionOperationsTest.RsaOaepInvalidPadding
5096 *
David Drysdale59cae642021-05-12 13:52:03 +01005097 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005098 * with a padding value that is only suitable for signing/verifying.
5099 */
5100TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5101 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5102 .Authorization(TAG_NO_AUTH_REQUIRED)
5103 .RsaEncryptionKey(2048, 65537)
5104 .Padding(PaddingMode::RSA_PSS)
5105 .Digest(Digest::NONE)
5106 .SetDefaultValidity()));
5107
5108 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005109 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005110}
5111
5112/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005113 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005114 *
David Drysdale59cae642021-05-12 13:52:03 +01005115 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005116 * with a different digest than was used to encrypt.
5117 */
5118TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005119 if (SecLevel() == SecurityLevel::STRONGBOX) {
5120 GTEST_SKIP() << "Test not applicable to StrongBox device";
5121 }
Selene Huang31ab4042020-04-29 04:22:39 -07005122
5123 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5124 .Authorization(TAG_NO_AUTH_REQUIRED)
5125 .RsaEncryptionKey(1024, 65537)
5126 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005127 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5128 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005129 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005130 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005131 message,
5132 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5133
5134 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5135 .Digest(Digest::SHA_2_256)
5136 .Padding(PaddingMode::RSA_OAEP)));
5137 string result;
5138 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5139 EXPECT_EQ(0U, result.size());
5140}
5141
5142/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005143 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5144 *
David Drysdale59cae642021-05-12 13:52:03 +01005145 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005146 * digests.
5147 */
5148TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5149 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5150
5151 size_t key_size = 2048; // Need largish key for SHA-512 test.
5152 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5153 .OaepMGFDigest(digests)
5154 .Authorization(TAG_NO_AUTH_REQUIRED)
5155 .RsaEncryptionKey(key_size, 65537)
5156 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005157 .Digest(Digest::SHA_2_256)
5158 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005159
5160 string message = "Hello";
5161
5162 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005163 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005164 auto params = AuthorizationSetBuilder()
5165 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5166 .Digest(Digest::SHA_2_256)
5167 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005168 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005169 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5170 EXPECT_EQ(key_size / 8, ciphertext1.size());
5171
David Drysdale59cae642021-05-12 13:52:03 +01005172 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005173 EXPECT_EQ(key_size / 8, ciphertext2.size());
5174
5175 // OAEP randomizes padding so every result should be different (with astronomically high
5176 // probability).
5177 EXPECT_NE(ciphertext1, ciphertext2);
5178
5179 string plaintext1 = DecryptMessage(ciphertext1, params);
5180 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5181 string plaintext2 = DecryptMessage(ciphertext2, params);
5182 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5183
5184 // Decrypting corrupted ciphertext should fail.
5185 size_t offset_to_corrupt = random() % ciphertext1.size();
5186 char corrupt_byte;
5187 do {
5188 corrupt_byte = static_cast<char>(random() % 256);
5189 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5190 ciphertext1[offset_to_corrupt] = corrupt_byte;
5191
5192 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5193 string result;
5194 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5195 EXPECT_EQ(0U, result.size());
5196 }
5197}
5198
5199/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005200 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5201 *
5202 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5203 * specified, defaulting to SHA-1.
5204 */
5205TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5206 size_t key_size = 2048;
5207 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5208 .Authorization(TAG_NO_AUTH_REQUIRED)
5209 .RsaEncryptionKey(key_size, 65537)
5210 .Padding(PaddingMode::RSA_OAEP)
5211 .Digest(Digest::SHA_2_256)
5212 .SetDefaultValidity()));
5213
5214 // Do local RSA encryption using the default MGF digest of SHA-1.
5215 string message = "Hello";
5216 auto params =
5217 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5218 string ciphertext = LocalRsaEncryptMessage(message, params);
5219 EXPECT_EQ(key_size / 8, ciphertext.size());
5220
5221 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5222 string plaintext = DecryptMessage(ciphertext, params);
5223 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5224
5225 // Decrypting corrupted ciphertext should fail.
5226 size_t offset_to_corrupt = random() % ciphertext.size();
5227 char corrupt_byte;
5228 do {
5229 corrupt_byte = static_cast<char>(random() % 256);
5230 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5231 ciphertext[offset_to_corrupt] = corrupt_byte;
5232
5233 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5234 string result;
5235 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5236 EXPECT_EQ(0U, result.size());
5237}
5238
5239/*
5240 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5241 *
5242 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5243 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5244 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5245 */
5246TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5247 size_t key_size = 2048;
5248 ASSERT_EQ(ErrorCode::OK,
5249 GenerateKey(AuthorizationSetBuilder()
5250 .Authorization(TAG_NO_AUTH_REQUIRED)
5251 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5252 .RsaEncryptionKey(key_size, 65537)
5253 .Padding(PaddingMode::RSA_OAEP)
5254 .Digest(Digest::SHA_2_256)
5255 .SetDefaultValidity()));
5256
5257 // Do local RSA encryption using the default MGF digest of SHA-1.
5258 string message = "Hello";
5259 auto params =
5260 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5261 string ciphertext = LocalRsaEncryptMessage(message, params);
5262 EXPECT_EQ(key_size / 8, ciphertext.size());
5263
5264 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5265 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5266 // is checked against those values, and found absent.
5267 auto result = Begin(KeyPurpose::DECRYPT, params);
5268 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5269 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5270}
5271
5272/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005273 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5274 *
David Drysdale59cae642021-05-12 13:52:03 +01005275 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005276 * with incompatible MGF digest.
5277 */
5278TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5279 ASSERT_EQ(ErrorCode::OK,
5280 GenerateKey(AuthorizationSetBuilder()
5281 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5282 .Authorization(TAG_NO_AUTH_REQUIRED)
5283 .RsaEncryptionKey(2048, 65537)
5284 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005285 .Digest(Digest::SHA_2_256)
5286 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005287 string message = "Hello World!";
5288
5289 auto params = AuthorizationSetBuilder()
5290 .Padding(PaddingMode::RSA_OAEP)
5291 .Digest(Digest::SHA_2_256)
5292 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005293 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005294}
5295
5296/*
5297 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5298 *
5299 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5300 * with unsupported MGF digest.
5301 */
5302TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5303 ASSERT_EQ(ErrorCode::OK,
5304 GenerateKey(AuthorizationSetBuilder()
5305 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5306 .Authorization(TAG_NO_AUTH_REQUIRED)
5307 .RsaEncryptionKey(2048, 65537)
5308 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005309 .Digest(Digest::SHA_2_256)
5310 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005311 string message = "Hello World!";
5312
5313 auto params = AuthorizationSetBuilder()
5314 .Padding(PaddingMode::RSA_OAEP)
5315 .Digest(Digest::SHA_2_256)
5316 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005317 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005318}
5319
5320/*
Selene Huang31ab4042020-04-29 04:22:39 -07005321 * EncryptionOperationsTest.RsaPkcs1Success
5322 *
5323 * Verifies that RSA PKCS encryption/decrypts works.
5324 */
5325TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5326 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5327 .Authorization(TAG_NO_AUTH_REQUIRED)
5328 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005329 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5330 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005331
5332 string message = "Hello World!";
5333 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005334 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005335 EXPECT_EQ(2048U / 8, ciphertext1.size());
5336
David Drysdale59cae642021-05-12 13:52:03 +01005337 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005338 EXPECT_EQ(2048U / 8, ciphertext2.size());
5339
5340 // PKCS1 v1.5 randomizes padding so every result should be different.
5341 EXPECT_NE(ciphertext1, ciphertext2);
5342
5343 string plaintext = DecryptMessage(ciphertext1, params);
5344 EXPECT_EQ(message, plaintext);
5345
5346 // Decrypting corrupted ciphertext should fail.
5347 size_t offset_to_corrupt = random() % ciphertext1.size();
5348 char corrupt_byte;
5349 do {
5350 corrupt_byte = static_cast<char>(random() % 256);
5351 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5352 ciphertext1[offset_to_corrupt] = corrupt_byte;
5353
5354 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5355 string result;
5356 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5357 EXPECT_EQ(0U, result.size());
5358}
5359
5360/*
Selene Huang31ab4042020-04-29 04:22:39 -07005361 * EncryptionOperationsTest.EcdsaEncrypt
5362 *
5363 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5364 */
5365TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5366 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5367 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005368 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005369 .Digest(Digest::NONE)
5370 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005371 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5372 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5373 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5374}
5375
5376/*
5377 * EncryptionOperationsTest.HmacEncrypt
5378 *
5379 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5380 */
5381TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5382 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5383 .Authorization(TAG_NO_AUTH_REQUIRED)
5384 .HmacKey(128)
5385 .Digest(Digest::SHA_2_256)
5386 .Padding(PaddingMode::NONE)
5387 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5388 auto params = AuthorizationSetBuilder()
5389 .Digest(Digest::SHA_2_256)
5390 .Padding(PaddingMode::NONE)
5391 .Authorization(TAG_MAC_LENGTH, 128);
5392 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5393 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5394}
5395
5396/*
5397 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5398 *
5399 * Verifies that AES ECB mode works.
5400 */
5401TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5402 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5403 .Authorization(TAG_NO_AUTH_REQUIRED)
5404 .AesEncryptionKey(128)
5405 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5406 .Padding(PaddingMode::NONE)));
5407
5408 ASSERT_GT(key_blob_.size(), 0U);
5409 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5410
5411 // Two-block message.
5412 string message = "12345678901234567890123456789012";
5413 string ciphertext1 = EncryptMessage(message, params);
5414 EXPECT_EQ(message.size(), ciphertext1.size());
5415
5416 string ciphertext2 = EncryptMessage(string(message), params);
5417 EXPECT_EQ(message.size(), ciphertext2.size());
5418
5419 // ECB is deterministic.
5420 EXPECT_EQ(ciphertext1, ciphertext2);
5421
5422 string plaintext = DecryptMessage(ciphertext1, params);
5423 EXPECT_EQ(message, plaintext);
5424}
5425
5426/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005427 * EncryptionOperationsTest.AesEcbUnknownTag
5428 *
5429 * Verifies that AES ECB operations ignore unknown tags.
5430 */
5431TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5432 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5433 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5434 KeyParameter unknown_param;
5435 unknown_param.tag = unknown_tag;
5436
5437 vector<KeyCharacteristics> key_characteristics;
5438 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5439 .Authorization(TAG_NO_AUTH_REQUIRED)
5440 .AesEncryptionKey(128)
5441 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5442 .Padding(PaddingMode::NONE)
5443 .Authorization(unknown_param),
5444 &key_blob_, &key_characteristics));
5445 ASSERT_GT(key_blob_.size(), 0U);
5446
5447 // Unknown tags should not be returned in key characteristics.
5448 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5449 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5450 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5451 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5452
5453 // Encrypt without mentioning the unknown parameter.
5454 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5455 string message = "12345678901234567890123456789012";
5456 string ciphertext = EncryptMessage(message, params);
5457 EXPECT_EQ(message.size(), ciphertext.size());
5458
5459 // Decrypt including the unknown parameter.
5460 auto decrypt_params = AuthorizationSetBuilder()
5461 .BlockMode(BlockMode::ECB)
5462 .Padding(PaddingMode::NONE)
5463 .Authorization(unknown_param);
5464 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5465 EXPECT_EQ(message, plaintext);
5466}
5467
5468/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005469 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005470 *
5471 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5472 */
5473TEST_P(EncryptionOperationsTest, AesWrongMode) {
5474 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5475 .Authorization(TAG_NO_AUTH_REQUIRED)
5476 .AesEncryptionKey(128)
5477 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5478 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005479 ASSERT_GT(key_blob_.size(), 0U);
5480
Selene Huang31ab4042020-04-29 04:22:39 -07005481 EXPECT_EQ(
5482 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5483 Begin(KeyPurpose::ENCRYPT,
5484 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5485}
5486
5487/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005488 * EncryptionOperationsTest.AesWrongPadding
5489 *
5490 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5491 */
5492TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5493 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5494 .Authorization(TAG_NO_AUTH_REQUIRED)
5495 .AesEncryptionKey(128)
5496 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5497 .Padding(PaddingMode::NONE)));
5498 ASSERT_GT(key_blob_.size(), 0U);
5499
5500 EXPECT_EQ(
5501 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5502 Begin(KeyPurpose::ENCRYPT,
5503 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5504}
5505
5506/*
5507 * EncryptionOperationsTest.AesInvalidParams
5508 *
5509 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5510 */
5511TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5512 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5513 .Authorization(TAG_NO_AUTH_REQUIRED)
5514 .AesEncryptionKey(128)
5515 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5516 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5517 .Padding(PaddingMode::NONE)
5518 .Padding(PaddingMode::PKCS7)));
5519 ASSERT_GT(key_blob_.size(), 0U);
5520
5521 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5522 .BlockMode(BlockMode::CBC)
5523 .BlockMode(BlockMode::ECB)
5524 .Padding(PaddingMode::NONE));
5525 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5526 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5527
5528 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5529 .BlockMode(BlockMode::ECB)
5530 .Padding(PaddingMode::NONE)
5531 .Padding(PaddingMode::PKCS7));
5532 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5533 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5534}
5535
5536/*
Selene Huang31ab4042020-04-29 04:22:39 -07005537 * EncryptionOperationsTest.AesWrongPurpose
5538 *
5539 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5540 * specified.
5541 */
5542TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5543 auto err = GenerateKey(AuthorizationSetBuilder()
5544 .Authorization(TAG_NO_AUTH_REQUIRED)
5545 .AesKey(128)
5546 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5547 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5548 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5549 .Padding(PaddingMode::NONE));
5550 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5551 ASSERT_GT(key_blob_.size(), 0U);
5552
5553 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5554 .BlockMode(BlockMode::GCM)
5555 .Padding(PaddingMode::NONE)
5556 .Authorization(TAG_MAC_LENGTH, 128));
5557 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5558
5559 CheckedDeleteKey();
5560
5561 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5562 .Authorization(TAG_NO_AUTH_REQUIRED)
5563 .AesKey(128)
5564 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5565 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5566 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5567 .Padding(PaddingMode::NONE)));
5568
5569 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5570 .BlockMode(BlockMode::GCM)
5571 .Padding(PaddingMode::NONE)
5572 .Authorization(TAG_MAC_LENGTH, 128));
5573 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5574}
5575
5576/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005577 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005578 *
5579 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5580 * multiple of the block size and no padding is specified.
5581 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005582TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5583 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005584 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005585 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5586 .Authorization(TAG_NO_AUTH_REQUIRED)
5587 .AesEncryptionKey(128)
5588 .Authorization(TAG_BLOCK_MODE, blockMode)
5589 .Padding(PaddingMode::NONE)));
5590 // Message is slightly shorter than two blocks.
5591 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005592
David Drysdaled2cc8c22021-04-15 13:29:45 +01005593 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5594 AuthorizationSet out_params;
5595 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5596 string ciphertext;
5597 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5598 EXPECT_EQ(0U, ciphertext.size());
5599
5600 CheckedDeleteKey();
5601 }
Selene Huang31ab4042020-04-29 04:22:39 -07005602}
5603
5604/*
5605 * EncryptionOperationsTest.AesEcbPkcs7Padding
5606 *
5607 * Verifies that AES PKCS7 padding works for any message length.
5608 */
5609TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5610 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5611 .Authorization(TAG_NO_AUTH_REQUIRED)
5612 .AesEncryptionKey(128)
5613 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5614 .Padding(PaddingMode::PKCS7)));
5615
5616 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5617
5618 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005619 for (size_t i = 0; i <= 48; i++) {
5620 SCOPED_TRACE(testing::Message() << "i = " << i);
5621 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5622 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005623 string ciphertext = EncryptMessage(message, params);
5624 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5625 string plaintext = DecryptMessage(ciphertext, params);
5626 EXPECT_EQ(message, plaintext);
5627 }
5628}
5629
5630/*
5631 * EncryptionOperationsTest.AesEcbWrongPadding
5632 *
5633 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5634 * specified.
5635 */
5636TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5637 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5638 .Authorization(TAG_NO_AUTH_REQUIRED)
5639 .AesEncryptionKey(128)
5640 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5641 .Padding(PaddingMode::NONE)));
5642
5643 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5644
5645 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005646 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005647 string message(i, 'a');
5648 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5649 }
5650}
5651
5652/*
5653 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5654 *
5655 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5656 */
5657TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5658 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5659 .Authorization(TAG_NO_AUTH_REQUIRED)
5660 .AesEncryptionKey(128)
5661 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5662 .Padding(PaddingMode::PKCS7)));
5663
5664 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5665
5666 string message = "a";
5667 string ciphertext = EncryptMessage(message, params);
5668 EXPECT_EQ(16U, ciphertext.size());
5669 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005670
Seth Moore7a55ae32021-06-23 14:28:11 -07005671 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5672 ++ciphertext[ciphertext.size() / 2];
5673
5674 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5675 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005676 ErrorCode error = Finish(ciphertext, &plaintext);
5677 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005678 // This is the expected error, we can exit the test now.
5679 return;
5680 } else {
5681 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005682 ASSERT_EQ(error, ErrorCode::OK)
5683 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005684 }
5685 }
5686 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005687}
5688
David Drysdaleb8093292022-04-08 12:22:35 +01005689/*
5690 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5691 *
5692 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5693 */
5694TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5695 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5696 .Authorization(TAG_NO_AUTH_REQUIRED)
5697 .AesEncryptionKey(128)
5698 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5699 .Padding(PaddingMode::PKCS7)));
5700
5701 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5702
5703 string message = "a";
5704 string ciphertext = EncryptMessage(message, params);
5705 EXPECT_EQ(16U, ciphertext.size());
5706 EXPECT_NE(ciphertext, message);
5707
5708 // Shorten the ciphertext.
5709 ciphertext.resize(ciphertext.size() - 1);
5710 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5711 string plaintext;
5712 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5713}
5714
Selene Huang31ab4042020-04-29 04:22:39 -07005715vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5716 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005717 EXPECT_TRUE(iv);
5718 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005719}
5720
5721/*
5722 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5723 *
5724 * Verifies that AES CTR mode works.
5725 */
5726TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5727 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5728 .Authorization(TAG_NO_AUTH_REQUIRED)
5729 .AesEncryptionKey(128)
5730 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5731 .Padding(PaddingMode::NONE)));
5732
5733 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5734
5735 string message = "123";
5736 AuthorizationSet out_params;
5737 string ciphertext1 = EncryptMessage(message, params, &out_params);
5738 vector<uint8_t> iv1 = CopyIv(out_params);
5739 EXPECT_EQ(16U, iv1.size());
5740
5741 EXPECT_EQ(message.size(), ciphertext1.size());
5742
5743 out_params.Clear();
5744 string ciphertext2 = EncryptMessage(message, params, &out_params);
5745 vector<uint8_t> iv2 = CopyIv(out_params);
5746 EXPECT_EQ(16U, iv2.size());
5747
5748 // IVs should be random, so ciphertexts should differ.
5749 EXPECT_NE(ciphertext1, ciphertext2);
5750
5751 auto params_iv1 =
5752 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5753 auto params_iv2 =
5754 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5755
5756 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5757 EXPECT_EQ(message, plaintext);
5758 plaintext = DecryptMessage(ciphertext2, params_iv2);
5759 EXPECT_EQ(message, plaintext);
5760
5761 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5762 plaintext = DecryptMessage(ciphertext1, params_iv2);
5763 EXPECT_NE(message, plaintext);
5764 plaintext = DecryptMessage(ciphertext2, params_iv1);
5765 EXPECT_NE(message, plaintext);
5766}
5767
5768/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305769 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07005770 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305771 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07005772 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305773TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5774 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5775}
Selene Huang31ab4042020-04-29 04:22:39 -07005776
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305777/*
5778 * EncryptionOperationsTest.AesCbcIncremental
5779 *
5780 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5781 */
5782TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5783 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5784}
Selene Huang31ab4042020-04-29 04:22:39 -07005785
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305786/*
5787 * EncryptionOperationsTest.AesCtrIncremental
5788 *
5789 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5790 */
5791TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5792 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5793}
Selene Huang31ab4042020-04-29 04:22:39 -07005794
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305795/*
5796 * EncryptionOperationsTest.AesGcmIncremental
5797 *
5798 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5799 */
5800TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5801 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07005802}
5803
Prashant Patildd5f7f02022-07-06 18:58:07 +00005804/*
5805 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
5806 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5807 */
5808TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
5809 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
5810 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
5811 string kat_plaintext =
5812 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
5813 "809FFF37081C22EF278F896AB213A2A631");
5814 string kat_ciphertext =
5815 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
5816 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
5817 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5818 kat_ciphertext);
5819}
5820
5821/*
5822 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
5823 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5824 */
5825TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
5826 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
5827 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
5828 string kat_plaintext =
5829 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
5830 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
5831 string kat_ciphertext =
5832 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
5833 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
5834 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
5835 kat_plaintext, kat_ciphertext);
5836}
5837
5838/*
5839 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
5840 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
5841 */
5842TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
5843 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
5844 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
5845 string kat_plaintext =
5846 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
5847 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
5848 string kat_ciphertext =
5849 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
5850 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
5851 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
5852 kat_ciphertext);
5853}
5854
5855/*
5856 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
5857 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
5858 */
5859TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
5860 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
5861 string kat_plaintext =
5862 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
5863 "7B6168A9A27BCE554BEA94EF26E6C742A0");
5864 string kat_ciphertext =
5865 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
5866 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
5867 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
5868 kat_ciphertext);
5869}
5870
5871/*
5872 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
5873 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
5874 */
5875TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
5876 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
5877 string kat_plaintext =
5878 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
5879 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
5880 string kat_ciphertext =
5881 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
5882 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
5883 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
5884 kat_ciphertext);
5885}
5886
5887/*
5888 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
5889 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
5890 */
5891TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
5892 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
5893 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
5894 string kat_plaintext =
5895 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
5896 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
5897 string kat_ciphertext =
5898 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
5899 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
5900 "bdfcc0cba0");
5901
5902 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
5903 kat_ciphertext);
5904}
5905
5906/*
5907 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
5908 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5909 */
5910TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
5911 if (SecLevel() == SecurityLevel::STRONGBOX) {
5912 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5913 }
5914 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
5915 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
5916 string kat_plaintext =
5917 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
5918 "167f2497c994bd496eb80bfb2ba2c9d5af");
5919 string kat_ciphertext =
5920 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
5921 "72c134552f3a138e726fbe493b3a839598");
5922 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5923 kat_ciphertext);
5924}
5925
5926/*
5927 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
5928 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5929 */
5930TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
5931 if (SecLevel() == SecurityLevel::STRONGBOX) {
5932 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5933 }
5934 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
5935 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
5936 string kat_plaintext =
5937 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
5938 "b170");
5939 string kat_ciphertext =
5940 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
5941 "4e3884138ff403a41fd99818708ada301c");
5942 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
5943 kat_plaintext, kat_ciphertext);
5944}
5945
5946/*
5947 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
5948 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
5949 */
5950TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
5951 if (SecLevel() == SecurityLevel::STRONGBOX) {
5952 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5953 }
5954 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
5955 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
5956 string kat_plaintext =
5957 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
5958 "28091e09cdbbd3b42b");
5959 string kat_ciphertext =
5960 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
5961 "2ae0f90f0c19f42b4a");
5962 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
5963 kat_ciphertext);
5964}
5965
5966/*
5967 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
5968 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
5969 */
5970TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
5971 if (SecLevel() == SecurityLevel::STRONGBOX) {
5972 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5973 }
5974 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
5975 string kat_plaintext =
5976 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
5977 "44ab");
5978 string kat_ciphertext =
5979 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
5980 "2453");
5981 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
5982 kat_ciphertext);
5983}
5984
5985/*
5986 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
5987 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
5988 */
5989TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
5990 if (SecLevel() == SecurityLevel::STRONGBOX) {
5991 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5992 }
5993 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
5994 string kat_plaintext =
5995 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
5996 "e2c7");
5997 string kat_ciphertext =
5998 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
5999 "bb7e3a889dd4a9589098b44acf1056e7aa");
6000 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6001 kat_ciphertext);
6002}
6003
6004/*
6005 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6006 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6007 */
6008TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6009 if (SecLevel() == SecurityLevel::STRONGBOX) {
6010 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6011 }
6012 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6013 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6014 string kat_plaintext =
6015 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6016 "ff52");
6017 string kat_ciphertext =
6018 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6019 "1413ad70fb0e1970669095ad77ebb5974ae8");
6020
6021 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6022 kat_ciphertext);
6023}
6024
6025/*
6026 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6027 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6028 */
6029TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6030 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6031 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6032 string kat_plaintext =
6033 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6034 "494cb53caca353e4b637ba05687be20f8d");
6035 string kat_ciphertext =
6036 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6037 "6047da1e4fd7c4e1cf2656097f75ae8685");
6038 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6039 kat_ciphertext);
6040}
6041
6042/*
6043 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6044 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6045 */
6046TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6047 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6048 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6049 string kat_plaintext =
6050 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6051 "2545a82b73c48078b9dae62261c65909");
6052 string kat_ciphertext =
6053 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6054 "9403a71987b95124073d69f2a3cb95b0ab");
6055 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6056 kat_plaintext, kat_ciphertext);
6057}
6058
6059/*
6060 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6061 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6062 */
6063TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6064 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6065 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6066 string kat_plaintext =
6067 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6068 "1f6db3c884");
6069 string kat_ciphertext =
6070 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6071 "a7be30d4c3");
6072 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6073 kat_ciphertext);
6074}
6075
6076/*
6077 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6078 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6079 */
6080TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6081 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6082 string kat_plaintext =
6083 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6084 "31a476d6806b8116089c6ec50bb543200f");
6085 string kat_ciphertext =
6086 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6087 "c83e377faf246288931136bef2a07c0be4");
6088 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6089 kat_ciphertext);
6090}
6091
6092/*
6093 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6094 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6095 */
6096TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6097 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6098 string kat_plaintext =
6099 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6100 "6f");
6101 string kat_ciphertext =
6102 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6103 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6104 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6105 kat_ciphertext);
6106}
6107
6108/*
6109 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6110 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6111 */
6112TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6113 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6114 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6115 string kat_plaintext =
6116 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6117 "f0");
6118 string kat_ciphertext =
6119 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6120 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6121
6122 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6123 kat_ciphertext);
6124}
6125
Selene Huang31ab4042020-04-29 04:22:39 -07006126struct AesCtrSp80038aTestVector {
6127 const char* key;
6128 const char* nonce;
6129 const char* plaintext;
6130 const char* ciphertext;
6131};
6132
6133// These test vectors are taken from
6134// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6135static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6136 // AES-128
6137 {
6138 "2b7e151628aed2a6abf7158809cf4f3c",
6139 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6140 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6141 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6142 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6143 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6144 },
6145 // AES-192
6146 {
6147 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6148 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6149 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6150 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6151 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6152 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6153 },
6154 // AES-256
6155 {
6156 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6157 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6158 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6159 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6160 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6161 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6162 },
6163};
6164
6165/*
6166 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6167 *
6168 * Verifies AES CTR implementation against SP800-38A test vectors.
6169 */
6170TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6171 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6172 for (size_t i = 0; i < 3; i++) {
6173 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6174 const string key = hex2str(test.key);
6175 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6176 InvalidSizes.end())
6177 continue;
6178 const string nonce = hex2str(test.nonce);
6179 const string plaintext = hex2str(test.plaintext);
6180 const string ciphertext = hex2str(test.ciphertext);
6181 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6182 }
6183}
6184
6185/*
6186 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6187 *
6188 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6189 */
6190TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6191 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6192 .Authorization(TAG_NO_AUTH_REQUIRED)
6193 .AesEncryptionKey(128)
6194 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6195 .Padding(PaddingMode::PKCS7)));
6196 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6197 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6198}
6199
6200/*
6201 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6202 *
6203 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6204 */
6205TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6206 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6207 .Authorization(TAG_NO_AUTH_REQUIRED)
6208 .AesEncryptionKey(128)
6209 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6210 .Authorization(TAG_CALLER_NONCE)
6211 .Padding(PaddingMode::NONE)));
6212
6213 auto params = AuthorizationSetBuilder()
6214 .BlockMode(BlockMode::CTR)
6215 .Padding(PaddingMode::NONE)
6216 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6217 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6218
6219 params = AuthorizationSetBuilder()
6220 .BlockMode(BlockMode::CTR)
6221 .Padding(PaddingMode::NONE)
6222 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6223 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6224
6225 params = AuthorizationSetBuilder()
6226 .BlockMode(BlockMode::CTR)
6227 .Padding(PaddingMode::NONE)
6228 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6229 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6230}
6231
6232/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006233 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006234 *
6235 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6236 */
6237TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6238 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6239 .Authorization(TAG_NO_AUTH_REQUIRED)
6240 .AesEncryptionKey(128)
6241 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6242 .Padding(PaddingMode::NONE)));
6243 // Two-block message.
6244 string message = "12345678901234567890123456789012";
6245 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6246 AuthorizationSet out_params;
6247 string ciphertext1 = EncryptMessage(message, params, &out_params);
6248 vector<uint8_t> iv1 = CopyIv(out_params);
6249 EXPECT_EQ(message.size(), ciphertext1.size());
6250
6251 out_params.Clear();
6252
6253 string ciphertext2 = EncryptMessage(message, params, &out_params);
6254 vector<uint8_t> iv2 = CopyIv(out_params);
6255 EXPECT_EQ(message.size(), ciphertext2.size());
6256
6257 // IVs should be random, so ciphertexts should differ.
6258 EXPECT_NE(ciphertext1, ciphertext2);
6259
6260 params.push_back(TAG_NONCE, iv1);
6261 string plaintext = DecryptMessage(ciphertext1, params);
6262 EXPECT_EQ(message, plaintext);
6263}
6264
6265/*
Tommy Chiuee705692021-09-23 20:09:13 +08006266 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6267 *
6268 * Verifies that keymaster generates correct output on zero-input with
6269 * NonePadding mode
6270 */
6271TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6272 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6273 .Authorization(TAG_NO_AUTH_REQUIRED)
6274 .AesEncryptionKey(128)
6275 .BlockMode(BlockMode::CBC)
6276 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6277
6278 // Zero input message
6279 string message = "";
6280 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006281 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006282 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6283 AuthorizationSet out_params;
6284 string ciphertext1 = EncryptMessage(message, params, &out_params);
6285 vector<uint8_t> iv1 = CopyIv(out_params);
6286 if (padding == PaddingMode::NONE)
6287 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6288 else
6289 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6290
6291 out_params.Clear();
6292
6293 string ciphertext2 = EncryptMessage(message, params, &out_params);
6294 vector<uint8_t> iv2 = CopyIv(out_params);
6295 if (padding == PaddingMode::NONE)
6296 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6297 else
6298 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6299
6300 // IVs should be random
6301 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6302
6303 params.push_back(TAG_NONCE, iv1);
6304 string plaintext = DecryptMessage(ciphertext1, params);
6305 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6306 }
6307}
6308
6309/*
Selene Huang31ab4042020-04-29 04:22:39 -07006310 * EncryptionOperationsTest.AesCallerNonce
6311 *
6312 * Verifies that AES caller-provided nonces work correctly.
6313 */
6314TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6315 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6316 .Authorization(TAG_NO_AUTH_REQUIRED)
6317 .AesEncryptionKey(128)
6318 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6319 .Authorization(TAG_CALLER_NONCE)
6320 .Padding(PaddingMode::NONE)));
6321
6322 string message = "12345678901234567890123456789012";
6323
6324 // Don't specify nonce, should get a random one.
6325 AuthorizationSetBuilder params =
6326 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6327 AuthorizationSet out_params;
6328 string ciphertext = EncryptMessage(message, params, &out_params);
6329 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006330 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006331
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006332 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006333 string plaintext = DecryptMessage(ciphertext, params);
6334 EXPECT_EQ(message, plaintext);
6335
6336 // Now specify a nonce, should also work.
6337 params = AuthorizationSetBuilder()
6338 .BlockMode(BlockMode::CBC)
6339 .Padding(PaddingMode::NONE)
6340 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6341 out_params.Clear();
6342 ciphertext = EncryptMessage(message, params, &out_params);
6343
6344 // Decrypt with correct nonce.
6345 plaintext = DecryptMessage(ciphertext, params);
6346 EXPECT_EQ(message, plaintext);
6347
6348 // Try with wrong nonce.
6349 params = AuthorizationSetBuilder()
6350 .BlockMode(BlockMode::CBC)
6351 .Padding(PaddingMode::NONE)
6352 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6353 plaintext = DecryptMessage(ciphertext, params);
6354 EXPECT_NE(message, plaintext);
6355}
6356
6357/*
6358 * EncryptionOperationsTest.AesCallerNonceProhibited
6359 *
6360 * Verifies that caller-provided nonces are not permitted when not specified in the key
6361 * authorizations.
6362 */
6363TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6364 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6365 .Authorization(TAG_NO_AUTH_REQUIRED)
6366 .AesEncryptionKey(128)
6367 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6368 .Padding(PaddingMode::NONE)));
6369
6370 string message = "12345678901234567890123456789012";
6371
6372 // Don't specify nonce, should get a random one.
6373 AuthorizationSetBuilder params =
6374 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6375 AuthorizationSet out_params;
6376 string ciphertext = EncryptMessage(message, params, &out_params);
6377 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006378 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006379
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006380 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006381 string plaintext = DecryptMessage(ciphertext, params);
6382 EXPECT_EQ(message, plaintext);
6383
6384 // Now specify a nonce, should fail
6385 params = AuthorizationSetBuilder()
6386 .BlockMode(BlockMode::CBC)
6387 .Padding(PaddingMode::NONE)
6388 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6389 out_params.Clear();
6390 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6391}
6392
6393/*
6394 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6395 *
6396 * Verifies that AES GCM mode works.
6397 */
6398TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6399 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6400 .Authorization(TAG_NO_AUTH_REQUIRED)
6401 .AesEncryptionKey(128)
6402 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6403 .Padding(PaddingMode::NONE)
6404 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6405
6406 string aad = "foobar";
6407 string message = "123456789012345678901234567890123456";
6408
6409 auto begin_params = AuthorizationSetBuilder()
6410 .BlockMode(BlockMode::GCM)
6411 .Padding(PaddingMode::NONE)
6412 .Authorization(TAG_MAC_LENGTH, 128);
6413
Selene Huang31ab4042020-04-29 04:22:39 -07006414 // Encrypt
6415 AuthorizationSet begin_out_params;
6416 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6417 << "Begin encrypt";
6418 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006419 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6420 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006421 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6422
6423 // Grab nonce
6424 begin_params.push_back(begin_out_params);
6425
6426 // Decrypt.
6427 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006428 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006429 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006430 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006431 EXPECT_EQ(message.length(), plaintext.length());
6432 EXPECT_EQ(message, plaintext);
6433}
6434
6435/*
6436 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6437 *
6438 * Verifies that AES GCM mode works, even when there's a long delay
6439 * between operations.
6440 */
6441TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6442 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6443 .Authorization(TAG_NO_AUTH_REQUIRED)
6444 .AesEncryptionKey(128)
6445 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6446 .Padding(PaddingMode::NONE)
6447 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6448
6449 string aad = "foobar";
6450 string message = "123456789012345678901234567890123456";
6451
6452 auto begin_params = AuthorizationSetBuilder()
6453 .BlockMode(BlockMode::GCM)
6454 .Padding(PaddingMode::NONE)
6455 .Authorization(TAG_MAC_LENGTH, 128);
6456
Selene Huang31ab4042020-04-29 04:22:39 -07006457 // Encrypt
6458 AuthorizationSet begin_out_params;
6459 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6460 << "Begin encrypt";
6461 string ciphertext;
6462 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006463 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006464 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006465 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006466
6467 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6468
6469 // Grab nonce
6470 begin_params.push_back(begin_out_params);
6471
6472 // Decrypt.
6473 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6474 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006475 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006476 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006477 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006478 sleep(5);
6479 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6480 EXPECT_EQ(message.length(), plaintext.length());
6481 EXPECT_EQ(message, plaintext);
6482}
6483
6484/*
6485 * EncryptionOperationsTest.AesGcmDifferentNonces
6486 *
6487 * Verifies that encrypting the same data with different nonces produces different outputs.
6488 */
6489TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6490 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6491 .Authorization(TAG_NO_AUTH_REQUIRED)
6492 .AesEncryptionKey(128)
6493 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6494 .Padding(PaddingMode::NONE)
6495 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6496 .Authorization(TAG_CALLER_NONCE)));
6497
6498 string aad = "foobar";
6499 string message = "123456789012345678901234567890123456";
6500 string nonce1 = "000000000000";
6501 string nonce2 = "111111111111";
6502 string nonce3 = "222222222222";
6503
6504 string ciphertext1 =
6505 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6506 string ciphertext2 =
6507 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6508 string ciphertext3 =
6509 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6510
6511 ASSERT_NE(ciphertext1, ciphertext2);
6512 ASSERT_NE(ciphertext1, ciphertext3);
6513 ASSERT_NE(ciphertext2, ciphertext3);
6514}
6515
6516/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006517 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6518 *
6519 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6520 */
6521TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6522 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6523 .Authorization(TAG_NO_AUTH_REQUIRED)
6524 .AesEncryptionKey(128)
6525 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6526 .Padding(PaddingMode::NONE)
6527 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6528
6529 string aad = "foobar";
6530 string message = "123456789012345678901234567890123456";
6531
6532 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6533 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6534 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6535
6536 ASSERT_NE(ciphertext1, ciphertext2);
6537 ASSERT_NE(ciphertext1, ciphertext3);
6538 ASSERT_NE(ciphertext2, ciphertext3);
6539}
6540
6541/*
Selene Huang31ab4042020-04-29 04:22:39 -07006542 * EncryptionOperationsTest.AesGcmTooShortTag
6543 *
6544 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6545 */
6546TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6547 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6548 .Authorization(TAG_NO_AUTH_REQUIRED)
6549 .AesEncryptionKey(128)
6550 .BlockMode(BlockMode::GCM)
6551 .Padding(PaddingMode::NONE)
6552 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6553 string message = "123456789012345678901234567890123456";
6554 auto params = AuthorizationSetBuilder()
6555 .BlockMode(BlockMode::GCM)
6556 .Padding(PaddingMode::NONE)
6557 .Authorization(TAG_MAC_LENGTH, 96);
6558
6559 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6560}
6561
6562/*
6563 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6564 *
6565 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6566 */
6567TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6568 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6569 .Authorization(TAG_NO_AUTH_REQUIRED)
6570 .AesEncryptionKey(128)
6571 .BlockMode(BlockMode::GCM)
6572 .Padding(PaddingMode::NONE)
6573 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6574 string aad = "foobar";
6575 string message = "123456789012345678901234567890123456";
6576 auto params = AuthorizationSetBuilder()
6577 .BlockMode(BlockMode::GCM)
6578 .Padding(PaddingMode::NONE)
6579 .Authorization(TAG_MAC_LENGTH, 128);
6580
Selene Huang31ab4042020-04-29 04:22:39 -07006581 // Encrypt
6582 AuthorizationSet begin_out_params;
6583 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6584 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006585 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006586
6587 AuthorizationSet finish_out_params;
6588 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006589 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6590 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006591
6592 params = AuthorizationSetBuilder()
6593 .Authorizations(begin_out_params)
6594 .BlockMode(BlockMode::GCM)
6595 .Padding(PaddingMode::NONE)
6596 .Authorization(TAG_MAC_LENGTH, 96);
6597
6598 // Decrypt.
6599 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6600}
6601
6602/*
6603 * EncryptionOperationsTest.AesGcmCorruptKey
6604 *
6605 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6606 */
6607TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6608 const uint8_t nonce_bytes[] = {
6609 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6610 };
6611 string nonce = make_string(nonce_bytes);
6612 const uint8_t ciphertext_bytes[] = {
6613 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6614 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6615 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6616 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6617 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6618 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6619 };
6620 string ciphertext = make_string(ciphertext_bytes);
6621
6622 auto params = AuthorizationSetBuilder()
6623 .BlockMode(BlockMode::GCM)
6624 .Padding(PaddingMode::NONE)
6625 .Authorization(TAG_MAC_LENGTH, 128)
6626 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6627
6628 auto import_params = AuthorizationSetBuilder()
6629 .Authorization(TAG_NO_AUTH_REQUIRED)
6630 .AesEncryptionKey(128)
6631 .BlockMode(BlockMode::GCM)
6632 .Padding(PaddingMode::NONE)
6633 .Authorization(TAG_CALLER_NONCE)
6634 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6635
6636 // Import correct key and decrypt
6637 const uint8_t key_bytes[] = {
6638 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6639 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6640 };
6641 string key = make_string(key_bytes);
6642 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6643 string plaintext = DecryptMessage(ciphertext, params);
6644 CheckedDeleteKey();
6645
6646 // Corrupt key and attempt to decrypt
6647 key[0] = 0;
6648 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6649 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6650 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6651 CheckedDeleteKey();
6652}
6653
6654/*
6655 * EncryptionOperationsTest.AesGcmAadNoData
6656 *
6657 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6658 * encrypt.
6659 */
6660TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6661 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6662 .Authorization(TAG_NO_AUTH_REQUIRED)
6663 .AesEncryptionKey(128)
6664 .BlockMode(BlockMode::GCM)
6665 .Padding(PaddingMode::NONE)
6666 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6667
6668 string aad = "1234567890123456";
6669 auto params = AuthorizationSetBuilder()
6670 .BlockMode(BlockMode::GCM)
6671 .Padding(PaddingMode::NONE)
6672 .Authorization(TAG_MAC_LENGTH, 128);
6673
Selene Huang31ab4042020-04-29 04:22:39 -07006674 // Encrypt
6675 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006676 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006677 string ciphertext;
6678 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006679 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6680 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006681 EXPECT_TRUE(finish_out_params.empty());
6682
6683 // Grab nonce
6684 params.push_back(begin_out_params);
6685
6686 // Decrypt.
6687 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006688 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006689 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006690 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006691
6692 EXPECT_TRUE(finish_out_params.empty());
6693
6694 EXPECT_EQ("", plaintext);
6695}
6696
6697/*
6698 * EncryptionOperationsTest.AesGcmMultiPartAad
6699 *
6700 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6701 * chunks.
6702 */
6703TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6704 const size_t tag_bits = 128;
6705 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6706 .Authorization(TAG_NO_AUTH_REQUIRED)
6707 .AesEncryptionKey(128)
6708 .BlockMode(BlockMode::GCM)
6709 .Padding(PaddingMode::NONE)
6710 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6711
6712 string message = "123456789012345678901234567890123456";
6713 auto begin_params = AuthorizationSetBuilder()
6714 .BlockMode(BlockMode::GCM)
6715 .Padding(PaddingMode::NONE)
6716 .Authorization(TAG_MAC_LENGTH, tag_bits);
6717 AuthorizationSet begin_out_params;
6718
David Drysdale7fc26b92022-05-13 09:54:24 +01006719 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006720
6721 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006722 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6723 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006724 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006725 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6726 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006727
Selene Huang31ab4042020-04-29 04:22:39 -07006728 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006729 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006730
6731 // Grab nonce.
6732 begin_params.push_back(begin_out_params);
6733
6734 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01006735 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006736 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006737 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006738 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006739 EXPECT_EQ(message, plaintext);
6740}
6741
6742/*
6743 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6744 *
6745 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6746 */
6747TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6748 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6749 .Authorization(TAG_NO_AUTH_REQUIRED)
6750 .AesEncryptionKey(128)
6751 .BlockMode(BlockMode::GCM)
6752 .Padding(PaddingMode::NONE)
6753 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6754
6755 string message = "123456789012345678901234567890123456";
6756 auto begin_params = AuthorizationSetBuilder()
6757 .BlockMode(BlockMode::GCM)
6758 .Padding(PaddingMode::NONE)
6759 .Authorization(TAG_MAC_LENGTH, 128);
6760 AuthorizationSet begin_out_params;
6761
David Drysdale7fc26b92022-05-13 09:54:24 +01006762 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006763
Shawn Willden92d79c02021-02-19 07:31:55 -07006764 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006765 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006766 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6767 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006768
David Drysdaled2cc8c22021-04-15 13:29:45 +01006769 // The failure should have already cancelled the operation.
6770 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6771
Shawn Willden92d79c02021-02-19 07:31:55 -07006772 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006773}
6774
6775/*
6776 * EncryptionOperationsTest.AesGcmBadAad
6777 *
6778 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6779 */
6780TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6781 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6782 .Authorization(TAG_NO_AUTH_REQUIRED)
6783 .AesEncryptionKey(128)
6784 .BlockMode(BlockMode::GCM)
6785 .Padding(PaddingMode::NONE)
6786 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6787
6788 string message = "12345678901234567890123456789012";
6789 auto begin_params = AuthorizationSetBuilder()
6790 .BlockMode(BlockMode::GCM)
6791 .Padding(PaddingMode::NONE)
6792 .Authorization(TAG_MAC_LENGTH, 128);
6793
Selene Huang31ab4042020-04-29 04:22:39 -07006794 // Encrypt
6795 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006796 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006797 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006798 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006799 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006800
6801 // Grab nonce
6802 begin_params.push_back(begin_out_params);
6803
Selene Huang31ab4042020-04-29 04:22:39 -07006804 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006805 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006806 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006807 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006808 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006809}
6810
6811/*
6812 * EncryptionOperationsTest.AesGcmWrongNonce
6813 *
6814 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6815 */
6816TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6817 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6818 .Authorization(TAG_NO_AUTH_REQUIRED)
6819 .AesEncryptionKey(128)
6820 .BlockMode(BlockMode::GCM)
6821 .Padding(PaddingMode::NONE)
6822 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6823
6824 string message = "12345678901234567890123456789012";
6825 auto begin_params = AuthorizationSetBuilder()
6826 .BlockMode(BlockMode::GCM)
6827 .Padding(PaddingMode::NONE)
6828 .Authorization(TAG_MAC_LENGTH, 128);
6829
Selene Huang31ab4042020-04-29 04:22:39 -07006830 // Encrypt
6831 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006832 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006833 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006834 string ciphertext;
6835 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006836 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006837
6838 // Wrong nonce
6839 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6840
6841 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006842 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006843 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006844 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006845 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006846
6847 // With wrong nonce, should have gotten garbage plaintext (or none).
6848 EXPECT_NE(message, plaintext);
6849}
6850
6851/*
6852 * EncryptionOperationsTest.AesGcmCorruptTag
6853 *
6854 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6855 */
6856TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6857 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6858 .Authorization(TAG_NO_AUTH_REQUIRED)
6859 .AesEncryptionKey(128)
6860 .BlockMode(BlockMode::GCM)
6861 .Padding(PaddingMode::NONE)
6862 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6863
6864 string aad = "1234567890123456";
6865 string message = "123456789012345678901234567890123456";
6866
6867 auto params = AuthorizationSetBuilder()
6868 .BlockMode(BlockMode::GCM)
6869 .Padding(PaddingMode::NONE)
6870 .Authorization(TAG_MAC_LENGTH, 128);
6871
Selene Huang31ab4042020-04-29 04:22:39 -07006872 // Encrypt
6873 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006874 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006875 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006876 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006877 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006878
6879 // Corrupt tag
6880 ++(*ciphertext.rbegin());
6881
6882 // Grab nonce
6883 params.push_back(begin_out_params);
6884
6885 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006886 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006887 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006888 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006889 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006890}
6891
6892/*
6893 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
6894 *
6895 * Verifies that 3DES is basically functional.
6896 */
6897TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
6898 auto auths = AuthorizationSetBuilder()
6899 .TripleDesEncryptionKey(168)
6900 .BlockMode(BlockMode::ECB)
6901 .Authorization(TAG_NO_AUTH_REQUIRED)
6902 .Padding(PaddingMode::NONE);
6903
6904 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
6905 // Two-block message.
6906 string message = "1234567890123456";
6907 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6908 string ciphertext1 = EncryptMessage(message, inParams);
6909 EXPECT_EQ(message.size(), ciphertext1.size());
6910
6911 string ciphertext2 = EncryptMessage(string(message), inParams);
6912 EXPECT_EQ(message.size(), ciphertext2.size());
6913
6914 // ECB is deterministic.
6915 EXPECT_EQ(ciphertext1, ciphertext2);
6916
6917 string plaintext = DecryptMessage(ciphertext1, inParams);
6918 EXPECT_EQ(message, plaintext);
6919}
6920
6921/*
6922 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
6923 *
6924 * Verifies that CBC keys reject ECB usage.
6925 */
6926TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
6927 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6928 .TripleDesEncryptionKey(168)
6929 .BlockMode(BlockMode::CBC)
6930 .Authorization(TAG_NO_AUTH_REQUIRED)
6931 .Padding(PaddingMode::NONE)));
6932
6933 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6934 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
6935}
6936
6937/*
6938 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
6939 *
6940 * Tests ECB mode with PKCS#7 padding, various message sizes.
6941 */
6942TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
6943 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6944 .TripleDesEncryptionKey(168)
6945 .BlockMode(BlockMode::ECB)
6946 .Authorization(TAG_NO_AUTH_REQUIRED)
6947 .Padding(PaddingMode::PKCS7)));
6948
6949 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006950 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07006951 string message(i, 'a');
6952 auto inParams =
6953 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6954 string ciphertext = EncryptMessage(message, inParams);
6955 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6956 string plaintext = DecryptMessage(ciphertext, inParams);
6957 EXPECT_EQ(message, plaintext);
6958 }
6959}
6960
6961/*
6962 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
6963 *
6964 * Verifies that keys configured for no padding reject PKCS7 padding
6965 */
6966TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
6967 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6968 .TripleDesEncryptionKey(168)
6969 .BlockMode(BlockMode::ECB)
6970 .Authorization(TAG_NO_AUTH_REQUIRED)
6971 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00006972 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6973 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07006974}
6975
6976/*
6977 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
6978 *
6979 * Verifies that corrupted padding is detected.
6980 */
6981TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
6982 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6983 .TripleDesEncryptionKey(168)
6984 .BlockMode(BlockMode::ECB)
6985 .Authorization(TAG_NO_AUTH_REQUIRED)
6986 .Padding(PaddingMode::PKCS7)));
6987
6988 string message = "a";
6989 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
6990 EXPECT_EQ(8U, ciphertext.size());
6991 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006992
6993 AuthorizationSetBuilder begin_params;
6994 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
6995 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07006996
6997 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
6998 ++ciphertext[ciphertext.size() / 2];
6999
David Drysdale7fc26b92022-05-13 09:54:24 +01007000 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007001 string plaintext;
7002 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7003 ErrorCode error = Finish(&plaintext);
7004 if (error == ErrorCode::INVALID_ARGUMENT) {
7005 // This is the expected error, we can exit the test now.
7006 return;
7007 } else {
7008 // Very small chance we got valid decryption, so try again.
7009 ASSERT_EQ(error, ErrorCode::OK);
7010 }
7011 }
7012 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007013}
7014
7015struct TripleDesTestVector {
7016 const char* name;
7017 const KeyPurpose purpose;
7018 const BlockMode block_mode;
7019 const PaddingMode padding_mode;
7020 const char* key;
7021 const char* iv;
7022 const char* input;
7023 const char* output;
7024};
7025
7026// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7027// of the NIST vectors are multiples of the block size.
7028static const TripleDesTestVector kTripleDesTestVectors[] = {
7029 {
7030 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7031 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7032 "", // IV
7033 "329d86bdf1bc5af4", // input
7034 "d946c2756d78633f", // output
7035 },
7036 {
7037 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7038 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7039 "", // IV
7040 "6b1540781b01ce1997adae102dbf3c5b", // input
7041 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7042 },
7043 {
7044 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7045 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7046 "", // IV
7047 "6daad94ce08acfe7", // input
7048 "660e7d32dcc90e79", // output
7049 },
7050 {
7051 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7052 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7053 "", // IV
7054 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7055 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7056 },
7057 {
7058 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7059 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7060 "43f791134c5647ba", // IV
7061 "dcc153cef81d6f24", // input
7062 "92538bd8af18d3ba", // output
7063 },
7064 {
7065 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7066 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7067 "c2e999cb6249023c", // IV
7068 "c689aee38a301bb316da75db36f110b5", // input
7069 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7070 },
7071 {
7072 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7073 PaddingMode::PKCS7,
7074 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7075 "c2e999cb6249023c", // IV
7076 "c689aee38a301bb316da75db36f110b500", // input
7077 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7078 },
7079 {
7080 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7081 PaddingMode::PKCS7,
7082 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7083 "c2e999cb6249023c", // IV
7084 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7085 "c689aee38a301bb316da75db36f110b500", // output
7086 },
7087 {
7088 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7089 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7090 "41746c7e442d3681", // IV
7091 "c53a7b0ec40600fe", // input
7092 "d4f00eb455de1034", // output
7093 },
7094 {
7095 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7096 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7097 "3982bc02c3727d45", // IV
7098 "6006f10adef52991fcc777a1238bbb65", // input
7099 "edae09288e9e3bc05746d872b48e3b29", // output
7100 },
7101};
7102
7103/*
7104 * EncryptionOperationsTest.TripleDesTestVector
7105 *
7106 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7107 */
7108TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7109 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7110 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7111 SCOPED_TRACE(test->name);
7112 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7113 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7114 hex2str(test->output));
7115 }
7116}
7117
7118/*
7119 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7120 *
7121 * Validates CBC mode functionality.
7122 */
7123TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7124 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7125 .TripleDesEncryptionKey(168)
7126 .BlockMode(BlockMode::CBC)
7127 .Authorization(TAG_NO_AUTH_REQUIRED)
7128 .Padding(PaddingMode::NONE)));
7129
7130 ASSERT_GT(key_blob_.size(), 0U);
7131
Brian J Murray734c8412022-01-13 14:55:30 -08007132 // Four-block message.
7133 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007134 vector<uint8_t> iv1;
7135 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7136 EXPECT_EQ(message.size(), ciphertext1.size());
7137
7138 vector<uint8_t> iv2;
7139 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7140 EXPECT_EQ(message.size(), ciphertext2.size());
7141
7142 // IVs should be random, so ciphertexts should differ.
7143 EXPECT_NE(iv1, iv2);
7144 EXPECT_NE(ciphertext1, ciphertext2);
7145
7146 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7147 EXPECT_EQ(message, plaintext);
7148}
7149
7150/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007151 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7152 *
7153 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7154 */
7155TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7156 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7157 .TripleDesEncryptionKey(168)
7158 .BlockMode(BlockMode::CBC)
7159 .Authorization(TAG_NO_AUTH_REQUIRED)
7160 .Authorization(TAG_CALLER_NONCE)
7161 .Padding(PaddingMode::NONE)));
7162 auto params = AuthorizationSetBuilder()
7163 .BlockMode(BlockMode::CBC)
7164 .Padding(PaddingMode::NONE)
7165 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7166 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7167}
7168
7169/*
Selene Huang31ab4042020-04-29 04:22:39 -07007170 * EncryptionOperationsTest.TripleDesCallerIv
7171 *
7172 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7173 */
7174TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7175 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7176 .TripleDesEncryptionKey(168)
7177 .BlockMode(BlockMode::CBC)
7178 .Authorization(TAG_NO_AUTH_REQUIRED)
7179 .Authorization(TAG_CALLER_NONCE)
7180 .Padding(PaddingMode::NONE)));
7181 string message = "1234567890123456";
7182 vector<uint8_t> iv;
7183 // Don't specify IV, should get a random one.
7184 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7185 EXPECT_EQ(message.size(), ciphertext1.size());
7186 EXPECT_EQ(8U, iv.size());
7187
7188 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7189 EXPECT_EQ(message, plaintext);
7190
7191 // Now specify an IV, should also work.
7192 iv = AidlBuf("abcdefgh");
7193 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7194
7195 // Decrypt with correct IV.
7196 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7197 EXPECT_EQ(message, plaintext);
7198
7199 // Now try with wrong IV.
7200 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7201 EXPECT_NE(message, plaintext);
7202}
7203
7204/*
7205 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7206 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007207 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007208 */
7209TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7210 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7211 .TripleDesEncryptionKey(168)
7212 .BlockMode(BlockMode::CBC)
7213 .Authorization(TAG_NO_AUTH_REQUIRED)
7214 .Padding(PaddingMode::NONE)));
7215
7216 string message = "12345678901234567890123456789012";
7217 vector<uint8_t> iv;
7218 // Don't specify nonce, should get a random one.
7219 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7220 EXPECT_EQ(message.size(), ciphertext1.size());
7221 EXPECT_EQ(8U, iv.size());
7222
7223 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7224 EXPECT_EQ(message, plaintext);
7225
7226 // Now specify a nonce, should fail.
7227 auto input_params = AuthorizationSetBuilder()
7228 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7229 .BlockMode(BlockMode::CBC)
7230 .Padding(PaddingMode::NONE);
7231 AuthorizationSet output_params;
7232 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7233 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7234}
7235
7236/*
7237 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7238 *
7239 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7240 */
7241TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7242 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7243 .TripleDesEncryptionKey(168)
7244 .BlockMode(BlockMode::ECB)
7245 .Authorization(TAG_NO_AUTH_REQUIRED)
7246 .Padding(PaddingMode::NONE)));
7247 // Two-block message.
7248 string message = "1234567890123456";
7249 auto begin_params =
7250 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7251 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7252}
7253
7254/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007255 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007256 *
7257 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7258 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007259TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7260 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007261 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007262 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7263 .TripleDesEncryptionKey(168)
7264 .BlockMode(blockMode)
7265 .Authorization(TAG_NO_AUTH_REQUIRED)
7266 .Padding(PaddingMode::NONE)));
7267 // Message is slightly shorter than two blocks.
7268 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007269
David Drysdaled2cc8c22021-04-15 13:29:45 +01007270 auto begin_params =
7271 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7272 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007273 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007274 string ciphertext;
7275 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7276
7277 CheckedDeleteKey();
7278 }
Selene Huang31ab4042020-04-29 04:22:39 -07007279}
7280
7281/*
7282 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7283 *
7284 * Verifies that PKCS7 padding works correctly in CBC mode.
7285 */
7286TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7287 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7288 .TripleDesEncryptionKey(168)
7289 .BlockMode(BlockMode::CBC)
7290 .Authorization(TAG_NO_AUTH_REQUIRED)
7291 .Padding(PaddingMode::PKCS7)));
7292
7293 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007294 for (size_t i = 0; i <= 32; i++) {
7295 SCOPED_TRACE(testing::Message() << "i = " << i);
7296 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7297 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007298 vector<uint8_t> iv;
7299 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7300 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7301 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7302 EXPECT_EQ(message, plaintext);
7303 }
7304}
7305
7306/*
7307 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7308 *
7309 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7310 */
7311TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7312 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7313 .TripleDesEncryptionKey(168)
7314 .BlockMode(BlockMode::CBC)
7315 .Authorization(TAG_NO_AUTH_REQUIRED)
7316 .Padding(PaddingMode::NONE)));
7317
7318 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007319 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007320 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007321 auto begin_params =
7322 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7323 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7324 }
7325}
7326
7327/*
7328 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7329 *
7330 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7331 */
7332TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7333 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7334 .TripleDesEncryptionKey(168)
7335 .BlockMode(BlockMode::CBC)
7336 .Authorization(TAG_NO_AUTH_REQUIRED)
7337 .Padding(PaddingMode::PKCS7)));
7338
7339 string message = "a";
7340 vector<uint8_t> iv;
7341 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7342 EXPECT_EQ(8U, ciphertext.size());
7343 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007344
7345 auto begin_params = AuthorizationSetBuilder()
7346 .BlockMode(BlockMode::CBC)
7347 .Padding(PaddingMode::PKCS7)
7348 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007349
7350 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007351 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007352 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007353 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007354 string plaintext;
7355 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7356 ErrorCode error = Finish(&plaintext);
7357 if (error == ErrorCode::INVALID_ARGUMENT) {
7358 // This is the expected error, we can exit the test now.
7359 return;
7360 } else {
7361 // Very small chance we got valid decryption, so try again.
7362 ASSERT_EQ(error, ErrorCode::OK);
7363 }
7364 }
7365 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007366}
7367
7368/*
7369 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7370 *
7371 * Verifies that 3DES CBC works with many different input sizes.
7372 */
7373TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7374 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7375 .TripleDesEncryptionKey(168)
7376 .BlockMode(BlockMode::CBC)
7377 .Authorization(TAG_NO_AUTH_REQUIRED)
7378 .Padding(PaddingMode::NONE)));
7379
7380 int increment = 7;
7381 string message(240, 'a');
7382 AuthorizationSet input_params =
7383 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7384 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007385 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007386
7387 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007388 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007389 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007390 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7391 EXPECT_EQ(message.size(), ciphertext.size());
7392
7393 // Move TAG_NONCE into input_params
7394 input_params = output_params;
7395 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7396 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7397 output_params.Clear();
7398
David Drysdale7fc26b92022-05-13 09:54:24 +01007399 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007400 string plaintext;
7401 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007402 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007403 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7404 EXPECT_EQ(ciphertext.size(), plaintext.size());
7405 EXPECT_EQ(message, plaintext);
7406}
7407
7408INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7409
7410typedef KeyMintAidlTestBase MaxOperationsTest;
7411
7412/*
7413 * MaxOperationsTest.TestLimitAes
7414 *
7415 * Verifies that the max uses per boot tag works correctly with AES keys.
7416 */
7417TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007418 if (SecLevel() == SecurityLevel::STRONGBOX) {
7419 GTEST_SKIP() << "Test not applicable to StrongBox device";
7420 }
Selene Huang31ab4042020-04-29 04:22:39 -07007421
7422 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7423 .Authorization(TAG_NO_AUTH_REQUIRED)
7424 .AesEncryptionKey(128)
7425 .EcbMode()
7426 .Padding(PaddingMode::NONE)
7427 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7428
7429 string message = "1234567890123456";
7430
7431 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7432
7433 EncryptMessage(message, params);
7434 EncryptMessage(message, params);
7435 EncryptMessage(message, params);
7436
7437 // Fourth time should fail.
7438 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7439}
7440
7441/*
Qi Wud22ec842020-11-26 13:27:53 +08007442 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007443 *
7444 * Verifies that the max uses per boot tag works correctly with RSA keys.
7445 */
7446TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007447 if (SecLevel() == SecurityLevel::STRONGBOX) {
7448 GTEST_SKIP() << "Test not applicable to StrongBox device";
7449 }
Selene Huang31ab4042020-04-29 04:22:39 -07007450
7451 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7452 .Authorization(TAG_NO_AUTH_REQUIRED)
7453 .RsaSigningKey(1024, 65537)
7454 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007455 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7456 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007457
7458 string message = "1234567890123456";
7459
7460 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7461
7462 SignMessage(message, params);
7463 SignMessage(message, params);
7464 SignMessage(message, params);
7465
7466 // Fourth time should fail.
7467 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7468}
7469
7470INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7471
Qi Wud22ec842020-11-26 13:27:53 +08007472typedef KeyMintAidlTestBase UsageCountLimitTest;
7473
7474/*
Qi Wubeefae42021-01-28 23:16:37 +08007475 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007476 *
Qi Wubeefae42021-01-28 23:16:37 +08007477 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007478 */
Qi Wubeefae42021-01-28 23:16:37 +08007479TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007480 if (SecLevel() == SecurityLevel::STRONGBOX) {
7481 GTEST_SKIP() << "Test not applicable to StrongBox device";
7482 }
Qi Wud22ec842020-11-26 13:27:53 +08007483
7484 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7485 .Authorization(TAG_NO_AUTH_REQUIRED)
7486 .AesEncryptionKey(128)
7487 .EcbMode()
7488 .Padding(PaddingMode::NONE)
7489 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7490
7491 // Check the usage count limit tag appears in the authorizations.
7492 AuthorizationSet auths;
7493 for (auto& entry : key_characteristics_) {
7494 auths.push_back(AuthorizationSet(entry.authorizations));
7495 }
7496 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7497 << "key usage count limit " << 1U << " missing";
7498
7499 string message = "1234567890123456";
7500 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7501
Qi Wubeefae42021-01-28 23:16:37 +08007502 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7503 AuthorizationSet keystore_auths =
7504 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7505
Qi Wud22ec842020-11-26 13:27:53 +08007506 // First usage of AES key should work.
7507 EncryptMessage(message, params);
7508
Qi Wud22ec842020-11-26 13:27:53 +08007509 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7510 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7511 // must be invalidated from secure storage (such as RPMB partition).
7512 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7513 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007514 // Usage count limit tag is enforced by keystore, keymint does nothing.
7515 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007516 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007517 }
7518}
7519
7520/*
Qi Wubeefae42021-01-28 23:16:37 +08007521 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007522 *
Qi Wubeefae42021-01-28 23:16:37 +08007523 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007524 */
Qi Wubeefae42021-01-28 23:16:37 +08007525TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007526 if (SecLevel() == SecurityLevel::STRONGBOX) {
7527 GTEST_SKIP() << "Test not applicable to StrongBox device";
7528 }
Qi Wubeefae42021-01-28 23:16:37 +08007529
7530 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7531 .Authorization(TAG_NO_AUTH_REQUIRED)
7532 .AesEncryptionKey(128)
7533 .EcbMode()
7534 .Padding(PaddingMode::NONE)
7535 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7536
7537 // Check the usage count limit tag appears in the authorizations.
7538 AuthorizationSet auths;
7539 for (auto& entry : key_characteristics_) {
7540 auths.push_back(AuthorizationSet(entry.authorizations));
7541 }
7542 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7543 << "key usage count limit " << 3U << " missing";
7544
7545 string message = "1234567890123456";
7546 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7547
7548 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7549 AuthorizationSet keystore_auths =
7550 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7551
7552 EncryptMessage(message, params);
7553 EncryptMessage(message, params);
7554 EncryptMessage(message, params);
7555
7556 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7557 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7558 // must be invalidated from secure storage (such as RPMB partition).
7559 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7560 } else {
7561 // Usage count limit tag is enforced by keystore, keymint does nothing.
7562 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007563 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007564 }
7565}
7566
7567/*
7568 * UsageCountLimitTest.TestSingleUseRsa
7569 *
7570 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7571 */
7572TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007573 if (SecLevel() == SecurityLevel::STRONGBOX) {
7574 GTEST_SKIP() << "Test not applicable to StrongBox device";
7575 }
Qi Wud22ec842020-11-26 13:27:53 +08007576
7577 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7578 .Authorization(TAG_NO_AUTH_REQUIRED)
7579 .RsaSigningKey(1024, 65537)
7580 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007581 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7582 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007583
7584 // Check the usage count limit tag appears in the authorizations.
7585 AuthorizationSet auths;
7586 for (auto& entry : key_characteristics_) {
7587 auths.push_back(AuthorizationSet(entry.authorizations));
7588 }
7589 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7590 << "key usage count limit " << 1U << " missing";
7591
7592 string message = "1234567890123456";
7593 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7594
Qi Wubeefae42021-01-28 23:16:37 +08007595 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7596 AuthorizationSet keystore_auths =
7597 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7598
Qi Wud22ec842020-11-26 13:27:53 +08007599 // First usage of RSA key should work.
7600 SignMessage(message, params);
7601
Qi Wud22ec842020-11-26 13:27:53 +08007602 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
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));
7606 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007607 // Usage count limit tag is enforced by keystore, keymint does nothing.
7608 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007609 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007610 }
7611}
7612
7613/*
7614 * UsageCountLimitTest.TestLimitUseRsa
7615 *
7616 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7617 */
7618TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007619 if (SecLevel() == SecurityLevel::STRONGBOX) {
7620 GTEST_SKIP() << "Test not applicable to StrongBox device";
7621 }
Qi Wubeefae42021-01-28 23:16:37 +08007622
7623 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7624 .Authorization(TAG_NO_AUTH_REQUIRED)
7625 .RsaSigningKey(1024, 65537)
7626 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007627 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7628 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007629
7630 // Check the usage count limit tag appears in the authorizations.
7631 AuthorizationSet auths;
7632 for (auto& entry : key_characteristics_) {
7633 auths.push_back(AuthorizationSet(entry.authorizations));
7634 }
7635 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7636 << "key usage count limit " << 3U << " missing";
7637
7638 string message = "1234567890123456";
7639 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7640
7641 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7642 AuthorizationSet keystore_auths =
7643 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7644
7645 SignMessage(message, params);
7646 SignMessage(message, params);
7647 SignMessage(message, params);
7648
7649 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7650 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7651 // must be invalidated from secure storage (such as RPMB partition).
7652 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7653 } else {
7654 // Usage count limit tag is enforced by keystore, keymint does nothing.
7655 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007656 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007657 }
7658}
7659
Qi Wu8e727f72021-02-11 02:49:33 +08007660/*
7661 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7662 *
7663 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7664 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7665 * in hardware.
7666 */
7667TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01007668 if (SecLevel() == SecurityLevel::STRONGBOX) {
7669 GTEST_SKIP() << "Test not applicable to StrongBox device";
7670 }
Qi Wu8e727f72021-02-11 02:49:33 +08007671
7672 auto error = GenerateKey(AuthorizationSetBuilder()
7673 .RsaSigningKey(2048, 65537)
7674 .Digest(Digest::NONE)
7675 .Padding(PaddingMode::NONE)
7676 .Authorization(TAG_NO_AUTH_REQUIRED)
7677 .Authorization(TAG_ROLLBACK_RESISTANCE)
7678 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007679 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7680 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007681 }
David Drysdale513bf122021-10-06 11:53:13 +01007682
7683 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7684 ASSERT_EQ(ErrorCode::OK, error);
7685 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7686 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7687 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7688
7689 // The KeyMint should also enforce single use key in hardware when it supports rollback
7690 // resistance.
7691 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7692 .Authorization(TAG_NO_AUTH_REQUIRED)
7693 .RsaSigningKey(1024, 65537)
7694 .NoDigestOrPadding()
7695 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7696 .SetDefaultValidity()));
7697
7698 // Check the usage count limit tag appears in the hardware authorizations.
7699 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7700 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7701 << "key usage count limit " << 1U << " missing";
7702
7703 string message = "1234567890123456";
7704 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7705
7706 // First usage of RSA key should work.
7707 SignMessage(message, params);
7708
7709 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7710 // must be invalidated from secure storage (such as RPMB partition).
7711 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007712}
7713
Qi Wud22ec842020-11-26 13:27:53 +08007714INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7715
David Drysdale7de9feb2021-03-05 14:56:19 +00007716typedef KeyMintAidlTestBase GetHardwareInfoTest;
7717
7718TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7719 // Retrieving hardware info should give the same result each time.
7720 KeyMintHardwareInfo info;
7721 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7722 KeyMintHardwareInfo info2;
7723 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7724 EXPECT_EQ(info, info2);
7725}
7726
7727INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7728
Selene Huang31ab4042020-04-29 04:22:39 -07007729typedef KeyMintAidlTestBase AddEntropyTest;
7730
7731/*
7732 * AddEntropyTest.AddEntropy
7733 *
7734 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7735 * is actually added.
7736 */
7737TEST_P(AddEntropyTest, AddEntropy) {
7738 string data = "foo";
7739 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7740}
7741
7742/*
7743 * AddEntropyTest.AddEmptyEntropy
7744 *
7745 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7746 */
7747TEST_P(AddEntropyTest, AddEmptyEntropy) {
7748 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7749}
7750
7751/*
7752 * AddEntropyTest.AddLargeEntropy
7753 *
7754 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7755 */
7756TEST_P(AddEntropyTest, AddLargeEntropy) {
7757 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7758}
7759
David Drysdalebb3d85e2021-04-13 11:15:51 +01007760/*
7761 * AddEntropyTest.AddTooLargeEntropy
7762 *
7763 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7764 */
7765TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7766 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7767 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7768}
7769
Selene Huang31ab4042020-04-29 04:22:39 -07007770INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7771
Selene Huang31ab4042020-04-29 04:22:39 -07007772typedef KeyMintAidlTestBase KeyDeletionTest;
7773
7774/**
7775 * KeyDeletionTest.DeleteKey
7776 *
7777 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7778 * valid key blob.
7779 */
7780TEST_P(KeyDeletionTest, DeleteKey) {
7781 auto error = GenerateKey(AuthorizationSetBuilder()
7782 .RsaSigningKey(2048, 65537)
7783 .Digest(Digest::NONE)
7784 .Padding(PaddingMode::NONE)
7785 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007786 .Authorization(TAG_ROLLBACK_RESISTANCE)
7787 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007788 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7789 GTEST_SKIP() << "Rollback resistance not supported";
7790 }
Selene Huang31ab4042020-04-29 04:22:39 -07007791
7792 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007793 ASSERT_EQ(ErrorCode::OK, error);
7794 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7795 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007796
David Drysdale513bf122021-10-06 11:53:13 +01007797 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007798
David Drysdale513bf122021-10-06 11:53:13 +01007799 string message = "12345678901234567890123456789012";
7800 AuthorizationSet begin_out_params;
7801 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7802 Begin(KeyPurpose::SIGN, key_blob_,
7803 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7804 &begin_out_params));
7805 AbortIfNeeded();
7806 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007807}
7808
7809/**
7810 * KeyDeletionTest.DeleteInvalidKey
7811 *
7812 * This test checks that the HAL excepts invalid key blobs..
7813 */
7814TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7815 // Generate key just to check if rollback protection is implemented
7816 auto error = GenerateKey(AuthorizationSetBuilder()
7817 .RsaSigningKey(2048, 65537)
7818 .Digest(Digest::NONE)
7819 .Padding(PaddingMode::NONE)
7820 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007821 .Authorization(TAG_ROLLBACK_RESISTANCE)
7822 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007823 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7824 GTEST_SKIP() << "Rollback resistance not supported";
7825 }
Selene Huang31ab4042020-04-29 04:22:39 -07007826
7827 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007828 ASSERT_EQ(ErrorCode::OK, error);
7829 AuthorizationSet enforced(SecLevelAuthorizations());
7830 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007831
David Drysdale513bf122021-10-06 11:53:13 +01007832 // Delete the key we don't care about the result at this point.
7833 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007834
David Drysdale513bf122021-10-06 11:53:13 +01007835 // Now create an invalid key blob and delete it.
7836 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007837
David Drysdale513bf122021-10-06 11:53:13 +01007838 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007839}
7840
7841/**
7842 * KeyDeletionTest.DeleteAllKeys
7843 *
7844 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7845 *
7846 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7847 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7848 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7849 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7850 * credentials stored in Keystore/Keymint.
7851 */
7852TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007853 if (!arm_deleteAllKeys) {
7854 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7855 return;
7856 }
Selene Huang31ab4042020-04-29 04:22:39 -07007857 auto error = GenerateKey(AuthorizationSetBuilder()
7858 .RsaSigningKey(2048, 65537)
7859 .Digest(Digest::NONE)
7860 .Padding(PaddingMode::NONE)
7861 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007862 .Authorization(TAG_ROLLBACK_RESISTANCE)
7863 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007864 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7865 GTEST_SKIP() << "Rollback resistance not supported";
7866 }
Selene Huang31ab4042020-04-29 04:22:39 -07007867
7868 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007869 ASSERT_EQ(ErrorCode::OK, error);
7870 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7871 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007872
David Drysdale513bf122021-10-06 11:53:13 +01007873 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007874
David Drysdale513bf122021-10-06 11:53:13 +01007875 string message = "12345678901234567890123456789012";
7876 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07007877
David Drysdale513bf122021-10-06 11:53:13 +01007878 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7879 Begin(KeyPurpose::SIGN, key_blob_,
7880 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7881 &begin_out_params));
7882 AbortIfNeeded();
7883 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007884}
7885
7886INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
7887
David Drysdaled2cc8c22021-04-15 13:29:45 +01007888typedef KeyMintAidlTestBase KeyUpgradeTest;
7889
7890/**
7891 * KeyUpgradeTest.UpgradeInvalidKey
7892 *
7893 * This test checks that the HAL excepts invalid key blobs..
7894 */
7895TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
7896 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
7897
7898 std::vector<uint8_t> new_blob;
7899 Status result = keymint_->upgradeKey(key_blob,
7900 AuthorizationSetBuilder()
7901 .Authorization(TAG_APPLICATION_ID, "clientid")
7902 .Authorization(TAG_APPLICATION_DATA, "appdata")
7903 .vector_data(),
7904 &new_blob);
7905 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
7906}
7907
7908INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
7909
Selene Huang31ab4042020-04-29 04:22:39 -07007910using UpgradeKeyTest = KeyMintAidlTestBase;
7911
7912/*
7913 * UpgradeKeyTest.UpgradeKey
7914 *
7915 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
7916 */
7917TEST_P(UpgradeKeyTest, UpgradeKey) {
7918 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7919 .AesEncryptionKey(128)
7920 .Padding(PaddingMode::NONE)
7921 .Authorization(TAG_NO_AUTH_REQUIRED)));
7922
7923 auto result = UpgradeKey(key_blob_);
7924
7925 // Key doesn't need upgrading. Should get okay, but no new key blob.
7926 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
7927}
7928
7929INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
7930
7931using ClearOperationsTest = KeyMintAidlTestBase;
7932
7933/*
7934 * ClearSlotsTest.TooManyOperations
7935 *
7936 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
7937 * operations are started without being finished or aborted. Also verifies
7938 * that aborting the operations clears the operations.
7939 *
7940 */
7941TEST_P(ClearOperationsTest, TooManyOperations) {
7942 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7943 .Authorization(TAG_NO_AUTH_REQUIRED)
7944 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08007945 .Padding(PaddingMode::NONE)
7946 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007947
7948 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
7949 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08007950 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07007951 AuthorizationSet out_params;
7952 ErrorCode result;
7953 size_t i;
7954
7955 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00007956 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07007957 if (ErrorCode::OK != result) {
7958 break;
7959 }
7960 }
7961 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
7962 // Try again just in case there's a weird overflow bug
7963 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00007964 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007965 for (size_t j = 0; j < i; j++) {
7966 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
7967 << "Aboort failed for i = " << j << std::endl;
7968 }
David Drysdale7fc26b92022-05-13 09:54:24 +01007969 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007970 AbortIfNeeded();
7971}
7972
7973INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
7974
7975typedef KeyMintAidlTestBase TransportLimitTest;
7976
7977/*
David Drysdale7de9feb2021-03-05 14:56:19 +00007978 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07007979 *
7980 * Verifies that passing input data to finish succeeds as expected.
7981 */
7982TEST_P(TransportLimitTest, LargeFinishInput) {
7983 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7984 .Authorization(TAG_NO_AUTH_REQUIRED)
7985 .AesEncryptionKey(128)
7986 .BlockMode(BlockMode::ECB)
7987 .Padding(PaddingMode::NONE)));
7988
7989 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007990 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07007991 auto cipher_params =
7992 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7993
7994 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007995 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007996
7997 string plain_message = std::string(1 << msg_size, 'x');
7998 string encrypted_message;
7999 auto rc = Finish(plain_message, &encrypted_message);
8000
8001 EXPECT_EQ(ErrorCode::OK, rc);
8002 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8003 << "Encrypt finish returned OK, but did not consume all of the given input";
8004 cipher_params.push_back(out_params);
8005
David Drysdale7fc26b92022-05-13 09:54:24 +01008006 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008007
8008 string decrypted_message;
8009 rc = Finish(encrypted_message, &decrypted_message);
8010 EXPECT_EQ(ErrorCode::OK, rc);
8011 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8012 << "Decrypt finish returned OK, did not consume all of the given input";
8013 }
8014}
8015
8016INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8017
Seth Moored79a0ec2021-12-13 20:03:33 +00008018static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008019 switch (curve) {
8020 case EcCurve::P_224:
8021 return NID_secp224r1;
8022 case EcCurve::P_256:
8023 return NID_X9_62_prime256v1;
8024 case EcCurve::P_384:
8025 return NID_secp384r1;
8026 case EcCurve::P_521:
8027 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008028 case EcCurve::CURVE_25519:
8029 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008030 }
8031}
8032
David Drysdale42fe1892021-10-14 14:43:46 +01008033class KeyAgreementTest : public KeyMintAidlTestBase {
8034 protected:
8035 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8036 std::vector<uint8_t>* localPublicKey) {
8037 // Generate EC key locally (with access to private key material)
8038 if (localCurve == EcCurve::CURVE_25519) {
8039 uint8_t privKeyData[32];
8040 uint8_t pubKeyData[32];
8041 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008042 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8043 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8044 } else {
8045 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8046 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8047 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8048 ASSERT_NE(group, nullptr);
8049 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8050 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8051 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8052 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008053 }
David Drysdalea410b772022-05-09 16:44:13 +01008054
8055 // Get encoded form of the public part of the locally generated key...
8056 unsigned char* p = nullptr;
8057 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8058 ASSERT_GT(localPublicKeySize, 0);
8059 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8060 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8061 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008062 }
8063
8064 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8065 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008066 auto builder = AuthorizationSetBuilder()
8067 .Authorization(TAG_NO_AUTH_REQUIRED)
8068 .Authorization(TAG_EC_CURVE, curve)
8069 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8070 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8071 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8072 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8073 .SetDefaultValidity();
8074 ErrorCode result = GenerateKey(builder);
8075
8076 if (SecLevel() == SecurityLevel::STRONGBOX) {
8077 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8078 result = GenerateKeyWithSelfSignedAttestKey(
8079 AuthorizationSetBuilder()
8080 .EcdsaKey(EcCurve::P_256)
8081 .AttestKey()
8082 .SetDefaultValidity(), /* attest key params */
8083 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8084 }
8085 }
David Drysdale42fe1892021-10-14 14:43:46 +01008086 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8087 ASSERT_GT(cert_chain_.size(), 0);
8088 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8089 ASSERT_NE(kmKeyCert, nullptr);
8090 // Check that keyAgreement (bit 4) is set in KeyUsage
8091 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8092 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8093 ASSERT_NE(*kmPubKey, nullptr);
8094 if (dump_Attestations) {
8095 for (size_t n = 0; n < cert_chain_.size(); n++) {
8096 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8097 }
8098 }
8099 }
8100
8101 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8102 const std::vector<uint8_t>& localPublicKey) {
8103 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8104 string ZabFromKeyMintStr;
8105 ASSERT_EQ(ErrorCode::OK,
8106 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8107 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8108 vector<uint8_t> ZabFromTest;
8109
8110 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8111 size_t kmPubKeySize = 32;
8112 uint8_t kmPubKeyData[32];
8113 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8114 ASSERT_EQ(kmPubKeySize, 32);
8115
8116 uint8_t localPrivKeyData[32];
8117 size_t localPrivKeySize = 32;
8118 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8119 &localPrivKeySize));
8120 ASSERT_EQ(localPrivKeySize, 32);
8121
8122 uint8_t sharedKey[32];
8123 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8124 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8125 } else {
8126 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8127 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8128 ASSERT_NE(ctx, nullptr);
8129 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8130 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8131 size_t ZabFromTestLen = 0;
8132 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8133 ZabFromTest.resize(ZabFromTestLen);
8134 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8135 }
8136 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8137 }
8138};
8139
David Zeuthene0c40892021-01-08 12:54:11 -05008140/*
8141 * KeyAgreementTest.Ecdh
8142 *
David Drysdale42fe1892021-10-14 14:43:46 +01008143 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008144 */
8145TEST_P(KeyAgreementTest, Ecdh) {
8146 // Because it's possible to use this API with keys on different curves, we
8147 // check all N^2 combinations where N is the number of supported
8148 // curves.
8149 //
8150 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8151 // lot more curves we can be smart about things and just pick |otherCurve| so
8152 // it's not |curve| and that way we end up with only 2*N runs
8153 //
8154 for (auto curve : ValidCurves()) {
8155 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008156 SCOPED_TRACE(testing::Message()
8157 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8158
David Zeuthene0c40892021-01-08 12:54:11 -05008159 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008160 EVP_PKEY_Ptr localPrivKey;
8161 vector<uint8_t> localPublicKey;
8162 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008163
8164 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008165 EVP_PKEY_Ptr kmPubKey;
8166 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008167
8168 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8169 if (curve != localCurve) {
8170 // If the keys are using different curves KeyMint should fail with
8171 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008172 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008173 string ZabFromKeyMintStr;
8174 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008175 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008176 &ZabFromKeyMintStr));
8177
8178 } else {
8179 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008180 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008181 }
8182
8183 CheckedDeleteKey();
8184 }
8185 }
8186}
8187
David Drysdale42fe1892021-10-14 14:43:46 +01008188/*
8189 * KeyAgreementTest.EcdhCurve25519
8190 *
8191 * Verifies that ECDH works for curve25519. This is also covered by the general
8192 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8193 * KeyMint 1.0.
8194 */
8195TEST_P(KeyAgreementTest, EcdhCurve25519) {
8196 if (!Curve25519Supported()) {
8197 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8198 }
8199
8200 // Generate EC key in KeyMint (only access to public key material)
8201 EcCurve curve = EcCurve::CURVE_25519;
8202 EVP_PKEY_Ptr kmPubKey = nullptr;
8203 GenerateKeyMintEcKey(curve, &kmPubKey);
8204
8205 // Generate EC key on same curve locally (with access to private key material).
8206 EVP_PKEY_Ptr privKey;
8207 vector<uint8_t> encodedPublicKey;
8208 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8209
8210 // Agree on a key between local and KeyMint and check it.
8211 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8212
8213 CheckedDeleteKey();
8214}
8215
8216/*
8217 * KeyAgreementTest.EcdhCurve25519Imported
8218 *
8219 * Verifies that ECDH works for an imported curve25519 key.
8220 */
8221TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8222 if (!Curve25519Supported()) {
8223 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8224 }
8225
8226 // Import x25519 key into KeyMint.
8227 EcCurve curve = EcCurve::CURVE_25519;
8228 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8229 .Authorization(TAG_NO_AUTH_REQUIRED)
8230 .EcdsaKey(EcCurve::CURVE_25519)
8231 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8232 .SetDefaultValidity(),
8233 KeyFormat::PKCS8, x25519_pkcs8_key));
8234 ASSERT_GT(cert_chain_.size(), 0);
8235 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8236 ASSERT_NE(kmKeyCert, nullptr);
8237 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8238 ASSERT_NE(kmPubKey.get(), nullptr);
8239
8240 // Expect the import to emit corresponding public key data.
8241 size_t kmPubKeySize = 32;
8242 uint8_t kmPubKeyData[32];
8243 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8244 ASSERT_EQ(kmPubKeySize, 32);
8245 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8246 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8247
8248 // Generate EC key on same curve locally (with access to private key material).
8249 EVP_PKEY_Ptr privKey;
8250 vector<uint8_t> encodedPublicKey;
8251 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8252
8253 // Agree on a key between local and KeyMint and check it.
8254 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8255
8256 CheckedDeleteKey();
8257}
8258
8259/*
8260 * KeyAgreementTest.EcdhCurve25519InvalidSize
8261 *
8262 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8263 */
8264TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8265 if (!Curve25519Supported()) {
8266 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8267 }
8268
8269 // Generate EC key in KeyMint (only access to public key material)
8270 EcCurve curve = EcCurve::CURVE_25519;
8271 EVP_PKEY_Ptr kmPubKey = nullptr;
8272 GenerateKeyMintEcKey(curve, &kmPubKey);
8273
8274 // Generate EC key on same curve locally (with access to private key material).
8275 EVP_PKEY_Ptr privKey;
8276 vector<uint8_t> encodedPublicKey;
8277 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8278
8279 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8280 string ZabFromKeyMintStr;
8281 // Send in an incomplete public key.
8282 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8283 &ZabFromKeyMintStr));
8284
8285 CheckedDeleteKey();
8286}
8287
8288/*
8289 * KeyAgreementTest.EcdhCurve25519Mismatch
8290 *
8291 * Verifies that ECDH fails between curve25519 and other curves.
8292 */
8293TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8294 if (!Curve25519Supported()) {
8295 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8296 }
8297
8298 // Generate EC key in KeyMint (only access to public key material)
8299 EcCurve curve = EcCurve::CURVE_25519;
8300 EVP_PKEY_Ptr kmPubKey = nullptr;
8301 GenerateKeyMintEcKey(curve, &kmPubKey);
8302
8303 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008304 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008305 if (localCurve == curve) {
8306 continue;
8307 }
8308 // Generate EC key on a different curve locally (with access to private key material).
8309 EVP_PKEY_Ptr privKey;
8310 vector<uint8_t> encodedPublicKey;
8311 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8312
David Drysdale7fc26b92022-05-13 09:54:24 +01008313 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008314 string ZabFromKeyMintStr;
8315 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8316 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8317 &ZabFromKeyMintStr));
8318 }
8319
8320 CheckedDeleteKey();
8321}
8322
David Zeuthene0c40892021-01-08 12:54:11 -05008323INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8324
David Drysdaled2cc8c22021-04-15 13:29:45 +01008325using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8326
8327// This is a problematic test, as it can render the device under test permanently unusable.
8328// Re-enable and run at your own risk.
8329TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8330 auto result = DestroyAttestationIds();
8331 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8332}
8333
8334INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8335
Shawn Willdend659c7c2021-02-19 14:51:51 -07008336using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008337
David Drysdaledb0dcf52021-05-18 11:43:31 +01008338/*
8339 * EarlyBootKeyTest.CreateEarlyBootKeys
8340 *
8341 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8342 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008343TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008344 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008345 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8346 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8347
David Drysdaleadfe6112021-05-27 12:00:53 +01008348 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8349 ASSERT_GT(keyData.blob.size(), 0U);
8350 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8351 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8352 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008353 CheckedDeleteKey(&aesKeyData.blob);
8354 CheckedDeleteKey(&hmacKeyData.blob);
8355 CheckedDeleteKey(&rsaKeyData.blob);
8356 CheckedDeleteKey(&ecdsaKeyData.blob);
8357}
8358
David Drysdaledb0dcf52021-05-18 11:43:31 +01008359/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008360 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8361 *
8362 * Verifies that creating an early boot key with attestation succeeds.
8363 */
8364TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8365 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8366 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8367 builder->AttestationChallenge("challenge");
8368 builder->AttestationApplicationId("app_id");
8369 });
8370
8371 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008372 // Strongbox may not support factory attestation. Key creation might fail with
8373 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8374 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8375 continue;
8376 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008377 ASSERT_GT(keyData.blob.size(), 0U);
8378 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8379 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8380 }
8381 CheckedDeleteKey(&aesKeyData.blob);
8382 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00008383 if (rsaKeyData.blob.size() != 0U) {
8384 CheckedDeleteKey(&rsaKeyData.blob);
8385 }
8386 if (ecdsaKeyData.blob.size() != 0U) {
8387 CheckedDeleteKey(&ecdsaKeyData.blob);
8388 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008389}
8390
8391/*
8392 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008393 *
8394 * Verifies that using early boot keys at a later stage fails.
8395 */
8396TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8397 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8398 .Authorization(TAG_NO_AUTH_REQUIRED)
8399 .Authorization(TAG_EARLY_BOOT_ONLY)
8400 .HmacKey(128)
8401 .Digest(Digest::SHA_2_256)
8402 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8403 AuthorizationSet output_params;
8404 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8405 AuthorizationSetBuilder()
8406 .Digest(Digest::SHA_2_256)
8407 .Authorization(TAG_MAC_LENGTH, 256),
8408 &output_params));
8409}
8410
8411/*
8412 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8413 *
8414 * Verifies that importing early boot keys fails.
8415 */
8416TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8417 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8418 .Authorization(TAG_NO_AUTH_REQUIRED)
8419 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008420 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008421 .Digest(Digest::SHA_2_256)
8422 .SetDefaultValidity(),
8423 KeyFormat::PKCS8, ec_256_key));
8424}
8425
David Drysdaled2cc8c22021-04-15 13:29:45 +01008426// 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 +00008427// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8428// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8429// early boot, so you'll have to reboot between runs.
8430TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8431 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8432 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8433 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8434 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8435 EXPECT_TRUE(
8436 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8437 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8438 EXPECT_TRUE(
8439 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8440
8441 // Should be able to use keys, since early boot has not ended
8442 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8443 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8444 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8445 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8446
8447 // End early boot
8448 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8449 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8450
8451 // Should not be able to use already-created keys.
8452 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8453 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8454 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8455 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8456
8457 CheckedDeleteKey(&aesKeyData.blob);
8458 CheckedDeleteKey(&hmacKeyData.blob);
8459 CheckedDeleteKey(&rsaKeyData.blob);
8460 CheckedDeleteKey(&ecdsaKeyData.blob);
8461
8462 // Should not be able to create new keys
8463 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
8464 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
8465
8466 CheckedDeleteKey(&aesKeyData.blob);
8467 CheckedDeleteKey(&hmacKeyData.blob);
8468 CheckedDeleteKey(&rsaKeyData.blob);
8469 CheckedDeleteKey(&ecdsaKeyData.blob);
8470}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008471
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008472INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8473
Shawn Willdend659c7c2021-02-19 14:51:51 -07008474using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008475
8476// This may be a problematic test. It can't be run repeatedly without unlocking the device in
8477// between runs... and on most test devices there are no enrolled credentials so it can't be
8478// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8479// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8480// a manual test process, which includes unlocking between runs, which is why it's included here.
8481// Well, that and the fact that it's the only test we can do without also making calls into the
8482// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8483// implications might be, so that may or may not be a solution.
8484TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8485 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8486 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
8487
8488 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8489 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8490 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8491 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8492
8493 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008494 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008495 ASSERT_EQ(ErrorCode::OK, rc);
8496 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8497 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8498 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8499 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
8500
8501 CheckedDeleteKey(&aesKeyData.blob);
8502 CheckedDeleteKey(&hmacKeyData.blob);
8503 CheckedDeleteKey(&rsaKeyData.blob);
8504 CheckedDeleteKey(&ecdsaKeyData.blob);
8505}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008506
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008507INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8508
Shawn Willden22fb9c12022-06-02 14:04:33 -06008509using VsrRequirementTest = KeyMintAidlTestBase;
8510
8511TEST_P(VsrRequirementTest, Vsr13Test) {
8512 int vsr_api_level = get_vsr_api_level();
8513 if (vsr_api_level < 33) {
8514 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8515 }
8516 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8517}
8518
8519INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8520
Janis Danisevskis24c04702020-12-16 18:28:39 -08008521} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008522
8523int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008524 std::cout << "Testing ";
8525 auto halInstances =
8526 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8527 std::cout << "HAL instances:\n";
8528 for (auto& entry : halInstances) {
8529 std::cout << " " << entry << '\n';
8530 }
8531
Selene Huang31ab4042020-04-29 04:22:39 -07008532 ::testing::InitGoogleTest(&argc, argv);
8533 for (int i = 1; i < argc; ++i) {
8534 if (argv[i][0] == '-') {
8535 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008536 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8537 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008538 }
8539 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008540 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8541 dump_Attestations = true;
8542 } else {
8543 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008544 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008545 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8546 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8547 // be run in emulated environments that don't have the normal bootloader
8548 // interactions.
8549 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8550 }
Selene Huang31ab4042020-04-29 04:22:39 -07008551 }
8552 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008553 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008554}