blob: b695deec5d00c5f44e6e4130e90f55aecb4a51e2 [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 Zeuthene0c40892021-01-08 12:54:11 -050025#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070026#include <openssl/evp.h>
27#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050028#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070029
30#include <cutils/properties.h>
31
David Drysdale4dc01072021-04-01 12:17:35 +010032#include <android/binder_manager.h>
33
34#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080035#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070036
Shawn Willden08a7e432020-12-11 13:05:27 +000037#include <keymint_support/key_param_output.h>
38#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070039
40#include "KeyMintAidlTestBase.h"
41
Janis Danisevskis24c04702020-12-16 18:28:39 -080042using aidl::android::hardware::security::keymint::AuthorizationSet;
43using aidl::android::hardware::security::keymint::KeyCharacteristics;
44using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070045
Selene Huang31ab4042020-04-29 04:22:39 -070046namespace std {
47
Janis Danisevskis24c04702020-12-16 18:28:39 -080048using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070049
50template <>
51struct std::equal_to<KeyCharacteristics> {
52 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070053 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070054
Shawn Willden7f424372021-01-10 18:06:50 -070055 // this isn't very efficient. Oh, well.
56 AuthorizationSet a_auths(a.authorizations);
57 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070058
Shawn Willden7f424372021-01-10 18:06:50 -070059 a_auths.Sort();
60 b_auths.Sort();
61
62 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070063 }
64};
65
66} // namespace std
67
Janis Danisevskis24c04702020-12-16 18:28:39 -080068namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000069
Selene Huang31ab4042020-04-29 04:22:39 -070070namespace {
71
David Drysdalebb3d85e2021-04-13 11:15:51 +010072bool check_patchLevels = false;
73
Seth Moore7a55ae32021-06-23 14:28:11 -070074// The maximum number of times we'll attempt to verify that corruption
75// of an ecrypted blob results in an error. Retries are necessary as there
76// is a small (roughly 1/256) chance that corrupting ciphertext still results
77// in valid PKCS7 padding.
78constexpr size_t kMaxPaddingCorruptionRetries = 8;
79
Selene Huang31ab4042020-04-29 04:22:39 -070080template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000081bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
82 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070083 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080084 if (auto p = authorizationValue(ttag, param)) {
85 return *p == expected_value;
86 }
87 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070088 });
89 return (it != set.end());
90}
91
92template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000093bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070094 auto it = std::find_if(set.begin(), set.end(),
95 [&](const KeyParameter& param) { return param.tag == tag; });
96 return (it != set.end());
97}
98
99constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
100 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
101 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
102 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
103 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
104 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
108 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
110 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
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
116string hex2str(string a) {
117 string b;
118 size_t num = a.size() / 2;
119 b.resize(num);
120 for (size_t i = 0; i < num; i++) {
121 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
122 }
123 return b;
124}
125
David Drysdaled2cc8c22021-04-15 13:29:45 +0100126string rsa_key = hex2str(
127 // RFC 5208 s5
128 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
129 "020100" // INTEGER length 1 value 0x00 (version)
130 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
131 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
132 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
133 "0500" // NULL (parameters)
134 // } end SEQUENCE (AlgorithmIdentifier)
135 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
136 // RFC 8017 A.1.2
137 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
138 "020100" // INTEGER length 1 value 0x00 (version)
139 "028181" // INTEGER length 0x81 value (modulus) ...
140 "00c6095409047d8634812d5a218176e4"
141 "5c41d60a75b13901f234226cffe77652"
142 "1c5a77b9e389417b71c0b6a44d13afe4"
143 "e4a2805d46c9da2935adb1ff0c1f24ea"
144 "06e62b20d776430a4d435157233c6f91"
145 "6783c30e310fcbd89b85c2d567711697"
146 "85ac12bca244abda72bfb19fc44d27c8"
147 "1e1d92de284f4061edfd99280745ea6d"
148 "25"
149 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
150 "028180" // INTEGER length 0x80 (privateExponent) value...
151 "1be0f04d9cae3718691f035338308e91"
152 "564b55899ffb5084d2460e6630257e05"
153 "b3ceab02972dfabcd6ce5f6ee2589eb6"
154 "7911ed0fac16e43a444b8c861e544a05"
155 "93365772f8baf6b22fc9e3c5f1024b06"
156 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
157 "ace7240290bef16c0b3f7f3cdd64ce3a"
158 "b5912cf6e32f39ab188358afcccd8081"
159 "0241" // INTEGER length 0x41 (prime1)
160 "00e4b49ef50f765d3b24dde01aceaaf1"
161 "30f2c76670a91a61ae08af497b4a82be"
162 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
163 "8c92bfab137fba2285227b83c342ff7c"
164 "55"
165 "0241" // INTEGER length 0x41 (prime2)
166 "00ddabb5839c4c7f6bf3d4183231f005"
167 "b31aa58affdda5c79e4cce217f6bc930"
168 "dbe563d480706c24e9ebfcab28a6cdef"
169 "d324b77e1bf7251b709092c24ff501fd"
170 "91"
171 "0240" // INTEGER length 0x40 (exponent1)
172 "23d4340eda3445d8cd26c14411da6fdc"
173 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
174 "842c1d280405bc2f6c1bea214a1d742a"
175 "b996b35b63a82a5e470fa88dbf823cdd"
176 "0240" // INTEGER length 0x40 (exponent2)
177 "1b7b57449ad30d1518249a5f56bb9829"
178 "4d4b6ac12ffc86940497a5a5837a6cf9"
179 "46262b494526d328c11e1126380fde04"
180 "c24f916dec250892db09a6d77cdba351"
181 "0240" // INTEGER length 0x40 (coefficient)
182 "7762cd8f4d050da56bd591adb515d24d"
183 "7ccd32cca0d05f866d583514bd7324d5"
184 "f33645e8ed8b4a1cb3cc4a1d67987399"
185 "f2a09f5b3fb68c88d5e5d90ac33492d6"
186 // } end SEQUENCE (PrivateKey)
187 // } end SEQUENCE (PrivateKeyInfo)
188);
Selene Huang31ab4042020-04-29 04:22:39 -0700189
Selene Huange5727e62021-04-13 22:41:20 -0700190/*
191 * DER-encoded PKCS#8 format RSA key. Generated using:
192 *
193 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
194 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100195string rsa_2048_key = hex2str(
196 // RFC 5208 s5
197 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
198 "020100" // INTEGER length 1 value 0x00 (version)
199 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
200 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
201 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
202 "0500" // NULL (parameters)
203 // } end SEQUENCE (AlgorithmIdentifier)
204 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
205 // RFC 8017 A.1.2
206 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
207 "020100" // INTEGER length 1 value 0x00 (version)
208 "02820101" // INTEGER length 0x101 value (modulus) ...
209 "00BEBC342B56D443B1299F9A6A7056E8"
210 "0A897E318476A5A18029E63B2ED739A6"
211 "1791D339F58DC763D9D14911F2EDEC38"
212 "3DEE11F6319B44510E7A3ECD9B79B973"
213 "82E49500ACF8117DC89CAF0E621F7775"
214 "6554A2FD4664BFE7AB8B59AB48340DBF"
215 "A27B93B5A81F6ECDEB02D0759307128D"
216 "F3E3BAD4055C8B840216DFAA5700670E"
217 "6C5126F0962FCB70FF308F25049164CC"
218 "F76CC2DA66A7DD9A81A714C2809D6918"
219 "6133D29D84568E892B6FFBF3199BDB14"
220 "383EE224407F190358F111A949552ABA"
221 "6714227D1BD7F6B20DD0CB88F9467B71"
222 "9339F33BFF35B3870B3F62204E4286B0"
223 "948EA348B524544B5F9838F29EE643B0"
224 "79EEF8A713B220D7806924CDF7295070"
225 "C5"
226 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
227 "02820100" // INTEGER length 0x100 (privateExponent) value...
228 "69F377F35F2F584EF075353CCD1CA997"
229 "38DB3DBC7C7FF35F9366CE176DFD1B13"
230 "5AB10030344ABF5FBECF1D4659FDEF1C"
231 "0FC430834BE1BE3911951377BB3D563A"
232 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
233 "2686C7B4B3C09A7B8354133E6F93F790"
234 "D59EAEB92E84C9A4339302CCE28FDF04"
235 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
236 "6AB706645BF074A4E4090D06FB163124"
237 "365FD5EE7A20D350E9958CC30D91326E"
238 "1B292E9EF5DB408EC42DAF737D201497"
239 "04D0A678A0FB5B5446863B099228A352"
240 "D604BA8091A164D01D5AB05397C71EAD"
241 "20BE2A08FC528FE442817809C787FEE4"
242 "AB97F97B9130D022153EDC6EB6CBE7B0"
243 "F8E3473F2E901209B5DB10F93604DB01"
244 "028181" // INTEGER length 0x81 (prime1)
245 "00E83C0998214941EA4F9293F1B77E2E"
246 "99E6CF305FAF358238E126124FEAF2EB"
247 "9724B2EA7B78E6032343821A80E55D1D"
248 "88FB12D220C3F41A56142FEC85796D19"
249 "17F1E8C774F142B67D3D6E7B7E6B4383"
250 "E94DB5929089DBB346D5BDAB40CC2D96"
251 "EE0409475E175C63BF78CFD744136740"
252 "838127EA723FF3FE7FA368C1311B4A4E"
253 "05"
254 "028181" // INTEGER length 0x81 (prime2)
255 "00D240FCC0F5D7715CDE21CB2DC86EA1"
256 "46132EA3B06F61FF2AF54BF38473F59D"
257 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
258 "B1B58C39F95E4798CCBB43E83D0119AC"
259 "F532F359CA743C85199F0286610E2009"
260 "97D7312917179AC9B67558773212EC96"
261 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
262 "94D94E066A0900B7B70E82A44FB30053"
263 "C1"
264 "028181" // INTEGER length 0x81 (exponent1)
265 "00AD15DA1CBD6A492B66851BA8C316D3"
266 "8AB700E2CFDDD926A658003513C54BAA"
267 "152B30021D667D20078F500F8AD3E7F3"
268 "945D74A891ED1A28EAD0FEEAEC8C14A8"
269 "E834CF46A13D1378C99D18940823CFDD"
270 "27EC5810D59339E0C34198AC638E09C8"
271 "7CBB1B634A9864AE9F4D5EB2D53514F6"
272 "7B4CAEC048C8AB849A02E397618F3271"
273 "35"
274 "028180" // INTEGER length 0x80 (exponent2)
275 "1FA2C1A5331880A92D8F3E281C617108"
276 "BF38244F16E352E69ED417C7153F9EC3"
277 "18F211839C643DCF8B4DD67CE2AC312E"
278 "95178D5D952F06B1BF779F4916924B70"
279 "F582A23F11304E02A5E7565AE22A35E7"
280 "4FECC8B6FDC93F92A1A37703E4CF0E63"
281 "783BD02EB716A7ECBBFA606B10B74D01"
282 "579522E7EF84D91FC522292108D902C1"
283 "028180" // INTEGER length 0x80 (coefficient)
284 "796FE3825F9DCC85DF22D58690065D93"
285 "898ACD65C087BEA8DA3A63BF4549B795"
286 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
287 "0D74F40DED8E1102C52152A31B6165F8"
288 "3A6722AECFCC35A493D7634664B888A0"
289 "8D3EB034F12EA28BFEE346E205D33482"
290 "7F778B16ED40872BD29FCB36536B6E93"
291 "FFB06778696B4A9D81BB0A9423E63DE5"
292 // } end SEQUENCE (PrivateKey)
293 // } end SEQUENCE (PrivateKeyInfo)
294);
Selene Huange5727e62021-04-13 22:41:20 -0700295
David Drysdaled2cc8c22021-04-15 13:29:45 +0100296string ec_256_key = hex2str(
297 // RFC 5208 s5
298 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
299 "020100" // INTEGER length 1 value 0 (version)
300 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
301 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
302 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
303 "0608" // OBJECT IDENTIFIER length 8 (param)
304 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
305 // } end SEQUENCE (AlgorithmIdentifier)
306 "046d" // OCTET STRING length 0x6d (privateKey) holding...
307 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
308 "020101" // INTEGER length 1 value 1 (version)
309 "0420" // OCTET STRING length 0x20 (privateKey)
310 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
311 "941eed09366bc03299986481f3a4d859"
312 "a144" // TAG [1] len 0x44 (publicKey) {
313 "03420004bf85d7720d07c25461683bc6"
314 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
315 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
316 "bcc41c6eb00083cf3376d11fd44949e0"
317 "b2183bfe"
318 // } end SEQUENCE (ECPrivateKey)
319 // } end SEQUENCE (PrivateKeyInfo)
320);
Selene Huang31ab4042020-04-29 04:22:39 -0700321
David Drysdaled2cc8c22021-04-15 13:29:45 +0100322string ec_521_key = hex2str(
323 // RFC 5208 s5
324 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
325 "020100" // INTEGER length 1 value 0 (version)
326 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
327 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
328 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
329 "0605" // OBJECT IDENTIFIER length 5 (param)
330 "2B81040023" // 1.3.132.0.35 (secp521r1)
331 // } end SEQUENCE (AlgorithmIdentifier)
332 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
333 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
334 "020101" // INTEGER length 1 value 1 (version)
335 "0442" // OCTET STRING length 0x42 (privateKey)
336 "0011458C586DB5DAA92AFAB03F4FE46A"
337 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
338 "9D18D7D08B5BCFA0E53C75B064AD51C4"
339 "49BAE0258D54B94B1E885DED08ED4FB2"
340 "5CE9"
341 "A18189" // TAG [1] len 0x89 (publicKey) {
342 "03818600040149EC11C6DF0FA122C6A9"
343 "AFD9754A4FA9513A627CA329E349535A"
344 "5629875A8ADFBE27DCB932C051986377"
345 "108D054C28C6F39B6F2C9AF81802F9F3"
346 "26B842FF2E5F3C00AB7635CFB36157FC"
347 "0882D574A10D839C1A0C049DC5E0D775"
348 "E2EE50671A208431BB45E78E70BEFE93"
349 "0DB34818EE4D5C26259F5C6B8E28A652"
350 "950F9F88D7B4B2C9D9"
351 // } end SEQUENCE (ECPrivateKey)
352 // } end SEQUENCE (PrivateKeyInfo)
353);
Selene Huang31ab4042020-04-29 04:22:39 -0700354
David Drysdaled2cc8c22021-04-15 13:29:45 +0100355string ec_256_key_rfc5915 = hex2str(
356 // RFC 5208 s5
357 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
358 "020100" // INTEGER length 1 value 0 (version)
359 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
360 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
361 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
362 "0608" // OBJECT IDENTIFIER length 8 (param)
363 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
364 // } end SEQUENCE (AlgorithmIdentifier)
365 "0479" // OCTET STRING length 0x79 (privateKey) holding...
366 // RFC 5915 s3
367 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
368 "020101" // INTEGER length 1 value 1 (version)
369 "0420" // OCTET STRING length 0x42 (privateKey)
370 "782370a8c8ce5537baadd04dcff079c8"
371 "158cfa9c67b818b38e8d21c9fa750c1d"
372 "a00a" // TAG [0] length 0xa (parameters)
373 "0608" // OBJECT IDENTIFIER length 8
374 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
375 // } end TAG [0]
376 "a144" // TAG [1] length 0x44 (publicKey) {
377 "0342" // BIT STRING length 0x42
378 "00" // no pad bits
379 "04e2cc561ee701da0ad0ef0d176bb0c9"
380 "19d42e79c393fdc1bd6c4010d85cf2cf"
381 "8e68c905464666f98dad4f01573ba810"
382 "78b3428570a439ba3229fbc026c55068"
383 "2f"
384 // } end SEQUENCE (ECPrivateKey)
385 // } end SEQUENCE (PrivateKeyInfo)
386);
Selene Huang31ab4042020-04-29 04:22:39 -0700387
David Drysdaled2cc8c22021-04-15 13:29:45 +0100388string ec_256_key_sec1 = hex2str(
389 // RFC 5208 s5
390 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
391 "020100" // INTEGER length 1 value 0 (version)
392 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
393 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
394 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
395 "0608" // OBJECT IDENTIFIER length 8 (param)
396 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
397 // } end SEQUENCE (AlgorithmIdentifier)
398 "046d" // OCTET STRING length 0x6d (privateKey) holding...
399 // SEC1-v2 C.4
400 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
401 "020101" // INTEGER length 1 value 0x01 (version)
402 "0420" // OCTET STRING length 0x20 (privateKey)
403 "782370a8c8ce5537baadd04dcff079c8"
404 "158cfa9c67b818b38e8d21c9fa750c1d"
405 "a144" // TAG [1] length 0x44 (publicKey) {
406 "0342" // BIT STRING length 0x42
407 "00" // no pad bits
408 "04e2cc561ee701da0ad0ef0d176bb0c9"
409 "19d42e79c393fdc1bd6c4010d85cf2cf"
410 "8e68c905464666f98dad4f01573ba810"
411 "78b3428570a439ba3229fbc026c55068"
412 "2f"
413 // } end TAG [1] (publicKey)
414 // } end SEQUENCE (PrivateKeyInfo)
415);
Selene Huang31ab4042020-04-29 04:22:39 -0700416
417struct RSA_Delete {
418 void operator()(RSA* p) { RSA_free(p); }
419};
420
Selene Huang31ab4042020-04-29 04:22:39 -0700421std::string make_string(const uint8_t* data, size_t length) {
422 return std::string(reinterpret_cast<const char*>(data), length);
423}
424
425template <size_t N>
426std::string make_string(const uint8_t (&a)[N]) {
427 return make_string(a, N);
428}
429
430class AidlBuf : public vector<uint8_t> {
431 typedef vector<uint8_t> super;
432
433 public:
434 AidlBuf() {}
435 AidlBuf(const super& other) : super(other) {}
436 AidlBuf(super&& other) : super(std::move(other)) {}
437 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
438
439 AidlBuf& operator=(const super& other) {
440 super::operator=(other);
441 return *this;
442 }
443
444 AidlBuf& operator=(super&& other) {
445 super::operator=(std::move(other));
446 return *this;
447 }
448
449 AidlBuf& operator=(const string& other) {
450 resize(other.size());
451 for (size_t i = 0; i < other.size(); ++i) {
452 (*this)[i] = static_cast<uint8_t>(other[i]);
453 }
454 return *this;
455 }
456
457 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
458};
459
David Drysdale4dc01072021-04-01 12:17:35 +0100460string device_suffix(const string& name) {
461 size_t pos = name.find('/');
462 if (pos == string::npos) {
463 return name;
464 }
465 return name.substr(pos + 1);
466}
467
468bool matching_rp_instance(const string& km_name,
469 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
470 string km_suffix = device_suffix(km_name);
471
472 vector<string> rp_names =
473 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
474 for (const string& rp_name : rp_names) {
475 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
476 // KeyMint instance, assume they match.
477 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
478 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
479 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
480 return true;
481 }
482 }
483 return false;
484}
485
Selene Huang31ab4042020-04-29 04:22:39 -0700486} // namespace
487
488class NewKeyGenerationTest : public KeyMintAidlTestBase {
489 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700490 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000491 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700492 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700493
Selene Huang31ab4042020-04-29 04:22:39 -0700494 // Check that some unexpected tags/values are NOT present.
495 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
496 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000497 }
498
499 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
500 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
501 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
502 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
503
504 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000505 }
506
507 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
508 // TODO(swillden): Distinguish which params should be in which auth list.
509 AuthorizationSet auths;
510 for (auto& entry : keyCharacteristics) {
511 auths.push_back(AuthorizationSet(entry.authorizations));
512 }
513 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
514
515 // Verify that App data, ROT and auth timeout are NOT included.
516 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
517 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700518 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
519
David Drysdaled2cc8c22021-04-15 13:29:45 +0100520 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
521 // never adds it.
522 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
523
David Drysdale7de9feb2021-03-05 14:56:19 +0000524 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700525 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000526 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700527 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700528 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000529 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700530 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000531
David Drysdalebb3d85e2021-04-13 11:15:51 +0100532 if (check_patchLevels) {
533 // Should include vendor and boot patchlevels.
534 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
535 EXPECT_TRUE(vendor_pl);
536 EXPECT_EQ(*vendor_pl, vendor_patch_level());
537 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
538 EXPECT_TRUE(boot_pl);
539 }
540
David Drysdale7de9feb2021-03-05 14:56:19 +0000541 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700542 }
543};
544
545/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000546 * NewKeyGenerationTest.Aes
547 *
548 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
549 * have correct characteristics.
550 */
551TEST_P(NewKeyGenerationTest, Aes) {
552 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
553 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
554 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
555 SCOPED_TRACE(testing::Message()
556 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
557 vector<uint8_t> key_blob;
558 vector<KeyCharacteristics> key_characteristics;
559 auto builder = AuthorizationSetBuilder()
560 .AesEncryptionKey(key_size)
561 .BlockMode(block_mode)
562 .Padding(padding_mode)
563 .SetDefaultValidity();
564 if (block_mode == BlockMode::GCM) {
565 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
566 }
567 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
568
569 EXPECT_GT(key_blob.size(), 0U);
570 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100571 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000572
573 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
574
575 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
576 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
577 << "Key size " << key_size << "missing";
578
579 CheckedDeleteKey(&key_blob);
580 }
581 }
582 }
583}
584
585/*
586 * NewKeyGenerationTest.AesInvalidSize
587 *
588 * Verifies that specifying an invalid key size for AES key generation returns
589 * UNSUPPORTED_KEY_SIZE.
590 */
591TEST_P(NewKeyGenerationTest, AesInvalidSize) {
592 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
593 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
594 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
595 SCOPED_TRACE(testing::Message()
596 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
597 vector<uint8_t> key_blob;
598 vector<KeyCharacteristics> key_characteristics;
599 auto builder = AuthorizationSetBuilder()
600 .AesEncryptionKey(key_size)
601 .BlockMode(block_mode)
602 .Padding(padding_mode)
603 .SetDefaultValidity();
604 if (block_mode == BlockMode::GCM) {
605 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
606 }
607 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
608 GenerateKey(builder, &key_blob, &key_characteristics));
609 }
610 }
611 }
612
613 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
614 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
615 vector<uint8_t> key_blob;
616 vector<KeyCharacteristics> key_characteristics;
617 // No key size specified
618 auto builder = AuthorizationSetBuilder()
619 .Authorization(TAG_ALGORITHM, Algorithm::AES)
620 .BlockMode(block_mode)
621 .Padding(padding_mode)
622 .SetDefaultValidity();
623 if (block_mode == BlockMode::GCM) {
624 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
625 }
626 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
627 GenerateKey(builder, &key_blob, &key_characteristics));
628 }
629 }
630}
631
632/*
633 * NewKeyGenerationTest.AesInvalidPadding
634 *
635 * Verifies that specifying an invalid padding on AES keys gives a failure
636 * somewhere along the way.
637 */
638TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
639 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
640 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
641 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
642 SCOPED_TRACE(testing::Message()
643 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000644 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800645 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000646 .AesEncryptionKey(key_size)
647 .BlockMode(block_mode)
648 .Padding(padding_mode)
649 .SetDefaultValidity();
650 if (block_mode == BlockMode::GCM) {
651 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
652 }
653
Tommy Chiu3950b452021-05-03 22:01:46 +0800654 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000655 if (result == ErrorCode::OK) {
656 // Key creation was OK but has generated a key that cannot be used.
657 auto params =
658 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800659 if (block_mode == BlockMode::GCM) {
660 params.Authorization(TAG_MAC_LENGTH, 128);
661 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000662 auto result = Begin(KeyPurpose::ENCRYPT, params);
663 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100664 result == ErrorCode::INVALID_KEY_BLOB)
665 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000666 } else {
667 // The KeyMint implementation detected that the generated key
668 // is unusable.
669 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
670 }
671 }
672 }
673 }
674}
675
676/*
677 * NewKeyGenerationTest.AesGcmMissingMinMac
678 *
679 * Verifies that specifying an invalid key size for AES key generation returns
680 * UNSUPPORTED_KEY_SIZE.
681 */
682TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
683 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
684 BlockMode block_mode = BlockMode::GCM;
685 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
686 SCOPED_TRACE(testing::Message()
687 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
688 vector<uint8_t> key_blob;
689 vector<KeyCharacteristics> key_characteristics;
690 // No MIN_MAC_LENGTH provided.
691 auto builder = AuthorizationSetBuilder()
692 .AesEncryptionKey(key_size)
693 .BlockMode(block_mode)
694 .Padding(padding_mode)
695 .SetDefaultValidity();
696 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
697 GenerateKey(builder, &key_blob, &key_characteristics));
698 }
699 }
700}
701
702/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100703 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
704 *
705 * Verifies that specifying an invalid min MAC size for AES key generation returns
706 * UNSUPPORTED_MIN_MAC_LENGTH.
707 */
708TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
709 for (size_t min_mac_len : {88, 136}) {
710 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
711 BlockMode block_mode = BlockMode::GCM;
712 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
713 SCOPED_TRACE(testing::Message()
714 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
715 vector<uint8_t> key_blob;
716 vector<KeyCharacteristics> key_characteristics;
717 auto builder = AuthorizationSetBuilder()
718 .AesEncryptionKey(key_size)
719 .BlockMode(block_mode)
720 .Padding(padding_mode)
721 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
722 .SetDefaultValidity();
723 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
724 GenerateKey(builder, &key_blob, &key_characteristics));
725 }
726 }
727 }
728}
729
730/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000731 * NewKeyGenerationTest.TripleDes
732 *
733 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
734 * have correct characteristics.
735 */
736TEST_P(NewKeyGenerationTest, TripleDes) {
737 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
738 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
739 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
740 SCOPED_TRACE(testing::Message()
741 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
742 vector<uint8_t> key_blob;
743 vector<KeyCharacteristics> key_characteristics;
744 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
745 .TripleDesEncryptionKey(key_size)
746 .BlockMode(block_mode)
747 .Padding(padding_mode)
748 .Authorization(TAG_NO_AUTH_REQUIRED)
749 .SetDefaultValidity(),
750 &key_blob, &key_characteristics));
751
752 EXPECT_GT(key_blob.size(), 0U);
753 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100754 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000755
756 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
757
758 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
759 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
760 << "Key size " << key_size << "missing";
761
762 CheckedDeleteKey(&key_blob);
763 }
764 }
765 }
766}
767
768/*
769 * NewKeyGenerationTest.TripleDesWithAttestation
770 *
771 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
772 * have correct characteristics.
773 *
774 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
775 * put in a certificate) but which isn't an error.
776 */
777TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
778 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
779 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
780 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
781 SCOPED_TRACE(testing::Message()
782 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
783
784 auto challenge = "hello";
785 auto app_id = "foo";
786
787 vector<uint8_t> key_blob;
788 vector<KeyCharacteristics> key_characteristics;
789 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
790 .TripleDesEncryptionKey(key_size)
791 .BlockMode(block_mode)
792 .Padding(padding_mode)
793 .Authorization(TAG_NO_AUTH_REQUIRED)
794 .AttestationChallenge(challenge)
795 .AttestationApplicationId(app_id)
796 .SetDefaultValidity(),
797 &key_blob, &key_characteristics));
798
799 EXPECT_GT(key_blob.size(), 0U);
800 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100801 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000802
803 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
804
805 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
806 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
807 << "Key size " << key_size << "missing";
808
809 CheckedDeleteKey(&key_blob);
810 }
811 }
812 }
813}
814
815/*
816 * NewKeyGenerationTest.TripleDesInvalidSize
817 *
818 * Verifies that specifying an invalid key size for 3-DES key generation returns
819 * UNSUPPORTED_KEY_SIZE.
820 */
821TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
822 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
823 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
824 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
825 SCOPED_TRACE(testing::Message()
826 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
827 vector<uint8_t> key_blob;
828 vector<KeyCharacteristics> key_characteristics;
829 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
830 GenerateKey(AuthorizationSetBuilder()
831 .TripleDesEncryptionKey(key_size)
832 .BlockMode(block_mode)
833 .Padding(padding_mode)
834 .Authorization(TAG_NO_AUTH_REQUIRED)
835 .SetDefaultValidity(),
836 &key_blob, &key_characteristics));
837 }
838 }
839 }
840
841 // Omitting the key size fails.
842 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
843 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
844 SCOPED_TRACE(testing::Message()
845 << "3DES-default-" << block_mode << "-" << padding_mode);
846 vector<uint8_t> key_blob;
847 vector<KeyCharacteristics> key_characteristics;
848 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
849 GenerateKey(AuthorizationSetBuilder()
850 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
851 .BlockMode(block_mode)
852 .Padding(padding_mode)
853 .Authorization(TAG_NO_AUTH_REQUIRED)
854 .SetDefaultValidity(),
855 &key_blob, &key_characteristics));
856 }
857 }
858}
859
860/*
Selene Huang31ab4042020-04-29 04:22:39 -0700861 * NewKeyGenerationTest.Rsa
862 *
863 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
864 * have correct characteristics.
865 */
866TEST_P(NewKeyGenerationTest, Rsa) {
867 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
868 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700869 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700870 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
871 .RsaSigningKey(key_size, 65537)
872 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800873 .Padding(PaddingMode::NONE)
874 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700875 &key_blob, &key_characteristics));
876
877 ASSERT_GT(key_blob.size(), 0U);
878 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100879 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700880
Shawn Willden7f424372021-01-10 18:06:50 -0700881 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700882
883 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
884 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
885 << "Key size " << key_size << "missing";
886 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
887
888 CheckedDeleteKey(&key_blob);
889 }
890}
891
892/*
Qi Wud22ec842020-11-26 13:27:53 +0800893 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700894 *
David Drysdaled2cc8c22021-04-15 13:29:45 +0100895 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
896 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700897 */
898TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700899 auto challenge = "hello";
900 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700901
Selene Huang6e46f142021-04-20 19:20:11 -0700902 auto subject = "cert subj 2";
903 vector<uint8_t> subject_der(make_name_from_str(subject));
904
905 uint64_t serial_int = 66;
906 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
907
Selene Huang4f64c222021-04-13 19:54:36 -0700908 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700909 vector<uint8_t> key_blob;
910 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700911 ASSERT_EQ(ErrorCode::OK,
912 GenerateKey(AuthorizationSetBuilder()
913 .RsaSigningKey(key_size, 65537)
914 .Digest(Digest::NONE)
915 .Padding(PaddingMode::NONE)
916 .AttestationChallenge(challenge)
917 .AttestationApplicationId(app_id)
918 .Authorization(TAG_NO_AUTH_REQUIRED)
919 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
920 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
921 .SetDefaultValidity(),
922 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700923
924 ASSERT_GT(key_blob.size(), 0U);
925 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100926 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700927
928 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
929
930 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
931 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
932 << "Key size " << key_size << "missing";
933 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
934
Selene Huang6e46f142021-04-20 19:20:11 -0700935 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700936 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700937 ASSERT_GT(cert_chain_.size(), 0);
938
939 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
940 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
941 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
942 sw_enforced, hw_enforced, SecLevel(),
943 cert_chain_[0].encodedCertificate));
944
945 CheckedDeleteKey(&key_blob);
946 }
947}
948
949/*
David Drysdale4dc01072021-04-01 12:17:35 +0100950 * NewKeyGenerationTest.RsaWithRpkAttestation
951 *
952 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
953 * that has been generated using an associate IRemotelyProvisionedComponent.
954 */
955TEST_P(NewKeyGenerationTest, RsaWithRpkAttestation) {
956 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
957 // instance.
958 std::shared_ptr<IRemotelyProvisionedComponent> rp;
959 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
960 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
961
962 // Generate a P-256 keypair to use as an attestation key.
963 MacedPublicKey macedPubKey;
964 std::vector<uint8_t> privateKeyBlob;
965 auto status =
966 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
967 ASSERT_TRUE(status.isOk());
968 vector<uint8_t> coseKeyData;
969 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
970
971 AttestationKey attestation_key;
972 attestation_key.keyBlob = std::move(privateKeyBlob);
973 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
974
975 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
976 auto challenge = "hello";
977 auto app_id = "foo";
978
979 vector<uint8_t> key_blob;
980 vector<KeyCharacteristics> key_characteristics;
981 ASSERT_EQ(ErrorCode::OK,
982 GenerateKey(AuthorizationSetBuilder()
983 .RsaSigningKey(key_size, 65537)
984 .Digest(Digest::NONE)
985 .Padding(PaddingMode::NONE)
986 .AttestationChallenge(challenge)
987 .AttestationApplicationId(app_id)
988 .Authorization(TAG_NO_AUTH_REQUIRED)
989 .SetDefaultValidity(),
990 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
991
992 ASSERT_GT(key_blob.size(), 0U);
993 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100994 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +0100995
996 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
997
998 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
999 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1000 << "Key size " << key_size << "missing";
1001 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1002
1003 // Attestation by itself is not valid (last entry is not self-signed).
1004 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1005
1006 // The signature over the attested key should correspond to the P256 public key.
1007 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1008 ASSERT_TRUE(key_cert.get());
1009 EVP_PKEY_Ptr signing_pubkey;
1010 p256_pub_key(coseKeyData, &signing_pubkey);
1011 ASSERT_TRUE(signing_pubkey.get());
1012
1013 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1014 << "Verification of attested certificate failed "
1015 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1016
1017 CheckedDeleteKey(&key_blob);
1018 }
1019}
1020
1021/*
Selene Huang4f64c222021-04-13 19:54:36 -07001022 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1023 *
1024 * Verifies that keymint attestation for RSA encryption keys with challenge and
1025 * app id is also successful.
1026 */
1027TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1028 auto key_size = 2048;
1029 auto challenge = "hello";
1030 auto app_id = "foo";
1031
Selene Huang6e46f142021-04-20 19:20:11 -07001032 auto subject = "subj 2";
1033 vector<uint8_t> subject_der(make_name_from_str(subject));
1034
1035 uint64_t serial_int = 111166;
1036 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1037
Selene Huang4f64c222021-04-13 19:54:36 -07001038 vector<uint8_t> key_blob;
1039 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001040 ASSERT_EQ(ErrorCode::OK,
1041 GenerateKey(AuthorizationSetBuilder()
1042 .RsaEncryptionKey(key_size, 65537)
1043 .Padding(PaddingMode::NONE)
1044 .AttestationChallenge(challenge)
1045 .AttestationApplicationId(app_id)
1046 .Authorization(TAG_NO_AUTH_REQUIRED)
1047 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1048 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1049 .SetDefaultValidity(),
1050 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001051
1052 ASSERT_GT(key_blob.size(), 0U);
1053 AuthorizationSet auths;
1054 for (auto& entry : key_characteristics) {
1055 auths.push_back(AuthorizationSet(entry.authorizations));
1056 }
1057
1058 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1059 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1060
1061 // Verify that App data and ROT are NOT included.
1062 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1063 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1064
1065 // Check that some unexpected tags/values are NOT present.
1066 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1067 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1068
1069 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1070
1071 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1072 ASSERT_TRUE(os_ver);
1073 EXPECT_EQ(*os_ver, os_version());
1074
1075 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1076
1077 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1078 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1079 << "Key size " << key_size << "missing";
1080 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1081
Selene Huang6e46f142021-04-20 19:20:11 -07001082 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001083 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1084 ASSERT_GT(cert_chain_.size(), 0);
1085
1086 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1087 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1088 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1089 sw_enforced, hw_enforced, SecLevel(),
1090 cert_chain_[0].encodedCertificate));
1091
1092 CheckedDeleteKey(&key_blob);
1093}
1094
1095/*
1096 * NewKeyGenerationTest.RsaWithSelfSign
1097 *
1098 * Verifies that attesting to RSA key generation is successful, and returns
1099 * self signed certificate if no challenge is provided. And signing etc
1100 * works as expected.
1101 */
1102TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001103 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1104 vector<uint8_t> subject_der(make_name_from_str(subject));
1105
1106 uint64_t serial_int = 0;
1107 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1108
Selene Huang4f64c222021-04-13 19:54:36 -07001109 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1110 vector<uint8_t> key_blob;
1111 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001112 ASSERT_EQ(ErrorCode::OK,
1113 GenerateKey(AuthorizationSetBuilder()
1114 .RsaSigningKey(key_size, 65537)
1115 .Digest(Digest::NONE)
1116 .Padding(PaddingMode::NONE)
1117 .Authorization(TAG_NO_AUTH_REQUIRED)
1118 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1119 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1120 .SetDefaultValidity(),
1121 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001122
1123 ASSERT_GT(key_blob.size(), 0U);
1124 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001125 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001126
1127 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1128
1129 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1130 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1131 << "Key size " << key_size << "missing";
1132 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1133
Selene Huang6e46f142021-04-20 19:20:11 -07001134 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001135 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1136 ASSERT_EQ(cert_chain_.size(), 1);
1137
1138 CheckedDeleteKey(&key_blob);
1139 }
1140}
1141
1142/*
1143 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1144 *
1145 * Verifies that attesting to RSA checks for missing app ID.
1146 */
1147TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1148 auto challenge = "hello";
1149 vector<uint8_t> key_blob;
1150 vector<KeyCharacteristics> key_characteristics;
1151
1152 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1153 GenerateKey(AuthorizationSetBuilder()
1154 .RsaSigningKey(2048, 65537)
1155 .Digest(Digest::NONE)
1156 .Padding(PaddingMode::NONE)
1157 .AttestationChallenge(challenge)
1158 .Authorization(TAG_NO_AUTH_REQUIRED)
1159 .SetDefaultValidity(),
1160 &key_blob, &key_characteristics));
1161}
1162
1163/*
1164 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1165 *
1166 * Verifies that attesting to RSA ignores app id if challenge is missing.
1167 */
1168TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1169 auto key_size = 2048;
1170 auto app_id = "foo";
1171
Selene Huang6e46f142021-04-20 19:20:11 -07001172 auto subject = "cert subj 2";
1173 vector<uint8_t> subject_der(make_name_from_str(subject));
1174
1175 uint64_t serial_int = 1;
1176 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1177
Selene Huang4f64c222021-04-13 19:54:36 -07001178 vector<uint8_t> key_blob;
1179 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001180 ASSERT_EQ(ErrorCode::OK,
1181 GenerateKey(AuthorizationSetBuilder()
1182 .RsaSigningKey(key_size, 65537)
1183 .Digest(Digest::NONE)
1184 .Padding(PaddingMode::NONE)
1185 .AttestationApplicationId(app_id)
1186 .Authorization(TAG_NO_AUTH_REQUIRED)
1187 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1188 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1189 .SetDefaultValidity(),
1190 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001191
1192 ASSERT_GT(key_blob.size(), 0U);
1193 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001194 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001195
1196 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1197
1198 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1199 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1200 << "Key size " << key_size << "missing";
1201 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1202
Selene Huang6e46f142021-04-20 19:20:11 -07001203 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001204 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1205 ASSERT_EQ(cert_chain_.size(), 1);
1206
1207 CheckedDeleteKey(&key_blob);
1208}
1209
1210/*
Qi Wud22ec842020-11-26 13:27:53 +08001211 * NewKeyGenerationTest.LimitedUsageRsa
1212 *
1213 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1214 * resulting keys have correct characteristics.
1215 */
1216TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1217 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1218 vector<uint8_t> key_blob;
1219 vector<KeyCharacteristics> key_characteristics;
1220 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1221 .RsaSigningKey(key_size, 65537)
1222 .Digest(Digest::NONE)
1223 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001224 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1225 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001226 &key_blob, &key_characteristics));
1227
1228 ASSERT_GT(key_blob.size(), 0U);
1229 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001230 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001231
1232 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1233
1234 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1235 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1236 << "Key size " << key_size << "missing";
1237 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1238
1239 // Check the usage count limit tag appears in the authorizations.
1240 AuthorizationSet auths;
1241 for (auto& entry : key_characteristics) {
1242 auths.push_back(AuthorizationSet(entry.authorizations));
1243 }
1244 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1245 << "key usage count limit " << 1U << " missing";
1246
1247 CheckedDeleteKey(&key_blob);
1248 }
1249}
1250
1251/*
Qi Wubeefae42021-01-28 23:16:37 +08001252 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1253 *
1254 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1255 * resulting keys have correct characteristics and attestation.
1256 */
1257TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001258 auto challenge = "hello";
1259 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001260
Selene Huang6e46f142021-04-20 19:20:11 -07001261 auto subject = "cert subj 2";
1262 vector<uint8_t> subject_der(make_name_from_str(subject));
1263
1264 uint64_t serial_int = 66;
1265 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1266
Selene Huang4f64c222021-04-13 19:54:36 -07001267 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001268 vector<uint8_t> key_blob;
1269 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001270 ASSERT_EQ(ErrorCode::OK,
1271 GenerateKey(AuthorizationSetBuilder()
1272 .RsaSigningKey(key_size, 65537)
1273 .Digest(Digest::NONE)
1274 .Padding(PaddingMode::NONE)
1275 .AttestationChallenge(challenge)
1276 .AttestationApplicationId(app_id)
1277 .Authorization(TAG_NO_AUTH_REQUIRED)
1278 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1279 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1280 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1281 .SetDefaultValidity(),
1282 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001283
1284 ASSERT_GT(key_blob.size(), 0U);
1285 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001286 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001287
1288 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1289
1290 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1291 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1292 << "Key size " << key_size << "missing";
1293 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1294
1295 // Check the usage count limit tag appears in the authorizations.
1296 AuthorizationSet auths;
1297 for (auto& entry : key_characteristics) {
1298 auths.push_back(AuthorizationSet(entry.authorizations));
1299 }
1300 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1301 << "key usage count limit " << 1U << " missing";
1302
1303 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001304 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001305 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001306 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001307
1308 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1309 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1310 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1311 sw_enforced, hw_enforced, SecLevel(),
1312 cert_chain_[0].encodedCertificate));
1313
1314 CheckedDeleteKey(&key_blob);
1315 }
1316}
1317
1318/*
Selene Huang31ab4042020-04-29 04:22:39 -07001319 * NewKeyGenerationTest.NoInvalidRsaSizes
1320 *
1321 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1322 */
1323TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1324 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1325 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001326 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001327 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1328 GenerateKey(AuthorizationSetBuilder()
1329 .RsaSigningKey(key_size, 65537)
1330 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001331 .Padding(PaddingMode::NONE)
1332 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001333 &key_blob, &key_characteristics));
1334 }
1335}
1336
1337/*
1338 * NewKeyGenerationTest.RsaNoDefaultSize
1339 *
1340 * Verifies that failing to specify a key size for RSA key generation returns
1341 * UNSUPPORTED_KEY_SIZE.
1342 */
1343TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1344 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1345 GenerateKey(AuthorizationSetBuilder()
1346 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1347 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001348 .SigningKey()
1349 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001350}
1351
1352/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001353 * NewKeyGenerationTest.RsaMissingParams
1354 *
1355 * Verifies that omitting optional tags works.
1356 */
1357TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1358 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1359 ASSERT_EQ(ErrorCode::OK,
1360 GenerateKey(
1361 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1362 CheckedDeleteKey();
1363 }
1364}
1365
1366/*
Selene Huang31ab4042020-04-29 04:22:39 -07001367 * NewKeyGenerationTest.Ecdsa
1368 *
1369 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1370 * have correct characteristics.
1371 */
1372TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001373 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001374 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001375 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001376 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001377 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001378 .Digest(Digest::NONE)
1379 .SetDefaultValidity(),
1380 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001381 ASSERT_GT(key_blob.size(), 0U);
1382 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001383 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001384
Shawn Willden7f424372021-01-10 18:06:50 -07001385 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001386
1387 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001388 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001389
1390 CheckedDeleteKey(&key_blob);
1391 }
1392}
1393
1394/*
Selene Huang4f64c222021-04-13 19:54:36 -07001395 * NewKeyGenerationTest.EcdsaAttestation
1396 *
1397 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1398 * an attestation will be generated.
1399 */
1400TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1401 auto challenge = "hello";
1402 auto app_id = "foo";
1403
Selene Huang6e46f142021-04-20 19:20:11 -07001404 auto subject = "cert subj 2";
1405 vector<uint8_t> subject_der(make_name_from_str(subject));
1406
1407 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1408 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1409
David Drysdaledf09e542021-06-08 15:46:11 +01001410 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001411 vector<uint8_t> key_blob;
1412 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001413 ASSERT_EQ(ErrorCode::OK,
1414 GenerateKey(AuthorizationSetBuilder()
1415 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001416 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001417 .Digest(Digest::NONE)
1418 .AttestationChallenge(challenge)
1419 .AttestationApplicationId(app_id)
1420 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1421 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1422 .SetDefaultValidity(),
1423 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001424 ASSERT_GT(key_blob.size(), 0U);
1425 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001426 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001427
1428 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1429
1430 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001431 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001432
1433 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1434 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001435 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001436
1437 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1438 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1439 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1440 sw_enforced, hw_enforced, SecLevel(),
1441 cert_chain_[0].encodedCertificate));
1442
1443 CheckedDeleteKey(&key_blob);
1444 }
1445}
1446
1447/*
David Drysdale37af4b32021-05-14 16:46:59 +01001448 * NewKeyGenerationTest.EcdsaAttestationTags
1449 *
1450 * Verifies that creation of an attested ECDSA key includes various tags in the
1451 * attestation extension.
1452 */
1453TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1454 auto challenge = "hello";
1455 auto app_id = "foo";
1456 auto subject = "cert subj 2";
1457 vector<uint8_t> subject_der(make_name_from_str(subject));
1458 uint64_t serial_int = 0x1010;
1459 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1460 const AuthorizationSetBuilder base_builder =
1461 AuthorizationSetBuilder()
1462 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001463 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001464 .Digest(Digest::NONE)
1465 .AttestationChallenge(challenge)
1466 .AttestationApplicationId(app_id)
1467 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1468 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1469 .SetDefaultValidity();
1470
1471 // Various tags that map to fields in the attestation extension ASN.1 schema.
1472 auto extra_tags = AuthorizationSetBuilder()
1473 .Authorization(TAG_ROLLBACK_RESISTANCE)
1474 .Authorization(TAG_EARLY_BOOT_ONLY)
1475 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1476 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1477 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1478 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1479 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1480 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1481 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1482 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1483 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1484 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
1485 for (const KeyParameter& tag : extra_tags) {
1486 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1487 vector<uint8_t> key_blob;
1488 vector<KeyCharacteristics> key_characteristics;
1489 AuthorizationSetBuilder builder = base_builder;
1490 builder.push_back(tag);
1491 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1492 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1493 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1494 continue;
1495 }
Seth Mooreb393b082021-07-12 14:18:28 -07001496 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1497 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001498 continue;
1499 }
1500 ASSERT_EQ(result, ErrorCode::OK);
1501 ASSERT_GT(key_blob.size(), 0U);
1502
1503 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1504 ASSERT_GT(cert_chain_.size(), 0);
1505 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1506
1507 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1508 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001509 // Some tags are optional, so don't require them to be in the enforcements.
1510 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001511 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1512 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1513 }
1514
1515 // Verifying the attestation record will check for the specific tag because
1516 // it's included in the authorizations.
1517 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1518 SecLevel(), cert_chain_[0].encodedCertificate));
1519
1520 CheckedDeleteKey(&key_blob);
1521 }
1522
1523 // Device attestation IDs should be rejected for normal attestation requests; these fields
1524 // are only used for device unique attestation.
1525 auto invalid_tags = AuthorizationSetBuilder()
1526 .Authorization(TAG_ATTESTATION_ID_BRAND, "brand")
1527 .Authorization(TAG_ATTESTATION_ID_DEVICE, "device")
1528 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "product")
1529 .Authorization(TAG_ATTESTATION_ID_SERIAL, "serial")
1530 .Authorization(TAG_ATTESTATION_ID_IMEI, "imei")
1531 .Authorization(TAG_ATTESTATION_ID_MEID, "meid")
1532 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer")
1533 .Authorization(TAG_ATTESTATION_ID_MODEL, "model");
1534 for (const KeyParameter& tag : invalid_tags) {
1535 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1536 vector<uint8_t> key_blob;
1537 vector<KeyCharacteristics> key_characteristics;
1538 AuthorizationSetBuilder builder =
1539 AuthorizationSetBuilder()
1540 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001541 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001542 .Digest(Digest::NONE)
1543 .AttestationChallenge(challenge)
1544 .AttestationApplicationId(app_id)
1545 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1546 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1547 .SetDefaultValidity();
1548 builder.push_back(tag);
1549 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1550 GenerateKey(builder, &key_blob, &key_characteristics));
1551 }
1552}
1553
1554/*
1555 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1556 *
1557 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1558 */
1559TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1560 auto challenge = "hello";
1561 auto attest_app_id = "foo";
1562 auto subject = "cert subj 2";
1563 vector<uint8_t> subject_der(make_name_from_str(subject));
1564 uint64_t serial_int = 0x1010;
1565 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1566
1567 // Earlier versions of the attestation extension schema included a slot:
1568 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1569 // This should never have been included, and should never be filled in.
1570 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1571 // to confirm that this field never makes it into the attestation extension.
1572 vector<uint8_t> key_blob;
1573 vector<KeyCharacteristics> key_characteristics;
1574 auto result = GenerateKey(AuthorizationSetBuilder()
1575 .Authorization(TAG_NO_AUTH_REQUIRED)
1576 .EcdsaSigningKey(EcCurve::P_256)
1577 .Digest(Digest::NONE)
1578 .AttestationChallenge(challenge)
1579 .AttestationApplicationId(attest_app_id)
1580 .Authorization(TAG_APPLICATION_ID, "client_id")
1581 .Authorization(TAG_APPLICATION_DATA, "appdata")
1582 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1583 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1584 .SetDefaultValidity(),
1585 &key_blob, &key_characteristics);
1586 ASSERT_EQ(result, ErrorCode::OK);
1587 ASSERT_GT(key_blob.size(), 0U);
1588
1589 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1590 ASSERT_GT(cert_chain_.size(), 0);
1591 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1592
1593 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1594 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1595 EXPECT_TRUE(verify_attestation_record(challenge, attest_app_id, sw_enforced, hw_enforced,
1596 SecLevel(), cert_chain_[0].encodedCertificate));
1597
1598 // Check that the app id is not in the cert.
1599 string app_id = "clientid";
1600 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1601 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1602 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1603 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1604 cert_chain_[0].encodedCertificate.end());
1605
1606 CheckedDeleteKey(&key_blob);
1607}
1608
1609/*
Selene Huang4f64c222021-04-13 19:54:36 -07001610 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1611 *
1612 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1613 * the key will generate a self signed attestation.
1614 */
1615TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001616 auto subject = "cert subj 2";
1617 vector<uint8_t> subject_der(make_name_from_str(subject));
1618
1619 uint64_t serial_int = 0x123456FFF1234;
1620 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1621
David Drysdaledf09e542021-06-08 15:46:11 +01001622 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001623 vector<uint8_t> key_blob;
1624 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001625 ASSERT_EQ(ErrorCode::OK,
1626 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001627 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001628 .Digest(Digest::NONE)
1629 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1630 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1631 .SetDefaultValidity(),
1632 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001633 ASSERT_GT(key_blob.size(), 0U);
1634 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001635 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001636
1637 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1638
1639 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001640 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001641
1642 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001643 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001644 ASSERT_EQ(cert_chain_.size(), 1);
1645
1646 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1647 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1648
1649 CheckedDeleteKey(&key_blob);
1650 }
1651}
1652
1653/*
1654 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1655 *
1656 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1657 * app id must also be provided or else it will fail.
1658 */
1659TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1660 auto challenge = "hello";
1661 vector<uint8_t> key_blob;
1662 vector<KeyCharacteristics> key_characteristics;
1663
1664 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1665 GenerateKey(AuthorizationSetBuilder()
1666 .EcdsaSigningKey(EcCurve::P_256)
1667 .Digest(Digest::NONE)
1668 .AttestationChallenge(challenge)
1669 .SetDefaultValidity(),
1670 &key_blob, &key_characteristics));
1671}
1672
1673/*
1674 * NewKeyGenerationTest.EcdsaIgnoreAppId
1675 *
1676 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1677 * any appid will be ignored, and keymint will generate a self sign certificate.
1678 */
1679TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1680 auto app_id = "foo";
1681
David Drysdaledf09e542021-06-08 15:46:11 +01001682 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001683 vector<uint8_t> key_blob;
1684 vector<KeyCharacteristics> key_characteristics;
1685 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001686 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001687 .Digest(Digest::NONE)
1688 .AttestationApplicationId(app_id)
1689 .SetDefaultValidity(),
1690 &key_blob, &key_characteristics));
1691
1692 ASSERT_GT(key_blob.size(), 0U);
1693 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001694 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001695
1696 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1697
1698 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001699 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001700
1701 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1702 ASSERT_EQ(cert_chain_.size(), 1);
1703
1704 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1705 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1706
1707 CheckedDeleteKey(&key_blob);
1708 }
1709}
1710
1711/*
1712 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1713 *
1714 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1715 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1716 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1717 * to specify how many following bytes will be used to encode the length.
1718 */
1719TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1720 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001721 std::vector<uint32_t> app_id_lengths{143, 258};
1722
1723 for (uint32_t length : app_id_lengths) {
1724 const string app_id(length, 'a');
1725 vector<uint8_t> key_blob;
1726 vector<KeyCharacteristics> key_characteristics;
1727 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1728 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001729 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001730 .Digest(Digest::NONE)
1731 .AttestationChallenge(challenge)
1732 .AttestationApplicationId(app_id)
1733 .SetDefaultValidity(),
1734 &key_blob, &key_characteristics));
1735 ASSERT_GT(key_blob.size(), 0U);
1736 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001737 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001738
1739 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1740
1741 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001742 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001743
1744 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1745 ASSERT_GT(cert_chain_.size(), 0);
1746
1747 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1748 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1749 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1750 sw_enforced, hw_enforced, SecLevel(),
1751 cert_chain_[0].encodedCertificate));
1752
1753 CheckedDeleteKey(&key_blob);
1754 }
1755}
1756
1757/*
Qi Wud22ec842020-11-26 13:27:53 +08001758 * NewKeyGenerationTest.LimitedUsageEcdsa
1759 *
1760 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1761 * resulting keys have correct characteristics.
1762 */
1763TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001764 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001765 vector<uint8_t> key_blob;
1766 vector<KeyCharacteristics> key_characteristics;
1767 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001768 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001769 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001770 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1771 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001772 &key_blob, &key_characteristics));
1773
1774 ASSERT_GT(key_blob.size(), 0U);
1775 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001776 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001777
1778 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1779
1780 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001781 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001782
1783 // Check the usage count limit tag appears in the authorizations.
1784 AuthorizationSet auths;
1785 for (auto& entry : key_characteristics) {
1786 auths.push_back(AuthorizationSet(entry.authorizations));
1787 }
1788 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1789 << "key usage count limit " << 1U << " missing";
1790
1791 CheckedDeleteKey(&key_blob);
1792 }
1793}
1794
1795/*
Selene Huang31ab4042020-04-29 04:22:39 -07001796 * NewKeyGenerationTest.EcdsaDefaultSize
1797 *
David Drysdaledf09e542021-06-08 15:46:11 +01001798 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001799 * UNSUPPORTED_KEY_SIZE.
1800 */
1801TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1802 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1803 GenerateKey(AuthorizationSetBuilder()
1804 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1805 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001806 .Digest(Digest::NONE)
1807 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001808}
1809
1810/*
1811 * NewKeyGenerationTest.EcdsaInvalidSize
1812 *
1813 * Verifies that specifying an invalid key size for EC key generation returns
1814 * UNSUPPORTED_KEY_SIZE.
1815 */
1816TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdaledf09e542021-06-08 15:46:11 +01001817 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001818 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001819 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001820 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001821 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001822 .Digest(Digest::NONE)
1823 .SetDefaultValidity(),
1824 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001825 }
1826
David Drysdaledf09e542021-06-08 15:46:11 +01001827 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1828 GenerateKey(AuthorizationSetBuilder()
1829 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1830 .Authorization(TAG_KEY_SIZE, 190)
1831 .SigningKey()
1832 .Digest(Digest::NONE)
1833 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001834}
1835
1836/*
1837 * NewKeyGenerationTest.EcdsaMismatchKeySize
1838 *
1839 * Verifies that specifying mismatched key size and curve for EC key generation returns
1840 * INVALID_ARGUMENT.
1841 */
1842TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1843 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1844
David Drysdaledf09e542021-06-08 15:46:11 +01001845 auto result = GenerateKey(AuthorizationSetBuilder()
1846 .Authorization(TAG_KEY_SIZE, 224)
1847 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
1848 .Digest(Digest::NONE)
1849 .SetDefaultValidity());
1850 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT ||
1851 result == ErrorCode::UNSUPPORTED_ALGORITHM);
Selene Huang31ab4042020-04-29 04:22:39 -07001852}
1853
1854/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001855 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07001856 *
1857 * Verifies that keymint does not support any curve designated as unsupported.
1858 */
1859TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1860 Digest digest;
1861 if (SecLevel() == SecurityLevel::STRONGBOX) {
1862 digest = Digest::SHA_2_256;
1863 } else {
1864 digest = Digest::SHA_2_512;
1865 }
1866 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001867 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1868 .EcdsaSigningKey(curve)
1869 .Digest(digest)
1870 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001871 << "Failed to generate key on curve: " << curve;
1872 CheckedDeleteKey();
1873 }
1874}
1875
1876/*
1877 * NewKeyGenerationTest.Hmac
1878 *
1879 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1880 * characteristics.
1881 */
1882TEST_P(NewKeyGenerationTest, Hmac) {
1883 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1884 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001885 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001886 constexpr size_t key_size = 128;
1887 ASSERT_EQ(ErrorCode::OK,
1888 GenerateKey(
1889 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1890 TAG_MIN_MAC_LENGTH, 128),
1891 &key_blob, &key_characteristics));
1892
1893 ASSERT_GT(key_blob.size(), 0U);
1894 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001895 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001896
Shawn Willden7f424372021-01-10 18:06:50 -07001897 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1898 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1899 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1900 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001901
1902 CheckedDeleteKey(&key_blob);
1903 }
1904}
1905
1906/*
Selene Huang4f64c222021-04-13 19:54:36 -07001907 * NewKeyGenerationTest.HmacNoAttestation
1908 *
1909 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1910 * and app id are provided.
1911 */
1912TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1913 auto challenge = "hello";
1914 auto app_id = "foo";
1915
1916 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1917 vector<uint8_t> key_blob;
1918 vector<KeyCharacteristics> key_characteristics;
1919 constexpr size_t key_size = 128;
1920 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1921 .HmacKey(key_size)
1922 .Digest(digest)
1923 .AttestationChallenge(challenge)
1924 .AttestationApplicationId(app_id)
1925 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1926 &key_blob, &key_characteristics));
1927
1928 ASSERT_GT(key_blob.size(), 0U);
1929 ASSERT_EQ(cert_chain_.size(), 0);
1930 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001931 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001932
1933 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1934 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1935 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1936 << "Key size " << key_size << "missing";
1937
1938 CheckedDeleteKey(&key_blob);
1939 }
1940}
1941
1942/*
Qi Wud22ec842020-11-26 13:27:53 +08001943 * NewKeyGenerationTest.LimitedUsageHmac
1944 *
1945 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1946 * resulting keys have correct characteristics.
1947 */
1948TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1949 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1950 vector<uint8_t> key_blob;
1951 vector<KeyCharacteristics> key_characteristics;
1952 constexpr size_t key_size = 128;
1953 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1954 .HmacKey(key_size)
1955 .Digest(digest)
1956 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1957 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1958 &key_blob, &key_characteristics));
1959
1960 ASSERT_GT(key_blob.size(), 0U);
1961 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001962 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001963
1964 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1965 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1966 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1967 << "Key size " << key_size << "missing";
1968
1969 // Check the usage count limit tag appears in the authorizations.
1970 AuthorizationSet auths;
1971 for (auto& entry : key_characteristics) {
1972 auths.push_back(AuthorizationSet(entry.authorizations));
1973 }
1974 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1975 << "key usage count limit " << 1U << " missing";
1976
1977 CheckedDeleteKey(&key_blob);
1978 }
1979}
1980
1981/*
Selene Huang31ab4042020-04-29 04:22:39 -07001982 * NewKeyGenerationTest.HmacCheckKeySizes
1983 *
1984 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1985 */
1986TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1987 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1988 if (key_size < 64 || key_size % 8 != 0) {
1989 // To keep this test from being very slow, we only test a random fraction of
1990 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1991 // them, we expect to run ~40 of them in each run.
1992 if (key_size % 8 == 0 || random() % 10 == 0) {
1993 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1994 GenerateKey(AuthorizationSetBuilder()
1995 .HmacKey(key_size)
1996 .Digest(Digest::SHA_2_256)
1997 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1998 << "HMAC key size " << key_size << " invalid";
1999 }
2000 } else {
2001 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2002 .HmacKey(key_size)
2003 .Digest(Digest::SHA_2_256)
2004 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2005 << "Failed to generate HMAC key of size " << key_size;
2006 CheckedDeleteKey();
2007 }
2008 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002009 if (SecLevel() == SecurityLevel::STRONGBOX) {
2010 // STRONGBOX devices must not support keys larger than 512 bits.
2011 size_t key_size = 520;
2012 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2013 GenerateKey(AuthorizationSetBuilder()
2014 .HmacKey(key_size)
2015 .Digest(Digest::SHA_2_256)
2016 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2017 << "HMAC key size " << key_size << " unexpectedly valid";
2018 }
Selene Huang31ab4042020-04-29 04:22:39 -07002019}
2020
2021/*
2022 * NewKeyGenerationTest.HmacCheckMinMacLengths
2023 *
2024 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2025 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2026 * specific MAC length that failed, so reproducing a failed run will be easy.
2027 */
2028TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2029 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2030 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2031 // To keep this test from being very long, we only test a random fraction of
2032 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2033 // we expect to run ~17 of them in each run.
2034 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2035 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2036 GenerateKey(AuthorizationSetBuilder()
2037 .HmacKey(128)
2038 .Digest(Digest::SHA_2_256)
2039 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2040 << "HMAC min mac length " << min_mac_length << " invalid.";
2041 }
2042 } else {
2043 EXPECT_EQ(ErrorCode::OK,
2044 GenerateKey(AuthorizationSetBuilder()
2045 .HmacKey(128)
2046 .Digest(Digest::SHA_2_256)
2047 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2048 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2049 CheckedDeleteKey();
2050 }
2051 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002052
2053 // Minimum MAC length must be no more than 512 bits.
2054 size_t min_mac_length = 520;
2055 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2056 GenerateKey(AuthorizationSetBuilder()
2057 .HmacKey(128)
2058 .Digest(Digest::SHA_2_256)
2059 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2060 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002061}
2062
2063/*
2064 * NewKeyGenerationTest.HmacMultipleDigests
2065 *
2066 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2067 */
2068TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
2069 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2070
2071 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2072 GenerateKey(AuthorizationSetBuilder()
2073 .HmacKey(128)
2074 .Digest(Digest::SHA1)
2075 .Digest(Digest::SHA_2_256)
2076 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2077}
2078
2079/*
2080 * NewKeyGenerationTest.HmacDigestNone
2081 *
2082 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2083 */
2084TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2085 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2086 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2087 128)));
2088
2089 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2090 GenerateKey(AuthorizationSetBuilder()
2091 .HmacKey(128)
2092 .Digest(Digest::NONE)
2093 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2094}
2095
Selene Huang4f64c222021-04-13 19:54:36 -07002096/*
2097 * NewKeyGenerationTest.AesNoAttestation
2098 *
2099 * Verifies that attestation parameters to AES keys are ignored and generateKey
2100 * will succeed.
2101 */
2102TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2103 auto challenge = "hello";
2104 auto app_id = "foo";
2105
2106 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2107 .Authorization(TAG_NO_AUTH_REQUIRED)
2108 .AesEncryptionKey(128)
2109 .EcbMode()
2110 .Padding(PaddingMode::PKCS7)
2111 .AttestationChallenge(challenge)
2112 .AttestationApplicationId(app_id)));
2113
2114 ASSERT_EQ(cert_chain_.size(), 0);
2115}
2116
2117/*
2118 * NewKeyGenerationTest.TripleDesNoAttestation
2119 *
2120 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2121 * will be successful. No attestation should be generated.
2122 */
2123TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2124 auto challenge = "hello";
2125 auto app_id = "foo";
2126
2127 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2128 .TripleDesEncryptionKey(168)
2129 .BlockMode(BlockMode::ECB)
2130 .Authorization(TAG_NO_AUTH_REQUIRED)
2131 .Padding(PaddingMode::NONE)
2132 .AttestationChallenge(challenge)
2133 .AttestationApplicationId(app_id)));
2134 ASSERT_EQ(cert_chain_.size(), 0);
2135}
2136
Selene Huang31ab4042020-04-29 04:22:39 -07002137INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2138
2139typedef KeyMintAidlTestBase SigningOperationsTest;
2140
2141/*
2142 * SigningOperationsTest.RsaSuccess
2143 *
2144 * Verifies that raw RSA signature operations succeed.
2145 */
2146TEST_P(SigningOperationsTest, RsaSuccess) {
2147 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2148 .RsaSigningKey(2048, 65537)
2149 .Digest(Digest::NONE)
2150 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002151 .Authorization(TAG_NO_AUTH_REQUIRED)
2152 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002153 string message = "12345678901234567890123456789012";
2154 string signature = SignMessage(
2155 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002156 LocalVerifyMessage(message, signature,
2157 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2158}
2159
2160/*
2161 * SigningOperationsTest.RsaAllPaddingsAndDigests
2162 *
2163 * Verifies RSA signature/verification for all padding modes and digests.
2164 */
2165TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2166 auto authorizations = AuthorizationSetBuilder()
2167 .Authorization(TAG_NO_AUTH_REQUIRED)
2168 .RsaSigningKey(2048, 65537)
2169 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2170 .Padding(PaddingMode::NONE)
2171 .Padding(PaddingMode::RSA_PSS)
2172 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2173 .SetDefaultValidity();
2174
2175 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2176
2177 string message(128, 'a');
2178 string corrupt_message(message);
2179 ++corrupt_message[corrupt_message.size() / 2];
2180
2181 for (auto padding :
2182 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2183 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2184 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2185 // Digesting only makes sense with padding.
2186 continue;
2187 }
2188
2189 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2190 // PSS requires digesting.
2191 continue;
2192 }
2193
2194 string signature =
2195 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2196 LocalVerifyMessage(message, signature,
2197 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2198 }
2199 }
Selene Huang31ab4042020-04-29 04:22:39 -07002200}
2201
2202/*
2203 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2204 *
Shawn Willden7f424372021-01-10 18:06:50 -07002205 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002206 */
2207TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2208 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2209 .Authorization(TAG_NO_AUTH_REQUIRED)
2210 .RsaSigningKey(2048, 65537)
2211 .Digest(Digest::NONE)
2212 .Padding(PaddingMode::NONE)
2213 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002214 .Authorization(TAG_APPLICATION_DATA, "appdata")
2215 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002216
2217 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2218
Selene Huang31ab4042020-04-29 04:22:39 -07002219 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2220 Begin(KeyPurpose::SIGN,
2221 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2222 AbortIfNeeded();
2223 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2224 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2225 .Digest(Digest::NONE)
2226 .Padding(PaddingMode::NONE)
2227 .Authorization(TAG_APPLICATION_ID, "clientid")));
2228 AbortIfNeeded();
2229 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2230 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2231 .Digest(Digest::NONE)
2232 .Padding(PaddingMode::NONE)
2233 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2234 AbortIfNeeded();
2235 EXPECT_EQ(ErrorCode::OK,
2236 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2237 .Digest(Digest::NONE)
2238 .Padding(PaddingMode::NONE)
2239 .Authorization(TAG_APPLICATION_DATA, "appdata")
2240 .Authorization(TAG_APPLICATION_ID, "clientid")));
2241 AbortIfNeeded();
2242}
2243
2244/*
2245 * SigningOperationsTest.RsaPssSha256Success
2246 *
2247 * Verifies that RSA-PSS signature operations succeed.
2248 */
2249TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2250 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2251 .RsaSigningKey(2048, 65537)
2252 .Digest(Digest::SHA_2_256)
2253 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002254 .Authorization(TAG_NO_AUTH_REQUIRED)
2255 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002256 // Use large message, which won't work without digesting.
2257 string message(1024, 'a');
2258 string signature = SignMessage(
2259 message,
2260 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2261}
2262
2263/*
2264 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2265 *
2266 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2267 * supports only unpadded operations.
2268 */
2269TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2270 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2271 .RsaSigningKey(2048, 65537)
2272 .Digest(Digest::NONE)
2273 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002274 .Padding(PaddingMode::NONE)
2275 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002276 string message = "12345678901234567890123456789012";
2277 string signature;
2278
2279 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2280 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2281 .Digest(Digest::NONE)
2282 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2283}
2284
2285/*
2286 * SigningOperationsTest.NoUserConfirmation
2287 *
2288 * Verifies that keymint rejects signing operations for keys with
2289 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2290 * presented.
2291 */
2292TEST_P(SigningOperationsTest, NoUserConfirmation) {
2293 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08002294 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2295 .RsaSigningKey(1024, 65537)
2296 .Digest(Digest::NONE)
2297 .Padding(PaddingMode::NONE)
2298 .Authorization(TAG_NO_AUTH_REQUIRED)
2299 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2300 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002301
2302 const string message = "12345678901234567890123456789012";
2303 EXPECT_EQ(ErrorCode::OK,
2304 Begin(KeyPurpose::SIGN,
2305 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2306 string signature;
2307 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2308}
2309
2310/*
2311 * SigningOperationsTest.RsaPkcs1Sha256Success
2312 *
2313 * Verifies that digested RSA-PKCS1 signature operations succeed.
2314 */
2315TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2316 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2317 .RsaSigningKey(2048, 65537)
2318 .Digest(Digest::SHA_2_256)
2319 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002320 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2321 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002322 string message(1024, 'a');
2323 string signature = SignMessage(message, AuthorizationSetBuilder()
2324 .Digest(Digest::SHA_2_256)
2325 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2326}
2327
2328/*
2329 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2330 *
2331 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2332 */
2333TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2334 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2335 .RsaSigningKey(2048, 65537)
2336 .Digest(Digest::NONE)
2337 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002338 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2339 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002340 string message(53, 'a');
2341 string signature = SignMessage(message, AuthorizationSetBuilder()
2342 .Digest(Digest::NONE)
2343 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2344}
2345
2346/*
2347 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2348 *
2349 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2350 * given a too-long message.
2351 */
2352TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2353 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2354 .RsaSigningKey(2048, 65537)
2355 .Digest(Digest::NONE)
2356 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002357 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2358 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002359 string message(257, 'a');
2360
2361 EXPECT_EQ(ErrorCode::OK,
2362 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2363 .Digest(Digest::NONE)
2364 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2365 string signature;
2366 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2367}
2368
2369/*
2370 * SigningOperationsTest.RsaPssSha512TooSmallKey
2371 *
2372 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2373 * used with a key that is too small for the message.
2374 *
2375 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2376 * keymint specification requires that salt_size == digest_size, so the message will be
2377 * digest_size * 2 +
2378 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2379 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2380 * for a 1024-bit key.
2381 */
2382TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
2383 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2384 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2385 .RsaSigningKey(1024, 65537)
2386 .Digest(Digest::SHA_2_512)
2387 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002388 .Padding(PaddingMode::RSA_PSS)
2389 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002390 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2391 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2392 .Digest(Digest::SHA_2_512)
2393 .Padding(PaddingMode::RSA_PSS)));
2394}
2395
2396/*
2397 * SigningOperationsTest.RsaNoPaddingTooLong
2398 *
2399 * Verifies that raw RSA signature operations fail with the correct error code when
2400 * given a too-long message.
2401 */
2402TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2403 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2404 .RsaSigningKey(2048, 65537)
2405 .Digest(Digest::NONE)
2406 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002407 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2408 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002409 // One byte too long
2410 string message(2048 / 8 + 1, 'a');
2411 ASSERT_EQ(ErrorCode::OK,
2412 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2413 .Digest(Digest::NONE)
2414 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2415 string result;
2416 ErrorCode finish_error_code = Finish(message, &result);
2417 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2418 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2419
2420 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2421 message = string(128 * 1024, 'a');
2422 ASSERT_EQ(ErrorCode::OK,
2423 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2424 .Digest(Digest::NONE)
2425 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2426 finish_error_code = Finish(message, &result);
2427 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2428 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2429}
2430
2431/*
2432 * SigningOperationsTest.RsaAbort
2433 *
2434 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2435 * test, but the behavior should be algorithm and purpose-independent.
2436 */
2437TEST_P(SigningOperationsTest, RsaAbort) {
2438 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2439 .RsaSigningKey(2048, 65537)
2440 .Digest(Digest::NONE)
2441 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002442 .Padding(PaddingMode::NONE)
2443 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002444
2445 ASSERT_EQ(ErrorCode::OK,
2446 Begin(KeyPurpose::SIGN,
2447 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2448 EXPECT_EQ(ErrorCode::OK, Abort());
2449
2450 // Another abort should fail
2451 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2452
2453 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002454 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002455}
2456
2457/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002458 * SigningOperationsTest.RsaNonUniqueParams
2459 *
2460 * Verifies that an operation with multiple padding modes is rejected.
2461 */
2462TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2463 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2464 .RsaSigningKey(2048, 65537)
2465 .Digest(Digest::NONE)
2466 .Digest(Digest::SHA1)
2467 .Authorization(TAG_NO_AUTH_REQUIRED)
2468 .Padding(PaddingMode::NONE)
2469 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2470 .SetDefaultValidity()));
2471
2472 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2473 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2474 .Digest(Digest::NONE)
2475 .Padding(PaddingMode::NONE)
2476 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2477
Tommy Chiuc93c4392021-05-11 18:36:50 +08002478 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2479 .Digest(Digest::NONE)
2480 .Digest(Digest::SHA1)
2481 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2482 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002483
2484 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2485 Begin(KeyPurpose::SIGN,
2486 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2487}
2488
2489/*
Selene Huang31ab4042020-04-29 04:22:39 -07002490 * SigningOperationsTest.RsaUnsupportedPadding
2491 *
2492 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2493 * with a padding mode inappropriate for RSA.
2494 */
2495TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2496 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2497 .RsaSigningKey(2048, 65537)
2498 .Authorization(TAG_NO_AUTH_REQUIRED)
2499 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002500 .Padding(PaddingMode::PKCS7)
2501 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002502 ASSERT_EQ(
2503 ErrorCode::UNSUPPORTED_PADDING_MODE,
2504 Begin(KeyPurpose::SIGN,
2505 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002506 CheckedDeleteKey();
2507
2508 ASSERT_EQ(ErrorCode::OK,
2509 GenerateKey(
2510 AuthorizationSetBuilder()
2511 .RsaSigningKey(2048, 65537)
2512 .Authorization(TAG_NO_AUTH_REQUIRED)
2513 .Digest(Digest::SHA_2_256 /* supported digest */)
2514 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2515 .SetDefaultValidity()));
2516 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2517 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2518 .Digest(Digest::SHA_2_256)
2519 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002520}
2521
2522/*
2523 * SigningOperationsTest.RsaPssNoDigest
2524 *
2525 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2526 */
2527TEST_P(SigningOperationsTest, RsaNoDigest) {
2528 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2529 .RsaSigningKey(2048, 65537)
2530 .Authorization(TAG_NO_AUTH_REQUIRED)
2531 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002532 .Padding(PaddingMode::RSA_PSS)
2533 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002534 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2535 Begin(KeyPurpose::SIGN,
2536 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2537
2538 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2539 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2540}
2541
2542/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002543 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002544 *
2545 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2546 * supported in some cases (as validated in other tests), but a mode must be specified.
2547 */
2548TEST_P(SigningOperationsTest, RsaNoPadding) {
2549 // Padding must be specified
2550 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2551 .RsaKey(2048, 65537)
2552 .Authorization(TAG_NO_AUTH_REQUIRED)
2553 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002554 .Digest(Digest::NONE)
2555 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002556 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2557 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2558}
2559
2560/*
2561 * SigningOperationsTest.RsaShortMessage
2562 *
2563 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2564 */
2565TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2566 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2567 .Authorization(TAG_NO_AUTH_REQUIRED)
2568 .RsaSigningKey(2048, 65537)
2569 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002570 .Padding(PaddingMode::NONE)
2571 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002572
2573 // Barely shorter
2574 string message(2048 / 8 - 1, 'a');
2575 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2576
2577 // Much shorter
2578 message = "a";
2579 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2580}
2581
2582/*
2583 * SigningOperationsTest.RsaSignWithEncryptionKey
2584 *
2585 * Verifies that RSA encryption keys cannot be used to sign.
2586 */
2587TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2588 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2589 .Authorization(TAG_NO_AUTH_REQUIRED)
2590 .RsaEncryptionKey(2048, 65537)
2591 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002592 .Padding(PaddingMode::NONE)
2593 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002594 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2595 Begin(KeyPurpose::SIGN,
2596 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2597}
2598
2599/*
2600 * SigningOperationsTest.RsaSignTooLargeMessage
2601 *
2602 * Verifies that attempting a raw signature of a message which is the same length as the key,
2603 * but numerically larger than the public modulus, fails with the correct error.
2604 */
2605TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2606 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2607 .Authorization(TAG_NO_AUTH_REQUIRED)
2608 .RsaSigningKey(2048, 65537)
2609 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002610 .Padding(PaddingMode::NONE)
2611 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002612
2613 // Largest possible message will always be larger than the public modulus.
2614 string message(2048 / 8, static_cast<char>(0xff));
2615 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2616 .Authorization(TAG_NO_AUTH_REQUIRED)
2617 .Digest(Digest::NONE)
2618 .Padding(PaddingMode::NONE)));
2619 string signature;
2620 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2621}
2622
2623/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01002624 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2625 *
2626 * Verifies ECDSA signature/verification for all digests and curves.
2627 */
2628TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2629 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2630
2631 string message = "1234567890";
2632 string corrupt_message = "2234567890";
2633 for (auto curve : ValidCurves()) {
2634 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2635 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2636 .Authorization(TAG_NO_AUTH_REQUIRED)
2637 .EcdsaSigningKey(curve)
2638 .Digest(digests)
2639 .SetDefaultValidity());
2640 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2641 if (error != ErrorCode::OK) {
2642 continue;
2643 }
2644
2645 for (auto digest : digests) {
2646 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2647 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2648 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2649 }
2650
2651 auto rc = DeleteKey();
2652 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2653 }
2654}
2655
2656/*
Selene Huang31ab4042020-04-29 04:22:39 -07002657 * SigningOperationsTest.EcdsaAllCurves
2658 *
2659 * Verifies that ECDSA operations succeed with all possible curves.
2660 */
2661TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2662 for (auto curve : ValidCurves()) {
2663 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2664 .Authorization(TAG_NO_AUTH_REQUIRED)
2665 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002666 .Digest(Digest::SHA_2_256)
2667 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002668 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2669 if (error != ErrorCode::OK) continue;
2670
2671 string message(1024, 'a');
2672 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2673 CheckedDeleteKey();
2674 }
2675}
2676
2677/*
2678 * SigningOperationsTest.EcdsaNoDigestHugeData
2679 *
2680 * Verifies that ECDSA operations support very large messages, even without digesting. This
2681 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2682 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2683 * the framework.
2684 */
2685TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2686 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2687 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002688 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002689 .Digest(Digest::NONE)
2690 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002691 string message(1 * 1024, 'a');
2692 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2693}
2694
2695/*
2696 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2697 *
2698 * Verifies that using an EC key requires the correct app ID/data.
2699 */
2700TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2701 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2702 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002703 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002704 .Digest(Digest::NONE)
2705 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002706 .Authorization(TAG_APPLICATION_DATA, "appdata")
2707 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002708
2709 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2710
Selene Huang31ab4042020-04-29 04:22:39 -07002711 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2712 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2713 AbortIfNeeded();
2714 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2715 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2716 .Digest(Digest::NONE)
2717 .Authorization(TAG_APPLICATION_ID, "clientid")));
2718 AbortIfNeeded();
2719 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2720 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2721 .Digest(Digest::NONE)
2722 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2723 AbortIfNeeded();
2724 EXPECT_EQ(ErrorCode::OK,
2725 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2726 .Digest(Digest::NONE)
2727 .Authorization(TAG_APPLICATION_DATA, "appdata")
2728 .Authorization(TAG_APPLICATION_ID, "clientid")));
2729 AbortIfNeeded();
2730}
2731
2732/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002733 * SigningOperationsTest.EcdsaIncompatibleDigest
2734 *
2735 * Verifies that using an EC key requires compatible digest.
2736 */
2737TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2738 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2739 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002740 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002741 .Digest(Digest::NONE)
2742 .Digest(Digest::SHA1)
2743 .SetDefaultValidity()));
2744 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2745 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2746 AbortIfNeeded();
2747}
2748
2749/*
Selene Huang31ab4042020-04-29 04:22:39 -07002750 * SigningOperationsTest.AesEcbSign
2751 *
2752 * Verifies that attempts to use AES keys to sign fail in the correct way.
2753 */
2754TEST_P(SigningOperationsTest, AesEcbSign) {
2755 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2756 .Authorization(TAG_NO_AUTH_REQUIRED)
2757 .SigningKey()
2758 .AesEncryptionKey(128)
2759 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2760
2761 AuthorizationSet out_params;
2762 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2763 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2764 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2765 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2766}
2767
2768/*
2769 * SigningOperationsTest.HmacAllDigests
2770 *
2771 * Verifies that HMAC works with all digests.
2772 */
2773TEST_P(SigningOperationsTest, HmacAllDigests) {
2774 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2775 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2776 .Authorization(TAG_NO_AUTH_REQUIRED)
2777 .HmacKey(128)
2778 .Digest(digest)
2779 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2780 << "Failed to create HMAC key with digest " << digest;
2781 string message = "12345678901234567890123456789012";
2782 string signature = MacMessage(message, digest, 160);
2783 EXPECT_EQ(160U / 8U, signature.size())
2784 << "Failed to sign with HMAC key with digest " << digest;
2785 CheckedDeleteKey();
2786 }
2787}
2788
2789/*
2790 * SigningOperationsTest.HmacSha256TooLargeMacLength
2791 *
2792 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2793 * digest size.
2794 */
2795TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2796 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2797 .Authorization(TAG_NO_AUTH_REQUIRED)
2798 .HmacKey(128)
2799 .Digest(Digest::SHA_2_256)
2800 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2801 AuthorizationSet output_params;
2802 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2803 AuthorizationSetBuilder()
2804 .Digest(Digest::SHA_2_256)
2805 .Authorization(TAG_MAC_LENGTH, 264),
2806 &output_params));
2807}
2808
2809/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002810 * SigningOperationsTest.HmacSha256InvalidMacLength
2811 *
2812 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2813 * not a multiple of 8.
2814 */
2815TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2816 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2817 .Authorization(TAG_NO_AUTH_REQUIRED)
2818 .HmacKey(128)
2819 .Digest(Digest::SHA_2_256)
2820 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2821 AuthorizationSet output_params;
2822 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2823 AuthorizationSetBuilder()
2824 .Digest(Digest::SHA_2_256)
2825 .Authorization(TAG_MAC_LENGTH, 161),
2826 &output_params));
2827}
2828
2829/*
Selene Huang31ab4042020-04-29 04:22:39 -07002830 * SigningOperationsTest.HmacSha256TooSmallMacLength
2831 *
2832 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2833 * specified minimum MAC length.
2834 */
2835TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2836 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2837 .Authorization(TAG_NO_AUTH_REQUIRED)
2838 .HmacKey(128)
2839 .Digest(Digest::SHA_2_256)
2840 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2841 AuthorizationSet output_params;
2842 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2843 AuthorizationSetBuilder()
2844 .Digest(Digest::SHA_2_256)
2845 .Authorization(TAG_MAC_LENGTH, 120),
2846 &output_params));
2847}
2848
2849/*
2850 * SigningOperationsTest.HmacRfc4231TestCase3
2851 *
2852 * Validates against the test vectors from RFC 4231 test case 3.
2853 */
2854TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2855 string key(20, 0xaa);
2856 string message(50, 0xdd);
2857 uint8_t sha_224_expected[] = {
2858 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2859 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2860 };
2861 uint8_t sha_256_expected[] = {
2862 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2863 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2864 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2865 };
2866 uint8_t sha_384_expected[] = {
2867 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2868 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2869 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2870 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2871 };
2872 uint8_t sha_512_expected[] = {
2873 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2874 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2875 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2876 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2877 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2878 };
2879
2880 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2881 if (SecLevel() != SecurityLevel::STRONGBOX) {
2882 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2883 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2884 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2885 }
2886}
2887
2888/*
2889 * SigningOperationsTest.HmacRfc4231TestCase5
2890 *
2891 * Validates against the test vectors from RFC 4231 test case 5.
2892 */
2893TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2894 string key(20, 0x0c);
2895 string message = "Test With Truncation";
2896
2897 uint8_t sha_224_expected[] = {
2898 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2899 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2900 };
2901 uint8_t sha_256_expected[] = {
2902 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2903 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2904 };
2905 uint8_t sha_384_expected[] = {
2906 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2907 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2908 };
2909 uint8_t sha_512_expected[] = {
2910 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2911 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2912 };
2913
2914 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2915 if (SecLevel() != SecurityLevel::STRONGBOX) {
2916 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2917 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2918 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2919 }
2920}
2921
2922INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2923
2924typedef KeyMintAidlTestBase VerificationOperationsTest;
2925
2926/*
Selene Huang31ab4042020-04-29 04:22:39 -07002927 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2928 *
2929 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2930 */
2931TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2932 string key_material = "HelloThisIsAKey";
2933
2934 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002935 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002936 EXPECT_EQ(ErrorCode::OK,
2937 ImportKey(AuthorizationSetBuilder()
2938 .Authorization(TAG_NO_AUTH_REQUIRED)
2939 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2940 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2941 .Digest(Digest::SHA_2_256)
2942 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2943 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2944 EXPECT_EQ(ErrorCode::OK,
2945 ImportKey(AuthorizationSetBuilder()
2946 .Authorization(TAG_NO_AUTH_REQUIRED)
2947 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2948 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2949 .Digest(Digest::SHA_2_256)
2950 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2951 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2952
2953 string message = "This is a message.";
2954 string signature = SignMessage(
2955 signing_key, message,
2956 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2957
2958 // Signing key should not work.
2959 AuthorizationSet out_params;
2960 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2961 Begin(KeyPurpose::VERIFY, signing_key,
2962 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2963
2964 // Verification key should work.
2965 VerifyMessage(verification_key, message, signature,
2966 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2967
2968 CheckedDeleteKey(&signing_key);
2969 CheckedDeleteKey(&verification_key);
2970}
2971
2972INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2973
2974typedef KeyMintAidlTestBase ExportKeyTest;
2975
2976/*
2977 * ExportKeyTest.RsaUnsupportedKeyFormat
2978 *
2979 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2980 */
2981// TODO(seleneh) add ExportKey to GenerateKey
2982// check result
2983
2984class ImportKeyTest : public KeyMintAidlTestBase {
2985 public:
2986 template <TagType tag_type, Tag tag, typename ValueT>
2987 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2988 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002989 for (auto& entry : key_characteristics_) {
2990 if (entry.securityLevel == SecLevel()) {
2991 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2992 << "Tag " << tag << " with value " << expected
2993 << " not found at security level" << entry.securityLevel;
2994 } else {
2995 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
2996 << "Tag " << tag << " found at security level " << entry.securityLevel;
2997 }
Selene Huang31ab4042020-04-29 04:22:39 -07002998 }
2999 }
3000
3001 void CheckOrigin() {
3002 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003003 // Origin isn't a crypto param, but it always lives with them.
3004 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003005 }
3006};
3007
3008/*
3009 * ImportKeyTest.RsaSuccess
3010 *
3011 * Verifies that importing and using an RSA key pair works correctly.
3012 */
3013TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003014 uint32_t key_size;
3015 string key;
3016
3017 if (SecLevel() == SecurityLevel::STRONGBOX) {
3018 key_size = 2048;
3019 key = rsa_2048_key;
3020 } else {
3021 key_size = 1024;
3022 key = rsa_key;
3023 }
3024
Selene Huang31ab4042020-04-29 04:22:39 -07003025 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3026 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003027 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003028 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003029 .Padding(PaddingMode::RSA_PSS)
3030 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003031 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003032
3033 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003034 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003035 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3036 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3037 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3038 CheckOrigin();
3039
3040 string message(1024 / 8, 'a');
3041 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3042 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003043 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003044}
3045
3046/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003047 * ImportKeyTest.RsaSuccessWithoutParams
3048 *
3049 * Verifies that importing and using an RSA key pair without specifying parameters
3050 * works correctly.
3051 */
3052TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3053 uint32_t key_size;
3054 string key;
3055
3056 if (SecLevel() == SecurityLevel::STRONGBOX) {
3057 key_size = 2048;
3058 key = rsa_2048_key;
3059 } else {
3060 key_size = 1024;
3061 key = rsa_key;
3062 }
3063
3064 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3065 .Authorization(TAG_NO_AUTH_REQUIRED)
3066 .SigningKey()
3067 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3068 .Digest(Digest::SHA_2_256)
3069 .Padding(PaddingMode::RSA_PSS)
3070 .SetDefaultValidity(),
3071 KeyFormat::PKCS8, key));
3072
3073 // Key size and public exponent are determined from the imported key material.
3074 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3075 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3076
3077 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3078 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3079 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3080 CheckOrigin();
3081
3082 string message(1024 / 8, 'a');
3083 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3084 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003085 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003086}
3087
3088/*
Selene Huang31ab4042020-04-29 04:22:39 -07003089 * ImportKeyTest.RsaKeySizeMismatch
3090 *
3091 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3092 * correct way.
3093 */
3094TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3095 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3096 ImportKey(AuthorizationSetBuilder()
3097 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3098 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003099 .Padding(PaddingMode::NONE)
3100 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003101 KeyFormat::PKCS8, rsa_key));
3102}
3103
3104/*
3105 * ImportKeyTest.RsaPublicExponentMismatch
3106 *
3107 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3108 * fails in the correct way.
3109 */
3110TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3111 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3112 ImportKey(AuthorizationSetBuilder()
3113 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3114 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003115 .Padding(PaddingMode::NONE)
3116 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003117 KeyFormat::PKCS8, rsa_key));
3118}
3119
3120/*
3121 * ImportKeyTest.EcdsaSuccess
3122 *
3123 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3124 */
3125TEST_P(ImportKeyTest, EcdsaSuccess) {
3126 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3127 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003128 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003129 .Digest(Digest::SHA_2_256)
3130 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003131 KeyFormat::PKCS8, ec_256_key));
3132
3133 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003134 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3135 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3136
3137 CheckOrigin();
3138
3139 string message(32, 'a');
3140 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3141 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003142 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003143}
3144
3145/*
3146 * ImportKeyTest.EcdsaP256RFC5915Success
3147 *
3148 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3149 * correctly.
3150 */
3151TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3152 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3153 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003154 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003155 .Digest(Digest::SHA_2_256)
3156 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003157 KeyFormat::PKCS8, ec_256_key_rfc5915));
3158
3159 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003160 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3161 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3162
3163 CheckOrigin();
3164
3165 string message(32, 'a');
3166 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3167 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003168 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003169}
3170
3171/*
3172 * ImportKeyTest.EcdsaP256SEC1Success
3173 *
3174 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3175 */
3176TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3177 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3178 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003179 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003180 .Digest(Digest::SHA_2_256)
3181 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003182 KeyFormat::PKCS8, ec_256_key_sec1));
3183
3184 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003185 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3186 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3187
3188 CheckOrigin();
3189
3190 string message(32, 'a');
3191 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3192 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003193 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003194}
3195
3196/*
3197 * ImportKeyTest.Ecdsa521Success
3198 *
3199 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3200 */
3201TEST_P(ImportKeyTest, Ecdsa521Success) {
3202 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3203 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3204 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003205 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003206 .Digest(Digest::SHA_2_256)
3207 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003208 KeyFormat::PKCS8, ec_521_key));
3209
3210 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003211 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3212 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3213 CheckOrigin();
3214
3215 string message(32, 'a');
3216 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3217 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003218 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003219}
3220
3221/*
Selene Huang31ab4042020-04-29 04:22:39 -07003222 * ImportKeyTest.EcdsaCurveMismatch
3223 *
3224 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3225 * the correct way.
3226 */
3227TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3228 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3229 ImportKey(AuthorizationSetBuilder()
3230 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003231 .Digest(Digest::NONE)
3232 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003233 KeyFormat::PKCS8, ec_256_key));
3234}
3235
3236/*
3237 * ImportKeyTest.AesSuccess
3238 *
3239 * Verifies that importing and using an AES key works.
3240 */
3241TEST_P(ImportKeyTest, AesSuccess) {
3242 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3243 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3244 .Authorization(TAG_NO_AUTH_REQUIRED)
3245 .AesEncryptionKey(key.size() * 8)
3246 .EcbMode()
3247 .Padding(PaddingMode::PKCS7),
3248 KeyFormat::RAW, key));
3249
3250 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3251 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3252 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3253 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3254 CheckOrigin();
3255
3256 string message = "Hello World!";
3257 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3258 string ciphertext = EncryptMessage(message, params);
3259 string plaintext = DecryptMessage(ciphertext, params);
3260 EXPECT_EQ(message, plaintext);
3261}
3262
3263/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003264 * ImportKeyTest.AesFailure
3265 *
3266 * Verifies that importing an invalid AES key fails.
3267 */
3268TEST_P(ImportKeyTest, AesFailure) {
3269 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3270 uint32_t bitlen = key.size() * 8;
3271 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003272 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003273 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003274 .Authorization(TAG_NO_AUTH_REQUIRED)
3275 .AesEncryptionKey(key_size)
3276 .EcbMode()
3277 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003278 KeyFormat::RAW, key);
3279 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003280 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3281 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003282 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003283
3284 // Explicit key size matches that of the provided key, but it's not a valid size.
3285 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3286 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3287 ImportKey(AuthorizationSetBuilder()
3288 .Authorization(TAG_NO_AUTH_REQUIRED)
3289 .AesEncryptionKey(long_key.size() * 8)
3290 .EcbMode()
3291 .Padding(PaddingMode::PKCS7),
3292 KeyFormat::RAW, long_key));
3293 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3294 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3295 ImportKey(AuthorizationSetBuilder()
3296 .Authorization(TAG_NO_AUTH_REQUIRED)
3297 .AesEncryptionKey(short_key.size() * 8)
3298 .EcbMode()
3299 .Padding(PaddingMode::PKCS7),
3300 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003301}
3302
3303/*
3304 * ImportKeyTest.TripleDesSuccess
3305 *
3306 * Verifies that importing and using a 3DES key works.
3307 */
3308TEST_P(ImportKeyTest, TripleDesSuccess) {
3309 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3310 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3311 .Authorization(TAG_NO_AUTH_REQUIRED)
3312 .TripleDesEncryptionKey(168)
3313 .EcbMode()
3314 .Padding(PaddingMode::PKCS7),
3315 KeyFormat::RAW, key));
3316
3317 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3318 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3319 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3320 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3321 CheckOrigin();
3322
3323 string message = "Hello World!";
3324 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3325 string ciphertext = EncryptMessage(message, params);
3326 string plaintext = DecryptMessage(ciphertext, params);
3327 EXPECT_EQ(message, plaintext);
3328}
3329
3330/*
3331 * ImportKeyTest.TripleDesFailure
3332 *
3333 * Verifies that importing an invalid 3DES key fails.
3334 */
3335TEST_P(ImportKeyTest, TripleDesFailure) {
3336 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003337 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003338 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003339 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003340 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003341 .Authorization(TAG_NO_AUTH_REQUIRED)
3342 .TripleDesEncryptionKey(key_size)
3343 .EcbMode()
3344 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003345 KeyFormat::RAW, key);
3346 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003347 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3348 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003349 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003350 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003351 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003352 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3353 ImportKey(AuthorizationSetBuilder()
3354 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003355 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003356 .EcbMode()
3357 .Padding(PaddingMode::PKCS7),
3358 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003359 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003360 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3361 ImportKey(AuthorizationSetBuilder()
3362 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003363 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003364 .EcbMode()
3365 .Padding(PaddingMode::PKCS7),
3366 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003367}
3368
3369/*
3370 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003371 *
3372 * Verifies that importing and using an HMAC key works.
3373 */
3374TEST_P(ImportKeyTest, HmacKeySuccess) {
3375 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3376 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3377 .Authorization(TAG_NO_AUTH_REQUIRED)
3378 .HmacKey(key.size() * 8)
3379 .Digest(Digest::SHA_2_256)
3380 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3381 KeyFormat::RAW, key));
3382
3383 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3384 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3385 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3386 CheckOrigin();
3387
3388 string message = "Hello World!";
3389 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3390 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3391}
3392
3393INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3394
3395auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003396 // IKeyMintDevice.aidl
3397 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3398 "020100" // INTEGER length 1 value 0x00 (version)
3399 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3400 "934bf94e2aa28a3f83c9f79297250262"
3401 "fbe3276b5a1c91159bbfa3ef8957aac8"
3402 "4b59b30b455a79c2973480823d8b3863"
3403 "c3deef4a8e243590268d80e18751a0e1"
3404 "30f67ce6a1ace9f79b95e097474febc9"
3405 "81195b1d13a69086c0863f66a7b7fdb4"
3406 "8792227b1ac5e2489febdf087ab54864"
3407 "83033a6f001ca5d1ec1e27f5c30f4cec"
3408 "2642074a39ae68aee552e196627a8e3d"
3409 "867e67a8c01b11e75f13cca0a97ab668"
3410 "b50cda07a8ecb7cd8e3dd7009c963653"
3411 "4f6f239cffe1fc8daa466f78b676c711"
3412 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3413 "99b801597d5220e307eaa5bee507fb94"
3414 "d1fa69f9e519b2de315bac92c36f2ea1"
3415 "fa1df4478c0ddedeae8c70e0233cd098"
3416 "040c" // OCTET STRING length 0x0c (initializationVector)
3417 "d796b02c370f1fa4cc0124f1"
3418 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3419 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3420 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3421 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3422 "3106" // SET length 0x06
3423 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3424 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3425 // } end SET
3426 // } end [1]
3427 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3428 "020120" // INTEGER length 1 value 0x20 (AES)
3429 // } end [2]
3430 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3431 "02020100" // INTEGER length 2 value 0x100
3432 // } end [3]
3433 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3434 "3103" // SET length 0x03 {
3435 "020101" // INTEGER length 1 value 0x01 (ECB)
3436 // } end SET
3437 // } end [4]
3438 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3439 "3103" // SET length 0x03 {
3440 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3441 // } end SET
3442 // } end [5]
3443 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3444 // (noAuthRequired)
3445 "0500" // NULL
3446 // } end [503]
3447 // } end SEQUENCE (AuthorizationList)
3448 // } end SEQUENCE (KeyDescription)
3449 "0420" // OCTET STRING length 0x20 (encryptedKey)
3450 "ccd540855f833a5e1480bfd2d36faf3a"
3451 "eee15df5beabe2691bc82dde2a7aa910"
3452 "0410" // OCTET STRING length 0x10 (tag)
3453 "64c9f689c60ff6223ab6e6999e0eb6e5"
3454 // } SEQUENCE (SecureKeyWrapper)
3455);
Selene Huang31ab4042020-04-29 04:22:39 -07003456
3457auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003458 // IKeyMintDevice.aidl
3459 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3460 "020100" // INTEGER length 1 value 0x00 (version)
3461 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3462 "aad93ed5924f283b4bb5526fbe7a1412"
3463 "f9d9749ec30db9062b29e574a8546f33"
3464 "c88732452f5b8e6a391ee76c39ed1712"
3465 "c61d8df6213dec1cffbc17a8c6d04c7b"
3466 "30893d8daa9b2015213e219468215532"
3467 "07f8f9931c4caba23ed3bee28b36947e"
3468 "47f10e0a5c3dc51c988a628daad3e5e1"
3469 "f4005e79c2d5a96c284b4b8d7e4948f3"
3470 "31e5b85dd5a236f85579f3ea1d1b8484"
3471 "87470bdb0ab4f81a12bee42c99fe0df4"
3472 "bee3759453e69ad1d68a809ce06b949f"
3473 "7694a990429b2fe81e066ff43e56a216"
3474 "02db70757922a4bcc23ab89f1e35da77"
3475 "586775f423e519c2ea394caf48a28d0c"
3476 "8020f1dcf6b3a68ec246f615ae96dae9"
3477 "a079b1f6eb959033c1af5c125fd94168"
3478 "040c" // OCTET STRING length 0x0c (initializationVector)
3479 "6d9721d08589581ab49204a3"
3480 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3481 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3482 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3483 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3484 "3106" // SET length 0x06
3485 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3486 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3487 // } end SET
3488 // } end [1]
3489 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3490 "020120" // INTEGER length 1 value 0x20 (AES)
3491 // } end [2]
3492 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3493 "02020100" // INTEGER length 2 value 0x100
3494 // } end [3]
3495 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3496 "3103" // SET length 0x03 {
3497 "020101" // INTEGER length 1 value 0x01 (ECB)
3498 // } end SET
3499 // } end [4]
3500 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3501 "3103" // SET length 0x03 {
3502 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3503 // } end SET
3504 // } end [5]
3505 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3506 // (noAuthRequired)
3507 "0500" // NULL
3508 // } end [503]
3509 // } end SEQUENCE (AuthorizationList)
3510 // } end SEQUENCE (KeyDescription)
3511 "0420" // OCTET STRING length 0x20 (encryptedKey)
3512 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3513 "c20d1f99a9a024a76f35c8e2cab9b68d"
3514 "0410" // OCTET STRING length 0x10 (tag)
3515 "2560c70109ae67c030f00b98b512a670"
3516 // } SEQUENCE (SecureKeyWrapper)
3517);
Selene Huang31ab4042020-04-29 04:22:39 -07003518
3519auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003520 // RFC 5208 s5
3521 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3522 "020100" // INTEGER length 1 value 0x00 (version)
3523 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3524 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3525 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3526 "0500" // NULL (parameters)
3527 // } SEQUENCE (AlgorithmIdentifier)
3528 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3529 // RFC 8017 A.1.2
3530 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3531 "020100" // INTEGER length 1 value 0x00 (version)
3532 "02820101" // INTEGER length 0x0101 (modulus) value...
3533 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3534 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3535 "7b06e673a837313d56b1c725150a3fef" // 0x30
3536 "86acbddc41bb759c2854eae32d35841e" // 0x40
3537 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3538 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3539 "312d7bd5921ffaea1347c157406fef71" // 0x70
3540 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3541 "f4645c11f5c1374c3886427411c44979" // 0x90
3542 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3543 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3544 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3545 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3546 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3547 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3548 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3549 "55" // 0x101
3550 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3551 "02820100" // INTEGER length 0x100 (privateExponent) value...
3552 "431447b6251908112b1ee76f99f3711a" // 0x10
3553 "52b6630960046c2de70de188d833f8b8" // 0x20
3554 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3555 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3556 "e710b630a03adc683b5d2c43080e52be" // 0x50
3557 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3558 "822bccff087d63c940ba8a45f670feb2" // 0x70
3559 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3560 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3561 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3562 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3563 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3564 "52659d5a5ba05b663737a8696281865b" // 0xd0
3565 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3566 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3567 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3568 "028181" // INTEGER length 0x81 (prime1) value...
3569 "00de392e18d682c829266cc3454e1d61" // 0x10
3570 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3571 "ff841be5bac82a164c5970007047b8c5" // 0x30
3572 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3573 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3574 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3575 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3576 "9e91346130748a6e3c124f9149d71c74" // 0x80
3577 "35"
3578 "028181" // INTEGER length 0x81 (prime2) value...
3579 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3580 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3581 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3582 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3583 "9ed39a2d934c880440aed8832f984316" // 0x50
3584 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3585 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3586 "b880677c068e1be936e81288815252a8" // 0x80
3587 "a1"
3588 "028180" // INTEGER length 0x80 (exponent1) value...
3589 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3590 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3591 "5a063212a4f105a3764743e53281988a" // 0x30
3592 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3593 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3594 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3595 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3596 "4719d6e2b9439823719cd08bcd031781" // 0x80
3597 "028181" // INTEGER length 0x81 (exponent2) value...
3598 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3599 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3600 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3601 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3602 "1254186af30b22c10582a8a43e34fe94" // 0x50
3603 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3604 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3605 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3606 "61"
3607 "028181" // INTEGER length 0x81 (coefficient) value...
3608 "00c931617c77829dfb1270502be9195c" // 0x10
3609 "8f2830885f57dba869536811e6864236" // 0x20
3610 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3611 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3612 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3613 "959356210723287b0affcc9f727044d4" // 0x60
3614 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3615 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3616 "22"
3617 // } SEQUENCE
3618 // } SEQUENCE ()
3619);
Selene Huang31ab4042020-04-29 04:22:39 -07003620
3621string zero_masking_key =
3622 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3623string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3624
3625class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3626
3627TEST_P(ImportWrappedKeyTest, Success) {
3628 auto wrapping_key_desc = AuthorizationSetBuilder()
3629 .RsaEncryptionKey(2048, 65537)
3630 .Digest(Digest::SHA_2_256)
3631 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003632 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3633 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003634
3635 ASSERT_EQ(ErrorCode::OK,
3636 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3637 AuthorizationSetBuilder()
3638 .Digest(Digest::SHA_2_256)
3639 .Padding(PaddingMode::RSA_OAEP)));
3640
3641 string message = "Hello World!";
3642 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3643 string ciphertext = EncryptMessage(message, params);
3644 string plaintext = DecryptMessage(ciphertext, params);
3645 EXPECT_EQ(message, plaintext);
3646}
3647
David Drysdaled2cc8c22021-04-15 13:29:45 +01003648/*
3649 * ImportWrappedKeyTest.SuccessSidsIgnored
3650 *
3651 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3652 * include Tag:USER_SECURE_ID.
3653 */
3654TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3655 auto wrapping_key_desc = AuthorizationSetBuilder()
3656 .RsaEncryptionKey(2048, 65537)
3657 .Digest(Digest::SHA_2_256)
3658 .Padding(PaddingMode::RSA_OAEP)
3659 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3660 .SetDefaultValidity();
3661
3662 int64_t password_sid = 42;
3663 int64_t biometric_sid = 24;
3664 ASSERT_EQ(ErrorCode::OK,
3665 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3666 AuthorizationSetBuilder()
3667 .Digest(Digest::SHA_2_256)
3668 .Padding(PaddingMode::RSA_OAEP),
3669 password_sid, biometric_sid));
3670
3671 string message = "Hello World!";
3672 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3673 string ciphertext = EncryptMessage(message, params);
3674 string plaintext = DecryptMessage(ciphertext, params);
3675 EXPECT_EQ(message, plaintext);
3676}
3677
Selene Huang31ab4042020-04-29 04:22:39 -07003678TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3679 auto wrapping_key_desc = AuthorizationSetBuilder()
3680 .RsaEncryptionKey(2048, 65537)
3681 .Digest(Digest::SHA_2_256)
3682 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003683 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3684 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003685
3686 ASSERT_EQ(ErrorCode::OK,
3687 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3688 AuthorizationSetBuilder()
3689 .Digest(Digest::SHA_2_256)
3690 .Padding(PaddingMode::RSA_OAEP)));
3691}
3692
3693TEST_P(ImportWrappedKeyTest, WrongMask) {
3694 auto wrapping_key_desc = AuthorizationSetBuilder()
3695 .RsaEncryptionKey(2048, 65537)
3696 .Digest(Digest::SHA_2_256)
3697 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003698 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3699 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003700
3701 ASSERT_EQ(
3702 ErrorCode::VERIFICATION_FAILED,
3703 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3704 AuthorizationSetBuilder()
3705 .Digest(Digest::SHA_2_256)
3706 .Padding(PaddingMode::RSA_OAEP)));
3707}
3708
3709TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3710 auto wrapping_key_desc = AuthorizationSetBuilder()
3711 .RsaEncryptionKey(2048, 65537)
3712 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003713 .Padding(PaddingMode::RSA_OAEP)
3714 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003715
3716 ASSERT_EQ(
3717 ErrorCode::INCOMPATIBLE_PURPOSE,
3718 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3719 AuthorizationSetBuilder()
3720 .Digest(Digest::SHA_2_256)
3721 .Padding(PaddingMode::RSA_OAEP)));
3722}
3723
David Drysdaled2cc8c22021-04-15 13:29:45 +01003724TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3725 auto wrapping_key_desc = AuthorizationSetBuilder()
3726 .RsaEncryptionKey(2048, 65537)
3727 .Digest(Digest::SHA_2_256)
3728 .Padding(PaddingMode::RSA_PSS)
3729 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3730 .SetDefaultValidity();
3731
3732 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3733 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3734 AuthorizationSetBuilder()
3735 .Digest(Digest::SHA_2_256)
3736 .Padding(PaddingMode::RSA_OAEP)));
3737}
3738
3739TEST_P(ImportWrappedKeyTest, WrongDigest) {
3740 auto wrapping_key_desc = AuthorizationSetBuilder()
3741 .RsaEncryptionKey(2048, 65537)
3742 .Digest(Digest::SHA_2_512)
3743 .Padding(PaddingMode::RSA_OAEP)
3744 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3745 .SetDefaultValidity();
3746
3747 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3748 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3749 AuthorizationSetBuilder()
3750 .Digest(Digest::SHA_2_256)
3751 .Padding(PaddingMode::RSA_OAEP)));
3752}
3753
Selene Huang31ab4042020-04-29 04:22:39 -07003754INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3755
3756typedef KeyMintAidlTestBase EncryptionOperationsTest;
3757
3758/*
3759 * EncryptionOperationsTest.RsaNoPaddingSuccess
3760 *
David Drysdale59cae642021-05-12 13:52:03 +01003761 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003762 */
3763TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003764 for (uint64_t exponent : {3, 65537}) {
3765 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3766 .Authorization(TAG_NO_AUTH_REQUIRED)
3767 .RsaEncryptionKey(2048, exponent)
3768 .Padding(PaddingMode::NONE)
3769 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003770
David Drysdaled2cc8c22021-04-15 13:29:45 +01003771 string message = string(2048 / 8, 'a');
3772 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003773 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003774 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003775
David Drysdale59cae642021-05-12 13:52:03 +01003776 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003777 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003778
David Drysdaled2cc8c22021-04-15 13:29:45 +01003779 // Unpadded RSA is deterministic
3780 EXPECT_EQ(ciphertext1, ciphertext2);
3781
3782 CheckedDeleteKey();
3783 }
Selene Huang31ab4042020-04-29 04:22:39 -07003784}
3785
3786/*
3787 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3788 *
David Drysdale59cae642021-05-12 13:52:03 +01003789 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003790 */
3791TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3792 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3793 .Authorization(TAG_NO_AUTH_REQUIRED)
3794 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003795 .Padding(PaddingMode::NONE)
3796 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003797
3798 string message = "1";
3799 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3800
David Drysdale59cae642021-05-12 13:52:03 +01003801 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003802 EXPECT_EQ(2048U / 8, ciphertext.size());
3803
3804 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3805 string plaintext = DecryptMessage(ciphertext, params);
3806
3807 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07003808}
3809
3810/*
Selene Huang31ab4042020-04-29 04:22:39 -07003811 * EncryptionOperationsTest.RsaOaepSuccess
3812 *
David Drysdale59cae642021-05-12 13:52:03 +01003813 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07003814 */
3815TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3816 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3817
3818 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01003819 ASSERT_EQ(ErrorCode::OK,
3820 GenerateKey(AuthorizationSetBuilder()
3821 .Authorization(TAG_NO_AUTH_REQUIRED)
3822 .RsaEncryptionKey(key_size, 65537)
3823 .Padding(PaddingMode::RSA_OAEP)
3824 .Digest(digests)
3825 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
3826 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003827
3828 string message = "Hello";
3829
3830 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01003831 SCOPED_TRACE(testing::Message() << "digest-" << digest);
3832
3833 auto params = AuthorizationSetBuilder()
3834 .Digest(digest)
3835 .Padding(PaddingMode::RSA_OAEP)
3836 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
3837 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003838 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3839 EXPECT_EQ(key_size / 8, ciphertext1.size());
3840
David Drysdale59cae642021-05-12 13:52:03 +01003841 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003842 EXPECT_EQ(key_size / 8, ciphertext2.size());
3843
3844 // OAEP randomizes padding so every result should be different (with astronomically high
3845 // probability).
3846 EXPECT_NE(ciphertext1, ciphertext2);
3847
3848 string plaintext1 = DecryptMessage(ciphertext1, params);
3849 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3850 string plaintext2 = DecryptMessage(ciphertext2, params);
3851 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3852
3853 // Decrypting corrupted ciphertext should fail.
3854 size_t offset_to_corrupt = random() % ciphertext1.size();
3855 char corrupt_byte;
3856 do {
3857 corrupt_byte = static_cast<char>(random() % 256);
3858 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3859 ciphertext1[offset_to_corrupt] = corrupt_byte;
3860
3861 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3862 string result;
3863 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3864 EXPECT_EQ(0U, result.size());
3865 }
3866}
3867
3868/*
3869 * EncryptionOperationsTest.RsaOaepInvalidDigest
3870 *
David Drysdale59cae642021-05-12 13:52:03 +01003871 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07003872 * without a digest.
3873 */
3874TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3875 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3876 .Authorization(TAG_NO_AUTH_REQUIRED)
3877 .RsaEncryptionKey(2048, 65537)
3878 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003879 .Digest(Digest::NONE)
3880 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003881
3882 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003883 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07003884}
3885
3886/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003887 * EncryptionOperationsTest.RsaOaepInvalidPadding
3888 *
David Drysdale59cae642021-05-12 13:52:03 +01003889 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01003890 * with a padding value that is only suitable for signing/verifying.
3891 */
3892TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3893 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3894 .Authorization(TAG_NO_AUTH_REQUIRED)
3895 .RsaEncryptionKey(2048, 65537)
3896 .Padding(PaddingMode::RSA_PSS)
3897 .Digest(Digest::NONE)
3898 .SetDefaultValidity()));
3899
3900 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003901 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003902}
3903
3904/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003905 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003906 *
David Drysdale59cae642021-05-12 13:52:03 +01003907 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07003908 * with a different digest than was used to encrypt.
3909 */
3910TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3911 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3912
3913 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3914 .Authorization(TAG_NO_AUTH_REQUIRED)
3915 .RsaEncryptionKey(1024, 65537)
3916 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003917 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3918 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003919 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01003920 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07003921 message,
3922 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3923
3924 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3925 .Digest(Digest::SHA_2_256)
3926 .Padding(PaddingMode::RSA_OAEP)));
3927 string result;
3928 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3929 EXPECT_EQ(0U, result.size());
3930}
3931
3932/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003933 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3934 *
David Drysdale59cae642021-05-12 13:52:03 +01003935 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003936 * digests.
3937 */
3938TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3939 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3940
3941 size_t key_size = 2048; // Need largish key for SHA-512 test.
3942 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3943 .OaepMGFDigest(digests)
3944 .Authorization(TAG_NO_AUTH_REQUIRED)
3945 .RsaEncryptionKey(key_size, 65537)
3946 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003947 .Digest(Digest::SHA_2_256)
3948 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003949
3950 string message = "Hello";
3951
3952 for (auto digest : digests) {
3953 auto params = AuthorizationSetBuilder()
3954 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
3955 .Digest(Digest::SHA_2_256)
3956 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01003957 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003958 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3959 EXPECT_EQ(key_size / 8, ciphertext1.size());
3960
David Drysdale59cae642021-05-12 13:52:03 +01003961 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003962 EXPECT_EQ(key_size / 8, ciphertext2.size());
3963
3964 // OAEP randomizes padding so every result should be different (with astronomically high
3965 // probability).
3966 EXPECT_NE(ciphertext1, ciphertext2);
3967
3968 string plaintext1 = DecryptMessage(ciphertext1, params);
3969 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3970 string plaintext2 = DecryptMessage(ciphertext2, params);
3971 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3972
3973 // Decrypting corrupted ciphertext should fail.
3974 size_t offset_to_corrupt = random() % ciphertext1.size();
3975 char corrupt_byte;
3976 do {
3977 corrupt_byte = static_cast<char>(random() % 256);
3978 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3979 ciphertext1[offset_to_corrupt] = corrupt_byte;
3980
3981 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3982 string result;
3983 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3984 EXPECT_EQ(0U, result.size());
3985 }
3986}
3987
3988/*
3989 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
3990 *
David Drysdale59cae642021-05-12 13:52:03 +01003991 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003992 * with incompatible MGF digest.
3993 */
3994TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
3995 ASSERT_EQ(ErrorCode::OK,
3996 GenerateKey(AuthorizationSetBuilder()
3997 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3998 .Authorization(TAG_NO_AUTH_REQUIRED)
3999 .RsaEncryptionKey(2048, 65537)
4000 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004001 .Digest(Digest::SHA_2_256)
4002 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004003 string message = "Hello World!";
4004
4005 auto params = AuthorizationSetBuilder()
4006 .Padding(PaddingMode::RSA_OAEP)
4007 .Digest(Digest::SHA_2_256)
4008 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004009 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004010}
4011
4012/*
4013 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4014 *
4015 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4016 * with unsupported MGF digest.
4017 */
4018TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4019 ASSERT_EQ(ErrorCode::OK,
4020 GenerateKey(AuthorizationSetBuilder()
4021 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4022 .Authorization(TAG_NO_AUTH_REQUIRED)
4023 .RsaEncryptionKey(2048, 65537)
4024 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004025 .Digest(Digest::SHA_2_256)
4026 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004027 string message = "Hello World!";
4028
4029 auto params = AuthorizationSetBuilder()
4030 .Padding(PaddingMode::RSA_OAEP)
4031 .Digest(Digest::SHA_2_256)
4032 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004033 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004034}
4035
4036/*
Selene Huang31ab4042020-04-29 04:22:39 -07004037 * EncryptionOperationsTest.RsaPkcs1Success
4038 *
4039 * Verifies that RSA PKCS encryption/decrypts works.
4040 */
4041TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4042 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4043 .Authorization(TAG_NO_AUTH_REQUIRED)
4044 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004045 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4046 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004047
4048 string message = "Hello World!";
4049 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01004050 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004051 EXPECT_EQ(2048U / 8, ciphertext1.size());
4052
David Drysdale59cae642021-05-12 13:52:03 +01004053 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004054 EXPECT_EQ(2048U / 8, ciphertext2.size());
4055
4056 // PKCS1 v1.5 randomizes padding so every result should be different.
4057 EXPECT_NE(ciphertext1, ciphertext2);
4058
4059 string plaintext = DecryptMessage(ciphertext1, params);
4060 EXPECT_EQ(message, plaintext);
4061
4062 // Decrypting corrupted ciphertext should fail.
4063 size_t offset_to_corrupt = random() % ciphertext1.size();
4064 char corrupt_byte;
4065 do {
4066 corrupt_byte = static_cast<char>(random() % 256);
4067 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4068 ciphertext1[offset_to_corrupt] = corrupt_byte;
4069
4070 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4071 string result;
4072 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4073 EXPECT_EQ(0U, result.size());
4074}
4075
4076/*
Selene Huang31ab4042020-04-29 04:22:39 -07004077 * EncryptionOperationsTest.EcdsaEncrypt
4078 *
4079 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4080 */
4081TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4082 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4083 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004084 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004085 .Digest(Digest::NONE)
4086 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004087 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4088 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4089 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4090}
4091
4092/*
4093 * EncryptionOperationsTest.HmacEncrypt
4094 *
4095 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4096 */
4097TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4098 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4099 .Authorization(TAG_NO_AUTH_REQUIRED)
4100 .HmacKey(128)
4101 .Digest(Digest::SHA_2_256)
4102 .Padding(PaddingMode::NONE)
4103 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4104 auto params = AuthorizationSetBuilder()
4105 .Digest(Digest::SHA_2_256)
4106 .Padding(PaddingMode::NONE)
4107 .Authorization(TAG_MAC_LENGTH, 128);
4108 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4109 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4110}
4111
4112/*
4113 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4114 *
4115 * Verifies that AES ECB mode works.
4116 */
4117TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4118 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4119 .Authorization(TAG_NO_AUTH_REQUIRED)
4120 .AesEncryptionKey(128)
4121 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4122 .Padding(PaddingMode::NONE)));
4123
4124 ASSERT_GT(key_blob_.size(), 0U);
4125 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4126
4127 // Two-block message.
4128 string message = "12345678901234567890123456789012";
4129 string ciphertext1 = EncryptMessage(message, params);
4130 EXPECT_EQ(message.size(), ciphertext1.size());
4131
4132 string ciphertext2 = EncryptMessage(string(message), params);
4133 EXPECT_EQ(message.size(), ciphertext2.size());
4134
4135 // ECB is deterministic.
4136 EXPECT_EQ(ciphertext1, ciphertext2);
4137
4138 string plaintext = DecryptMessage(ciphertext1, params);
4139 EXPECT_EQ(message, plaintext);
4140}
4141
4142/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004143 * EncryptionOperationsTest.AesEcbUnknownTag
4144 *
4145 * Verifies that AES ECB operations ignore unknown tags.
4146 */
4147TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4148 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4149 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4150 KeyParameter unknown_param;
4151 unknown_param.tag = unknown_tag;
4152
4153 vector<KeyCharacteristics> key_characteristics;
4154 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4155 .Authorization(TAG_NO_AUTH_REQUIRED)
4156 .AesEncryptionKey(128)
4157 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4158 .Padding(PaddingMode::NONE)
4159 .Authorization(unknown_param),
4160 &key_blob_, &key_characteristics));
4161 ASSERT_GT(key_blob_.size(), 0U);
4162
4163 // Unknown tags should not be returned in key characteristics.
4164 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4165 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4166 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4167 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4168
4169 // Encrypt without mentioning the unknown parameter.
4170 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4171 string message = "12345678901234567890123456789012";
4172 string ciphertext = EncryptMessage(message, params);
4173 EXPECT_EQ(message.size(), ciphertext.size());
4174
4175 // Decrypt including the unknown parameter.
4176 auto decrypt_params = AuthorizationSetBuilder()
4177 .BlockMode(BlockMode::ECB)
4178 .Padding(PaddingMode::NONE)
4179 .Authorization(unknown_param);
4180 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4181 EXPECT_EQ(message, plaintext);
4182}
4183
4184/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004185 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004186 *
4187 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4188 */
4189TEST_P(EncryptionOperationsTest, AesWrongMode) {
4190 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4191 .Authorization(TAG_NO_AUTH_REQUIRED)
4192 .AesEncryptionKey(128)
4193 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4194 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004195 ASSERT_GT(key_blob_.size(), 0U);
4196
Selene Huang31ab4042020-04-29 04:22:39 -07004197 EXPECT_EQ(
4198 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4199 Begin(KeyPurpose::ENCRYPT,
4200 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4201}
4202
4203/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004204 * EncryptionOperationsTest.AesWrongPadding
4205 *
4206 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4207 */
4208TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4209 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4210 .Authorization(TAG_NO_AUTH_REQUIRED)
4211 .AesEncryptionKey(128)
4212 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4213 .Padding(PaddingMode::NONE)));
4214 ASSERT_GT(key_blob_.size(), 0U);
4215
4216 EXPECT_EQ(
4217 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4218 Begin(KeyPurpose::ENCRYPT,
4219 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4220}
4221
4222/*
4223 * EncryptionOperationsTest.AesInvalidParams
4224 *
4225 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4226 */
4227TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4228 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4229 .Authorization(TAG_NO_AUTH_REQUIRED)
4230 .AesEncryptionKey(128)
4231 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4232 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4233 .Padding(PaddingMode::NONE)
4234 .Padding(PaddingMode::PKCS7)));
4235 ASSERT_GT(key_blob_.size(), 0U);
4236
4237 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4238 .BlockMode(BlockMode::CBC)
4239 .BlockMode(BlockMode::ECB)
4240 .Padding(PaddingMode::NONE));
4241 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4242 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4243
4244 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4245 .BlockMode(BlockMode::ECB)
4246 .Padding(PaddingMode::NONE)
4247 .Padding(PaddingMode::PKCS7));
4248 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4249 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4250}
4251
4252/*
Selene Huang31ab4042020-04-29 04:22:39 -07004253 * EncryptionOperationsTest.AesWrongPurpose
4254 *
4255 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4256 * specified.
4257 */
4258TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4259 auto err = GenerateKey(AuthorizationSetBuilder()
4260 .Authorization(TAG_NO_AUTH_REQUIRED)
4261 .AesKey(128)
4262 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4263 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4264 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4265 .Padding(PaddingMode::NONE));
4266 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4267 ASSERT_GT(key_blob_.size(), 0U);
4268
4269 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4270 .BlockMode(BlockMode::GCM)
4271 .Padding(PaddingMode::NONE)
4272 .Authorization(TAG_MAC_LENGTH, 128));
4273 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4274
4275 CheckedDeleteKey();
4276
4277 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4278 .Authorization(TAG_NO_AUTH_REQUIRED)
4279 .AesKey(128)
4280 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4281 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4282 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4283 .Padding(PaddingMode::NONE)));
4284
4285 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4286 .BlockMode(BlockMode::GCM)
4287 .Padding(PaddingMode::NONE)
4288 .Authorization(TAG_MAC_LENGTH, 128));
4289 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4290}
4291
4292/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004293 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004294 *
4295 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4296 * multiple of the block size and no padding is specified.
4297 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004298TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4299 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4300 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4301 .Authorization(TAG_NO_AUTH_REQUIRED)
4302 .AesEncryptionKey(128)
4303 .Authorization(TAG_BLOCK_MODE, blockMode)
4304 .Padding(PaddingMode::NONE)));
4305 // Message is slightly shorter than two blocks.
4306 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004307
David Drysdaled2cc8c22021-04-15 13:29:45 +01004308 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4309 AuthorizationSet out_params;
4310 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4311 string ciphertext;
4312 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4313 EXPECT_EQ(0U, ciphertext.size());
4314
4315 CheckedDeleteKey();
4316 }
Selene Huang31ab4042020-04-29 04:22:39 -07004317}
4318
4319/*
4320 * EncryptionOperationsTest.AesEcbPkcs7Padding
4321 *
4322 * Verifies that AES PKCS7 padding works for any message length.
4323 */
4324TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4325 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4326 .Authorization(TAG_NO_AUTH_REQUIRED)
4327 .AesEncryptionKey(128)
4328 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4329 .Padding(PaddingMode::PKCS7)));
4330
4331 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4332
4333 // Try various message lengths; all should work.
4334 for (size_t i = 0; i < 32; ++i) {
4335 string message(i, 'a');
4336 string ciphertext = EncryptMessage(message, params);
4337 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4338 string plaintext = DecryptMessage(ciphertext, params);
4339 EXPECT_EQ(message, plaintext);
4340 }
4341}
4342
4343/*
4344 * EncryptionOperationsTest.AesEcbWrongPadding
4345 *
4346 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4347 * specified.
4348 */
4349TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4350 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4351 .Authorization(TAG_NO_AUTH_REQUIRED)
4352 .AesEncryptionKey(128)
4353 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4354 .Padding(PaddingMode::NONE)));
4355
4356 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4357
4358 // Try various message lengths; all should fail
4359 for (size_t i = 0; i < 32; ++i) {
4360 string message(i, 'a');
4361 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4362 }
4363}
4364
4365/*
4366 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4367 *
4368 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4369 */
4370TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4371 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4372 .Authorization(TAG_NO_AUTH_REQUIRED)
4373 .AesEncryptionKey(128)
4374 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4375 .Padding(PaddingMode::PKCS7)));
4376
4377 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4378
4379 string message = "a";
4380 string ciphertext = EncryptMessage(message, params);
4381 EXPECT_EQ(16U, ciphertext.size());
4382 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07004383
Seth Moore7a55ae32021-06-23 14:28:11 -07004384 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
4385 ++ciphertext[ciphertext.size() / 2];
4386
4387 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4388 string plaintext;
4389 ErrorCode error = Finish(message, &plaintext);
4390 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
4391 // This is the expected error, we can exit the test now.
4392 return;
4393 } else {
4394 // Very small chance we got valid decryption, so try again.
4395 ASSERT_EQ(error, ErrorCode::OK);
4396 }
4397 }
4398 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07004399}
4400
4401vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4402 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004403 EXPECT_TRUE(iv);
4404 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004405}
4406
4407/*
4408 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4409 *
4410 * Verifies that AES CTR mode works.
4411 */
4412TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4413 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4414 .Authorization(TAG_NO_AUTH_REQUIRED)
4415 .AesEncryptionKey(128)
4416 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4417 .Padding(PaddingMode::NONE)));
4418
4419 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4420
4421 string message = "123";
4422 AuthorizationSet out_params;
4423 string ciphertext1 = EncryptMessage(message, params, &out_params);
4424 vector<uint8_t> iv1 = CopyIv(out_params);
4425 EXPECT_EQ(16U, iv1.size());
4426
4427 EXPECT_EQ(message.size(), ciphertext1.size());
4428
4429 out_params.Clear();
4430 string ciphertext2 = EncryptMessage(message, params, &out_params);
4431 vector<uint8_t> iv2 = CopyIv(out_params);
4432 EXPECT_EQ(16U, iv2.size());
4433
4434 // IVs should be random, so ciphertexts should differ.
4435 EXPECT_NE(ciphertext1, ciphertext2);
4436
4437 auto params_iv1 =
4438 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4439 auto params_iv2 =
4440 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4441
4442 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4443 EXPECT_EQ(message, plaintext);
4444 plaintext = DecryptMessage(ciphertext2, params_iv2);
4445 EXPECT_EQ(message, plaintext);
4446
4447 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4448 plaintext = DecryptMessage(ciphertext1, params_iv2);
4449 EXPECT_NE(message, plaintext);
4450 plaintext = DecryptMessage(ciphertext2, params_iv1);
4451 EXPECT_NE(message, plaintext);
4452}
4453
4454/*
4455 * EncryptionOperationsTest.AesIncremental
4456 *
4457 * Verifies that AES works, all modes, when provided data in various size increments.
4458 */
4459TEST_P(EncryptionOperationsTest, AesIncremental) {
4460 auto block_modes = {
4461 BlockMode::ECB,
4462 BlockMode::CBC,
4463 BlockMode::CTR,
4464 BlockMode::GCM,
4465 };
4466
4467 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4468 .Authorization(TAG_NO_AUTH_REQUIRED)
4469 .AesEncryptionKey(128)
4470 .BlockMode(block_modes)
4471 .Padding(PaddingMode::NONE)
4472 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4473
4474 for (int increment = 1; increment <= 240; ++increment) {
4475 for (auto block_mode : block_modes) {
4476 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004477 auto params =
4478 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4479 if (block_mode == BlockMode::GCM) {
4480 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4481 }
Selene Huang31ab4042020-04-29 04:22:39 -07004482
4483 AuthorizationSet output_params;
4484 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4485
4486 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004487 string to_send;
4488 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004489 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004490 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004491 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4492 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004493
4494 switch (block_mode) {
4495 case BlockMode::GCM:
4496 EXPECT_EQ(message.size() + 16, ciphertext.size());
4497 break;
4498 case BlockMode::CTR:
4499 EXPECT_EQ(message.size(), ciphertext.size());
4500 break;
4501 case BlockMode::CBC:
4502 case BlockMode::ECB:
4503 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4504 break;
4505 }
4506
4507 auto iv = output_params.GetTagValue(TAG_NONCE);
4508 switch (block_mode) {
4509 case BlockMode::CBC:
4510 case BlockMode::GCM:
4511 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004512 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4513 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4514 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004515 break;
4516
4517 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004518 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004519 break;
4520 }
4521
4522 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4523 << "Decrypt begin() failed for block mode " << block_mode;
4524
4525 string plaintext;
4526 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004527 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004528 }
4529 ErrorCode error = Finish(to_send, &plaintext);
4530 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4531 << " and increment " << increment;
4532 if (error == ErrorCode::OK) {
4533 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4534 << block_mode << " and increment " << increment;
4535 }
4536 }
4537 }
4538}
4539
4540struct AesCtrSp80038aTestVector {
4541 const char* key;
4542 const char* nonce;
4543 const char* plaintext;
4544 const char* ciphertext;
4545};
4546
4547// These test vectors are taken from
4548// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4549static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4550 // AES-128
4551 {
4552 "2b7e151628aed2a6abf7158809cf4f3c",
4553 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4554 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4555 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4556 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4557 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4558 },
4559 // AES-192
4560 {
4561 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4562 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4563 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4564 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4565 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4566 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4567 },
4568 // AES-256
4569 {
4570 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4571 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4572 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4573 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4574 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4575 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4576 },
4577};
4578
4579/*
4580 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4581 *
4582 * Verifies AES CTR implementation against SP800-38A test vectors.
4583 */
4584TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4585 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4586 for (size_t i = 0; i < 3; i++) {
4587 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4588 const string key = hex2str(test.key);
4589 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4590 InvalidSizes.end())
4591 continue;
4592 const string nonce = hex2str(test.nonce);
4593 const string plaintext = hex2str(test.plaintext);
4594 const string ciphertext = hex2str(test.ciphertext);
4595 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4596 }
4597}
4598
4599/*
4600 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4601 *
4602 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4603 */
4604TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4605 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4606 .Authorization(TAG_NO_AUTH_REQUIRED)
4607 .AesEncryptionKey(128)
4608 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4609 .Padding(PaddingMode::PKCS7)));
4610 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4611 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4612}
4613
4614/*
4615 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4616 *
4617 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4618 */
4619TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4620 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4621 .Authorization(TAG_NO_AUTH_REQUIRED)
4622 .AesEncryptionKey(128)
4623 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4624 .Authorization(TAG_CALLER_NONCE)
4625 .Padding(PaddingMode::NONE)));
4626
4627 auto params = AuthorizationSetBuilder()
4628 .BlockMode(BlockMode::CTR)
4629 .Padding(PaddingMode::NONE)
4630 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4631 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4632
4633 params = AuthorizationSetBuilder()
4634 .BlockMode(BlockMode::CTR)
4635 .Padding(PaddingMode::NONE)
4636 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4637 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4638
4639 params = AuthorizationSetBuilder()
4640 .BlockMode(BlockMode::CTR)
4641 .Padding(PaddingMode::NONE)
4642 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4643 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4644}
4645
4646/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004647 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004648 *
4649 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4650 */
4651TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4652 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4653 .Authorization(TAG_NO_AUTH_REQUIRED)
4654 .AesEncryptionKey(128)
4655 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4656 .Padding(PaddingMode::NONE)));
4657 // Two-block message.
4658 string message = "12345678901234567890123456789012";
4659 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4660 AuthorizationSet out_params;
4661 string ciphertext1 = EncryptMessage(message, params, &out_params);
4662 vector<uint8_t> iv1 = CopyIv(out_params);
4663 EXPECT_EQ(message.size(), ciphertext1.size());
4664
4665 out_params.Clear();
4666
4667 string ciphertext2 = EncryptMessage(message, params, &out_params);
4668 vector<uint8_t> iv2 = CopyIv(out_params);
4669 EXPECT_EQ(message.size(), ciphertext2.size());
4670
4671 // IVs should be random, so ciphertexts should differ.
4672 EXPECT_NE(ciphertext1, ciphertext2);
4673
4674 params.push_back(TAG_NONCE, iv1);
4675 string plaintext = DecryptMessage(ciphertext1, params);
4676 EXPECT_EQ(message, plaintext);
4677}
4678
4679/*
4680 * EncryptionOperationsTest.AesCallerNonce
4681 *
4682 * Verifies that AES caller-provided nonces work correctly.
4683 */
4684TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4685 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4686 .Authorization(TAG_NO_AUTH_REQUIRED)
4687 .AesEncryptionKey(128)
4688 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4689 .Authorization(TAG_CALLER_NONCE)
4690 .Padding(PaddingMode::NONE)));
4691
4692 string message = "12345678901234567890123456789012";
4693
4694 // Don't specify nonce, should get a random one.
4695 AuthorizationSetBuilder params =
4696 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4697 AuthorizationSet out_params;
4698 string ciphertext = EncryptMessage(message, params, &out_params);
4699 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004700 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004701
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004702 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004703 string plaintext = DecryptMessage(ciphertext, params);
4704 EXPECT_EQ(message, plaintext);
4705
4706 // Now specify a nonce, should also work.
4707 params = AuthorizationSetBuilder()
4708 .BlockMode(BlockMode::CBC)
4709 .Padding(PaddingMode::NONE)
4710 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4711 out_params.Clear();
4712 ciphertext = EncryptMessage(message, params, &out_params);
4713
4714 // Decrypt with correct nonce.
4715 plaintext = DecryptMessage(ciphertext, params);
4716 EXPECT_EQ(message, plaintext);
4717
4718 // Try with wrong nonce.
4719 params = AuthorizationSetBuilder()
4720 .BlockMode(BlockMode::CBC)
4721 .Padding(PaddingMode::NONE)
4722 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4723 plaintext = DecryptMessage(ciphertext, params);
4724 EXPECT_NE(message, plaintext);
4725}
4726
4727/*
4728 * EncryptionOperationsTest.AesCallerNonceProhibited
4729 *
4730 * Verifies that caller-provided nonces are not permitted when not specified in the key
4731 * authorizations.
4732 */
4733TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4734 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4735 .Authorization(TAG_NO_AUTH_REQUIRED)
4736 .AesEncryptionKey(128)
4737 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4738 .Padding(PaddingMode::NONE)));
4739
4740 string message = "12345678901234567890123456789012";
4741
4742 // Don't specify nonce, should get a random one.
4743 AuthorizationSetBuilder params =
4744 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4745 AuthorizationSet out_params;
4746 string ciphertext = EncryptMessage(message, params, &out_params);
4747 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004748 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004749
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004750 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004751 string plaintext = DecryptMessage(ciphertext, params);
4752 EXPECT_EQ(message, plaintext);
4753
4754 // Now specify a nonce, should fail
4755 params = AuthorizationSetBuilder()
4756 .BlockMode(BlockMode::CBC)
4757 .Padding(PaddingMode::NONE)
4758 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4759 out_params.Clear();
4760 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4761}
4762
4763/*
4764 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4765 *
4766 * Verifies that AES GCM mode works.
4767 */
4768TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4769 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4770 .Authorization(TAG_NO_AUTH_REQUIRED)
4771 .AesEncryptionKey(128)
4772 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4773 .Padding(PaddingMode::NONE)
4774 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4775
4776 string aad = "foobar";
4777 string message = "123456789012345678901234567890123456";
4778
4779 auto begin_params = AuthorizationSetBuilder()
4780 .BlockMode(BlockMode::GCM)
4781 .Padding(PaddingMode::NONE)
4782 .Authorization(TAG_MAC_LENGTH, 128);
4783
Selene Huang31ab4042020-04-29 04:22:39 -07004784 // Encrypt
4785 AuthorizationSet begin_out_params;
4786 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4787 << "Begin encrypt";
4788 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004789 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4790 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004791 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4792
4793 // Grab nonce
4794 begin_params.push_back(begin_out_params);
4795
4796 // Decrypt.
4797 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004798 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004799 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004800 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004801 EXPECT_EQ(message.length(), plaintext.length());
4802 EXPECT_EQ(message, plaintext);
4803}
4804
4805/*
4806 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4807 *
4808 * Verifies that AES GCM mode works, even when there's a long delay
4809 * between operations.
4810 */
4811TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4812 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4813 .Authorization(TAG_NO_AUTH_REQUIRED)
4814 .AesEncryptionKey(128)
4815 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4816 .Padding(PaddingMode::NONE)
4817 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4818
4819 string aad = "foobar";
4820 string message = "123456789012345678901234567890123456";
4821
4822 auto begin_params = AuthorizationSetBuilder()
4823 .BlockMode(BlockMode::GCM)
4824 .Padding(PaddingMode::NONE)
4825 .Authorization(TAG_MAC_LENGTH, 128);
4826
Selene Huang31ab4042020-04-29 04:22:39 -07004827 // Encrypt
4828 AuthorizationSet begin_out_params;
4829 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4830 << "Begin encrypt";
4831 string ciphertext;
4832 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004833 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004834 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004835 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004836
4837 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4838
4839 // Grab nonce
4840 begin_params.push_back(begin_out_params);
4841
4842 // Decrypt.
4843 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4844 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004845 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004846 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004847 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004848 sleep(5);
4849 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4850 EXPECT_EQ(message.length(), plaintext.length());
4851 EXPECT_EQ(message, plaintext);
4852}
4853
4854/*
4855 * EncryptionOperationsTest.AesGcmDifferentNonces
4856 *
4857 * Verifies that encrypting the same data with different nonces produces different outputs.
4858 */
4859TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4860 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4861 .Authorization(TAG_NO_AUTH_REQUIRED)
4862 .AesEncryptionKey(128)
4863 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4864 .Padding(PaddingMode::NONE)
4865 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4866 .Authorization(TAG_CALLER_NONCE)));
4867
4868 string aad = "foobar";
4869 string message = "123456789012345678901234567890123456";
4870 string nonce1 = "000000000000";
4871 string nonce2 = "111111111111";
4872 string nonce3 = "222222222222";
4873
4874 string ciphertext1 =
4875 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4876 string ciphertext2 =
4877 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4878 string ciphertext3 =
4879 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4880
4881 ASSERT_NE(ciphertext1, ciphertext2);
4882 ASSERT_NE(ciphertext1, ciphertext3);
4883 ASSERT_NE(ciphertext2, ciphertext3);
4884}
4885
4886/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004887 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4888 *
4889 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4890 */
4891TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4892 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4893 .Authorization(TAG_NO_AUTH_REQUIRED)
4894 .AesEncryptionKey(128)
4895 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4896 .Padding(PaddingMode::NONE)
4897 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4898
4899 string aad = "foobar";
4900 string message = "123456789012345678901234567890123456";
4901
4902 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4903 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4904 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4905
4906 ASSERT_NE(ciphertext1, ciphertext2);
4907 ASSERT_NE(ciphertext1, ciphertext3);
4908 ASSERT_NE(ciphertext2, ciphertext3);
4909}
4910
4911/*
Selene Huang31ab4042020-04-29 04:22:39 -07004912 * EncryptionOperationsTest.AesGcmTooShortTag
4913 *
4914 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4915 */
4916TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4917 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4918 .Authorization(TAG_NO_AUTH_REQUIRED)
4919 .AesEncryptionKey(128)
4920 .BlockMode(BlockMode::GCM)
4921 .Padding(PaddingMode::NONE)
4922 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4923 string message = "123456789012345678901234567890123456";
4924 auto params = AuthorizationSetBuilder()
4925 .BlockMode(BlockMode::GCM)
4926 .Padding(PaddingMode::NONE)
4927 .Authorization(TAG_MAC_LENGTH, 96);
4928
4929 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4930}
4931
4932/*
4933 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4934 *
4935 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4936 */
4937TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4938 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4939 .Authorization(TAG_NO_AUTH_REQUIRED)
4940 .AesEncryptionKey(128)
4941 .BlockMode(BlockMode::GCM)
4942 .Padding(PaddingMode::NONE)
4943 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4944 string aad = "foobar";
4945 string message = "123456789012345678901234567890123456";
4946 auto params = AuthorizationSetBuilder()
4947 .BlockMode(BlockMode::GCM)
4948 .Padding(PaddingMode::NONE)
4949 .Authorization(TAG_MAC_LENGTH, 128);
4950
Selene Huang31ab4042020-04-29 04:22:39 -07004951 // Encrypt
4952 AuthorizationSet begin_out_params;
4953 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4954 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004955 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004956
4957 AuthorizationSet finish_out_params;
4958 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004959 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4960 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004961
4962 params = AuthorizationSetBuilder()
4963 .Authorizations(begin_out_params)
4964 .BlockMode(BlockMode::GCM)
4965 .Padding(PaddingMode::NONE)
4966 .Authorization(TAG_MAC_LENGTH, 96);
4967
4968 // Decrypt.
4969 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
4970}
4971
4972/*
4973 * EncryptionOperationsTest.AesGcmCorruptKey
4974 *
4975 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
4976 */
4977TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
4978 const uint8_t nonce_bytes[] = {
4979 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
4980 };
4981 string nonce = make_string(nonce_bytes);
4982 const uint8_t ciphertext_bytes[] = {
4983 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
4984 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
4985 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
4986 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
4987 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
4988 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
4989 };
4990 string ciphertext = make_string(ciphertext_bytes);
4991
4992 auto params = AuthorizationSetBuilder()
4993 .BlockMode(BlockMode::GCM)
4994 .Padding(PaddingMode::NONE)
4995 .Authorization(TAG_MAC_LENGTH, 128)
4996 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
4997
4998 auto import_params = AuthorizationSetBuilder()
4999 .Authorization(TAG_NO_AUTH_REQUIRED)
5000 .AesEncryptionKey(128)
5001 .BlockMode(BlockMode::GCM)
5002 .Padding(PaddingMode::NONE)
5003 .Authorization(TAG_CALLER_NONCE)
5004 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5005
5006 // Import correct key and decrypt
5007 const uint8_t key_bytes[] = {
5008 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5009 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5010 };
5011 string key = make_string(key_bytes);
5012 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5013 string plaintext = DecryptMessage(ciphertext, params);
5014 CheckedDeleteKey();
5015
5016 // Corrupt key and attempt to decrypt
5017 key[0] = 0;
5018 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5019 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5020 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5021 CheckedDeleteKey();
5022}
5023
5024/*
5025 * EncryptionOperationsTest.AesGcmAadNoData
5026 *
5027 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5028 * encrypt.
5029 */
5030TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5031 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5032 .Authorization(TAG_NO_AUTH_REQUIRED)
5033 .AesEncryptionKey(128)
5034 .BlockMode(BlockMode::GCM)
5035 .Padding(PaddingMode::NONE)
5036 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5037
5038 string aad = "1234567890123456";
5039 auto params = AuthorizationSetBuilder()
5040 .BlockMode(BlockMode::GCM)
5041 .Padding(PaddingMode::NONE)
5042 .Authorization(TAG_MAC_LENGTH, 128);
5043
Selene Huang31ab4042020-04-29 04:22:39 -07005044 // Encrypt
5045 AuthorizationSet begin_out_params;
5046 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5047 string ciphertext;
5048 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005049 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5050 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005051 EXPECT_TRUE(finish_out_params.empty());
5052
5053 // Grab nonce
5054 params.push_back(begin_out_params);
5055
5056 // Decrypt.
5057 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005058 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005059 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005060 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005061
5062 EXPECT_TRUE(finish_out_params.empty());
5063
5064 EXPECT_EQ("", plaintext);
5065}
5066
5067/*
5068 * EncryptionOperationsTest.AesGcmMultiPartAad
5069 *
5070 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5071 * chunks.
5072 */
5073TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5074 const size_t tag_bits = 128;
5075 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5076 .Authorization(TAG_NO_AUTH_REQUIRED)
5077 .AesEncryptionKey(128)
5078 .BlockMode(BlockMode::GCM)
5079 .Padding(PaddingMode::NONE)
5080 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5081
5082 string message = "123456789012345678901234567890123456";
5083 auto begin_params = AuthorizationSetBuilder()
5084 .BlockMode(BlockMode::GCM)
5085 .Padding(PaddingMode::NONE)
5086 .Authorization(TAG_MAC_LENGTH, tag_bits);
5087 AuthorizationSet begin_out_params;
5088
Selene Huang31ab4042020-04-29 04:22:39 -07005089 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5090
5091 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005092 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5093 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005094 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005095 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5096 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005097
Selene Huang31ab4042020-04-29 04:22:39 -07005098 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005099 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005100
5101 // Grab nonce.
5102 begin_params.push_back(begin_out_params);
5103
5104 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005105 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005106 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005107 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005108 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005109 EXPECT_EQ(message, plaintext);
5110}
5111
5112/*
5113 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5114 *
5115 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5116 */
5117TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5118 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5119 .Authorization(TAG_NO_AUTH_REQUIRED)
5120 .AesEncryptionKey(128)
5121 .BlockMode(BlockMode::GCM)
5122 .Padding(PaddingMode::NONE)
5123 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5124
5125 string message = "123456789012345678901234567890123456";
5126 auto begin_params = AuthorizationSetBuilder()
5127 .BlockMode(BlockMode::GCM)
5128 .Padding(PaddingMode::NONE)
5129 .Authorization(TAG_MAC_LENGTH, 128);
5130 AuthorizationSet begin_out_params;
5131
Selene Huang31ab4042020-04-29 04:22:39 -07005132 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5133
Shawn Willden92d79c02021-02-19 07:31:55 -07005134 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005135 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005136 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5137 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005138
David Drysdaled2cc8c22021-04-15 13:29:45 +01005139 // The failure should have already cancelled the operation.
5140 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5141
Shawn Willden92d79c02021-02-19 07:31:55 -07005142 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005143}
5144
5145/*
5146 * EncryptionOperationsTest.AesGcmBadAad
5147 *
5148 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5149 */
5150TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5151 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5152 .Authorization(TAG_NO_AUTH_REQUIRED)
5153 .AesEncryptionKey(128)
5154 .BlockMode(BlockMode::GCM)
5155 .Padding(PaddingMode::NONE)
5156 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5157
5158 string message = "12345678901234567890123456789012";
5159 auto begin_params = AuthorizationSetBuilder()
5160 .BlockMode(BlockMode::GCM)
5161 .Padding(PaddingMode::NONE)
5162 .Authorization(TAG_MAC_LENGTH, 128);
5163
Selene Huang31ab4042020-04-29 04:22:39 -07005164 // Encrypt
5165 AuthorizationSet begin_out_params;
5166 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005167 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005168 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005169 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005170
5171 // Grab nonce
5172 begin_params.push_back(begin_out_params);
5173
Selene Huang31ab4042020-04-29 04:22:39 -07005174 // Decrypt.
5175 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005176 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005177 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005178 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005179}
5180
5181/*
5182 * EncryptionOperationsTest.AesGcmWrongNonce
5183 *
5184 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5185 */
5186TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5187 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5188 .Authorization(TAG_NO_AUTH_REQUIRED)
5189 .AesEncryptionKey(128)
5190 .BlockMode(BlockMode::GCM)
5191 .Padding(PaddingMode::NONE)
5192 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5193
5194 string message = "12345678901234567890123456789012";
5195 auto begin_params = AuthorizationSetBuilder()
5196 .BlockMode(BlockMode::GCM)
5197 .Padding(PaddingMode::NONE)
5198 .Authorization(TAG_MAC_LENGTH, 128);
5199
Selene Huang31ab4042020-04-29 04:22:39 -07005200 // Encrypt
5201 AuthorizationSet begin_out_params;
5202 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005203 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005204 string ciphertext;
5205 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005206 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005207
5208 // Wrong nonce
5209 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5210
5211 // Decrypt.
5212 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005213 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005214 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005215 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005216
5217 // With wrong nonce, should have gotten garbage plaintext (or none).
5218 EXPECT_NE(message, plaintext);
5219}
5220
5221/*
5222 * EncryptionOperationsTest.AesGcmCorruptTag
5223 *
5224 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5225 */
5226TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5227 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5228 .Authorization(TAG_NO_AUTH_REQUIRED)
5229 .AesEncryptionKey(128)
5230 .BlockMode(BlockMode::GCM)
5231 .Padding(PaddingMode::NONE)
5232 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5233
5234 string aad = "1234567890123456";
5235 string message = "123456789012345678901234567890123456";
5236
5237 auto params = AuthorizationSetBuilder()
5238 .BlockMode(BlockMode::GCM)
5239 .Padding(PaddingMode::NONE)
5240 .Authorization(TAG_MAC_LENGTH, 128);
5241
Selene Huang31ab4042020-04-29 04:22:39 -07005242 // Encrypt
5243 AuthorizationSet begin_out_params;
5244 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005245 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005246 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005247 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005248
5249 // Corrupt tag
5250 ++(*ciphertext.rbegin());
5251
5252 // Grab nonce
5253 params.push_back(begin_out_params);
5254
5255 // Decrypt.
5256 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005257 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005258 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005259 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005260}
5261
5262/*
5263 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5264 *
5265 * Verifies that 3DES is basically functional.
5266 */
5267TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5268 auto auths = AuthorizationSetBuilder()
5269 .TripleDesEncryptionKey(168)
5270 .BlockMode(BlockMode::ECB)
5271 .Authorization(TAG_NO_AUTH_REQUIRED)
5272 .Padding(PaddingMode::NONE);
5273
5274 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5275 // Two-block message.
5276 string message = "1234567890123456";
5277 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5278 string ciphertext1 = EncryptMessage(message, inParams);
5279 EXPECT_EQ(message.size(), ciphertext1.size());
5280
5281 string ciphertext2 = EncryptMessage(string(message), inParams);
5282 EXPECT_EQ(message.size(), ciphertext2.size());
5283
5284 // ECB is deterministic.
5285 EXPECT_EQ(ciphertext1, ciphertext2);
5286
5287 string plaintext = DecryptMessage(ciphertext1, inParams);
5288 EXPECT_EQ(message, plaintext);
5289}
5290
5291/*
5292 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5293 *
5294 * Verifies that CBC keys reject ECB usage.
5295 */
5296TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5297 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5298 .TripleDesEncryptionKey(168)
5299 .BlockMode(BlockMode::CBC)
5300 .Authorization(TAG_NO_AUTH_REQUIRED)
5301 .Padding(PaddingMode::NONE)));
5302
5303 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5304 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5305}
5306
5307/*
5308 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5309 *
5310 * Tests ECB mode with PKCS#7 padding, various message sizes.
5311 */
5312TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5313 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5314 .TripleDesEncryptionKey(168)
5315 .BlockMode(BlockMode::ECB)
5316 .Authorization(TAG_NO_AUTH_REQUIRED)
5317 .Padding(PaddingMode::PKCS7)));
5318
5319 for (size_t i = 0; i < 32; ++i) {
5320 string message(i, 'a');
5321 auto inParams =
5322 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5323 string ciphertext = EncryptMessage(message, inParams);
5324 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5325 string plaintext = DecryptMessage(ciphertext, inParams);
5326 EXPECT_EQ(message, plaintext);
5327 }
5328}
5329
5330/*
5331 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5332 *
5333 * Verifies that keys configured for no padding reject PKCS7 padding
5334 */
5335TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5336 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5337 .TripleDesEncryptionKey(168)
5338 .BlockMode(BlockMode::ECB)
5339 .Authorization(TAG_NO_AUTH_REQUIRED)
5340 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005341 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5342 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005343}
5344
5345/*
5346 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5347 *
5348 * Verifies that corrupted padding is detected.
5349 */
5350TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5351 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5352 .TripleDesEncryptionKey(168)
5353 .BlockMode(BlockMode::ECB)
5354 .Authorization(TAG_NO_AUTH_REQUIRED)
5355 .Padding(PaddingMode::PKCS7)));
5356
5357 string message = "a";
5358 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5359 EXPECT_EQ(8U, ciphertext.size());
5360 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005361
5362 AuthorizationSetBuilder begin_params;
5363 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5364 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07005365
5366 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5367 ++ciphertext[ciphertext.size() / 2];
5368
5369 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5370 string plaintext;
5371 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5372 ErrorCode error = Finish(&plaintext);
5373 if (error == ErrorCode::INVALID_ARGUMENT) {
5374 // This is the expected error, we can exit the test now.
5375 return;
5376 } else {
5377 // Very small chance we got valid decryption, so try again.
5378 ASSERT_EQ(error, ErrorCode::OK);
5379 }
5380 }
5381 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005382}
5383
5384struct TripleDesTestVector {
5385 const char* name;
5386 const KeyPurpose purpose;
5387 const BlockMode block_mode;
5388 const PaddingMode padding_mode;
5389 const char* key;
5390 const char* iv;
5391 const char* input;
5392 const char* output;
5393};
5394
5395// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5396// of the NIST vectors are multiples of the block size.
5397static const TripleDesTestVector kTripleDesTestVectors[] = {
5398 {
5399 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5400 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5401 "", // IV
5402 "329d86bdf1bc5af4", // input
5403 "d946c2756d78633f", // output
5404 },
5405 {
5406 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5407 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5408 "", // IV
5409 "6b1540781b01ce1997adae102dbf3c5b", // input
5410 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5411 },
5412 {
5413 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5414 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5415 "", // IV
5416 "6daad94ce08acfe7", // input
5417 "660e7d32dcc90e79", // output
5418 },
5419 {
5420 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5421 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5422 "", // IV
5423 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5424 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5425 },
5426 {
5427 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5428 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5429 "43f791134c5647ba", // IV
5430 "dcc153cef81d6f24", // input
5431 "92538bd8af18d3ba", // output
5432 },
5433 {
5434 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5435 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5436 "c2e999cb6249023c", // IV
5437 "c689aee38a301bb316da75db36f110b5", // input
5438 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5439 },
5440 {
5441 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5442 PaddingMode::PKCS7,
5443 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5444 "c2e999cb6249023c", // IV
5445 "c689aee38a301bb316da75db36f110b500", // input
5446 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5447 },
5448 {
5449 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5450 PaddingMode::PKCS7,
5451 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5452 "c2e999cb6249023c", // IV
5453 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5454 "c689aee38a301bb316da75db36f110b500", // output
5455 },
5456 {
5457 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5458 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5459 "41746c7e442d3681", // IV
5460 "c53a7b0ec40600fe", // input
5461 "d4f00eb455de1034", // output
5462 },
5463 {
5464 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5465 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5466 "3982bc02c3727d45", // IV
5467 "6006f10adef52991fcc777a1238bbb65", // input
5468 "edae09288e9e3bc05746d872b48e3b29", // output
5469 },
5470};
5471
5472/*
5473 * EncryptionOperationsTest.TripleDesTestVector
5474 *
5475 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5476 */
5477TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5478 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5479 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5480 SCOPED_TRACE(test->name);
5481 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5482 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5483 hex2str(test->output));
5484 }
5485}
5486
5487/*
5488 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5489 *
5490 * Validates CBC mode functionality.
5491 */
5492TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5493 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5494 .TripleDesEncryptionKey(168)
5495 .BlockMode(BlockMode::CBC)
5496 .Authorization(TAG_NO_AUTH_REQUIRED)
5497 .Padding(PaddingMode::NONE)));
5498
5499 ASSERT_GT(key_blob_.size(), 0U);
5500
5501 // Two-block message.
5502 string message = "1234567890123456";
5503 vector<uint8_t> iv1;
5504 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5505 EXPECT_EQ(message.size(), ciphertext1.size());
5506
5507 vector<uint8_t> iv2;
5508 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5509 EXPECT_EQ(message.size(), ciphertext2.size());
5510
5511 // IVs should be random, so ciphertexts should differ.
5512 EXPECT_NE(iv1, iv2);
5513 EXPECT_NE(ciphertext1, ciphertext2);
5514
5515 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5516 EXPECT_EQ(message, plaintext);
5517}
5518
5519/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005520 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5521 *
5522 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5523 */
5524TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5525 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5526 .TripleDesEncryptionKey(168)
5527 .BlockMode(BlockMode::CBC)
5528 .Authorization(TAG_NO_AUTH_REQUIRED)
5529 .Authorization(TAG_CALLER_NONCE)
5530 .Padding(PaddingMode::NONE)));
5531 auto params = AuthorizationSetBuilder()
5532 .BlockMode(BlockMode::CBC)
5533 .Padding(PaddingMode::NONE)
5534 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5535 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5536}
5537
5538/*
Selene Huang31ab4042020-04-29 04:22:39 -07005539 * EncryptionOperationsTest.TripleDesCallerIv
5540 *
5541 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5542 */
5543TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5544 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5545 .TripleDesEncryptionKey(168)
5546 .BlockMode(BlockMode::CBC)
5547 .Authorization(TAG_NO_AUTH_REQUIRED)
5548 .Authorization(TAG_CALLER_NONCE)
5549 .Padding(PaddingMode::NONE)));
5550 string message = "1234567890123456";
5551 vector<uint8_t> iv;
5552 // Don't specify IV, should get a random one.
5553 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5554 EXPECT_EQ(message.size(), ciphertext1.size());
5555 EXPECT_EQ(8U, iv.size());
5556
5557 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5558 EXPECT_EQ(message, plaintext);
5559
5560 // Now specify an IV, should also work.
5561 iv = AidlBuf("abcdefgh");
5562 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5563
5564 // Decrypt with correct IV.
5565 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5566 EXPECT_EQ(message, plaintext);
5567
5568 // Now try with wrong IV.
5569 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5570 EXPECT_NE(message, plaintext);
5571}
5572
5573/*
5574 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5575 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005576 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005577 */
5578TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5579 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5580 .TripleDesEncryptionKey(168)
5581 .BlockMode(BlockMode::CBC)
5582 .Authorization(TAG_NO_AUTH_REQUIRED)
5583 .Padding(PaddingMode::NONE)));
5584
5585 string message = "12345678901234567890123456789012";
5586 vector<uint8_t> iv;
5587 // Don't specify nonce, should get a random one.
5588 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5589 EXPECT_EQ(message.size(), ciphertext1.size());
5590 EXPECT_EQ(8U, iv.size());
5591
5592 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5593 EXPECT_EQ(message, plaintext);
5594
5595 // Now specify a nonce, should fail.
5596 auto input_params = AuthorizationSetBuilder()
5597 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5598 .BlockMode(BlockMode::CBC)
5599 .Padding(PaddingMode::NONE);
5600 AuthorizationSet output_params;
5601 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5602 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5603}
5604
5605/*
5606 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5607 *
5608 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5609 */
5610TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5611 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5612 .TripleDesEncryptionKey(168)
5613 .BlockMode(BlockMode::ECB)
5614 .Authorization(TAG_NO_AUTH_REQUIRED)
5615 .Padding(PaddingMode::NONE)));
5616 // Two-block message.
5617 string message = "1234567890123456";
5618 auto begin_params =
5619 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5620 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5621}
5622
5623/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005624 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005625 *
5626 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5627 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005628TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5629 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5630 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5631 .TripleDesEncryptionKey(168)
5632 .BlockMode(blockMode)
5633 .Authorization(TAG_NO_AUTH_REQUIRED)
5634 .Padding(PaddingMode::NONE)));
5635 // Message is slightly shorter than two blocks.
5636 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005637
David Drysdaled2cc8c22021-04-15 13:29:45 +01005638 auto begin_params =
5639 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5640 AuthorizationSet output_params;
5641 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5642 string ciphertext;
5643 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5644
5645 CheckedDeleteKey();
5646 }
Selene Huang31ab4042020-04-29 04:22:39 -07005647}
5648
5649/*
5650 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5651 *
5652 * Verifies that PKCS7 padding works correctly in CBC mode.
5653 */
5654TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5655 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5656 .TripleDesEncryptionKey(168)
5657 .BlockMode(BlockMode::CBC)
5658 .Authorization(TAG_NO_AUTH_REQUIRED)
5659 .Padding(PaddingMode::PKCS7)));
5660
5661 // Try various message lengths; all should work.
5662 for (size_t i = 0; i < 32; ++i) {
5663 string message(i, 'a');
5664 vector<uint8_t> iv;
5665 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5666 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5667 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5668 EXPECT_EQ(message, plaintext);
5669 }
5670}
5671
5672/*
5673 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5674 *
5675 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5676 */
5677TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5678 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5679 .TripleDesEncryptionKey(168)
5680 .BlockMode(BlockMode::CBC)
5681 .Authorization(TAG_NO_AUTH_REQUIRED)
5682 .Padding(PaddingMode::NONE)));
5683
5684 // Try various message lengths; all should fail.
5685 for (size_t i = 0; i < 32; ++i) {
5686 auto begin_params =
5687 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5688 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5689 }
5690}
5691
5692/*
5693 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5694 *
5695 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5696 */
5697TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5698 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5699 .TripleDesEncryptionKey(168)
5700 .BlockMode(BlockMode::CBC)
5701 .Authorization(TAG_NO_AUTH_REQUIRED)
5702 .Padding(PaddingMode::PKCS7)));
5703
5704 string message = "a";
5705 vector<uint8_t> iv;
5706 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5707 EXPECT_EQ(8U, ciphertext.size());
5708 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005709
5710 auto begin_params = AuthorizationSetBuilder()
5711 .BlockMode(BlockMode::CBC)
5712 .Padding(PaddingMode::PKCS7)
5713 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07005714
5715 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5716 ++ciphertext[ciphertext.size() / 2];
5717 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5718 string plaintext;
5719 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5720 ErrorCode error = Finish(&plaintext);
5721 if (error == ErrorCode::INVALID_ARGUMENT) {
5722 // This is the expected error, we can exit the test now.
5723 return;
5724 } else {
5725 // Very small chance we got valid decryption, so try again.
5726 ASSERT_EQ(error, ErrorCode::OK);
5727 }
5728 }
5729 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005730}
5731
5732/*
5733 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5734 *
5735 * Verifies that 3DES CBC works with many different input sizes.
5736 */
5737TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5738 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5739 .TripleDesEncryptionKey(168)
5740 .BlockMode(BlockMode::CBC)
5741 .Authorization(TAG_NO_AUTH_REQUIRED)
5742 .Padding(PaddingMode::NONE)));
5743
5744 int increment = 7;
5745 string message(240, 'a');
5746 AuthorizationSet input_params =
5747 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5748 AuthorizationSet output_params;
5749 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5750
5751 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005752 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005753 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005754 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5755 EXPECT_EQ(message.size(), ciphertext.size());
5756
5757 // Move TAG_NONCE into input_params
5758 input_params = output_params;
5759 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5760 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5761 output_params.Clear();
5762
5763 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5764 string plaintext;
5765 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005766 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005767 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5768 EXPECT_EQ(ciphertext.size(), plaintext.size());
5769 EXPECT_EQ(message, plaintext);
5770}
5771
5772INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5773
5774typedef KeyMintAidlTestBase MaxOperationsTest;
5775
5776/*
5777 * MaxOperationsTest.TestLimitAes
5778 *
5779 * Verifies that the max uses per boot tag works correctly with AES keys.
5780 */
5781TEST_P(MaxOperationsTest, TestLimitAes) {
5782 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5783
5784 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5785 .Authorization(TAG_NO_AUTH_REQUIRED)
5786 .AesEncryptionKey(128)
5787 .EcbMode()
5788 .Padding(PaddingMode::NONE)
5789 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5790
5791 string message = "1234567890123456";
5792
5793 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5794
5795 EncryptMessage(message, params);
5796 EncryptMessage(message, params);
5797 EncryptMessage(message, params);
5798
5799 // Fourth time should fail.
5800 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5801}
5802
5803/*
Qi Wud22ec842020-11-26 13:27:53 +08005804 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005805 *
5806 * Verifies that the max uses per boot tag works correctly with RSA keys.
5807 */
5808TEST_P(MaxOperationsTest, TestLimitRsa) {
5809 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5810
5811 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5812 .Authorization(TAG_NO_AUTH_REQUIRED)
5813 .RsaSigningKey(1024, 65537)
5814 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005815 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5816 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005817
5818 string message = "1234567890123456";
5819
5820 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5821
5822 SignMessage(message, params);
5823 SignMessage(message, params);
5824 SignMessage(message, params);
5825
5826 // Fourth time should fail.
5827 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5828}
5829
5830INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5831
Qi Wud22ec842020-11-26 13:27:53 +08005832typedef KeyMintAidlTestBase UsageCountLimitTest;
5833
5834/*
Qi Wubeefae42021-01-28 23:16:37 +08005835 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005836 *
Qi Wubeefae42021-01-28 23:16:37 +08005837 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005838 */
Qi Wubeefae42021-01-28 23:16:37 +08005839TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005840 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5841
5842 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5843 .Authorization(TAG_NO_AUTH_REQUIRED)
5844 .AesEncryptionKey(128)
5845 .EcbMode()
5846 .Padding(PaddingMode::NONE)
5847 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5848
5849 // Check the usage count limit tag appears in the authorizations.
5850 AuthorizationSet auths;
5851 for (auto& entry : key_characteristics_) {
5852 auths.push_back(AuthorizationSet(entry.authorizations));
5853 }
5854 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5855 << "key usage count limit " << 1U << " missing";
5856
5857 string message = "1234567890123456";
5858 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5859
Qi Wubeefae42021-01-28 23:16:37 +08005860 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5861 AuthorizationSet keystore_auths =
5862 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5863
Qi Wud22ec842020-11-26 13:27:53 +08005864 // First usage of AES key should work.
5865 EncryptMessage(message, params);
5866
Qi Wud22ec842020-11-26 13:27:53 +08005867 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5868 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5869 // must be invalidated from secure storage (such as RPMB partition).
5870 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5871 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005872 // Usage count limit tag is enforced by keystore, keymint does nothing.
5873 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005874 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5875 }
5876}
5877
5878/*
Qi Wubeefae42021-01-28 23:16:37 +08005879 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005880 *
Qi Wubeefae42021-01-28 23:16:37 +08005881 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005882 */
Qi Wubeefae42021-01-28 23:16:37 +08005883TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5884 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5885
5886 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5887 .Authorization(TAG_NO_AUTH_REQUIRED)
5888 .AesEncryptionKey(128)
5889 .EcbMode()
5890 .Padding(PaddingMode::NONE)
5891 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5892
5893 // Check the usage count limit tag appears in the authorizations.
5894 AuthorizationSet auths;
5895 for (auto& entry : key_characteristics_) {
5896 auths.push_back(AuthorizationSet(entry.authorizations));
5897 }
5898 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5899 << "key usage count limit " << 3U << " missing";
5900
5901 string message = "1234567890123456";
5902 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5903
5904 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5905 AuthorizationSet keystore_auths =
5906 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5907
5908 EncryptMessage(message, params);
5909 EncryptMessage(message, params);
5910 EncryptMessage(message, params);
5911
5912 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5913 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5914 // must be invalidated from secure storage (such as RPMB partition).
5915 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5916 } else {
5917 // Usage count limit tag is enforced by keystore, keymint does nothing.
5918 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5919 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5920 }
5921}
5922
5923/*
5924 * UsageCountLimitTest.TestSingleUseRsa
5925 *
5926 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5927 */
5928TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005929 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5930
5931 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5932 .Authorization(TAG_NO_AUTH_REQUIRED)
5933 .RsaSigningKey(1024, 65537)
5934 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005935 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5936 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005937
5938 // Check the usage count limit tag appears in the authorizations.
5939 AuthorizationSet auths;
5940 for (auto& entry : key_characteristics_) {
5941 auths.push_back(AuthorizationSet(entry.authorizations));
5942 }
5943 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5944 << "key usage count limit " << 1U << " missing";
5945
5946 string message = "1234567890123456";
5947 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5948
Qi Wubeefae42021-01-28 23:16:37 +08005949 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5950 AuthorizationSet keystore_auths =
5951 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5952
Qi Wud22ec842020-11-26 13:27:53 +08005953 // First usage of RSA key should work.
5954 SignMessage(message, params);
5955
Qi Wud22ec842020-11-26 13:27:53 +08005956 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5957 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5958 // must be invalidated from secure storage (such as RPMB partition).
5959 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5960 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005961 // Usage count limit tag is enforced by keystore, keymint does nothing.
5962 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5963 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5964 }
5965}
5966
5967/*
5968 * UsageCountLimitTest.TestLimitUseRsa
5969 *
5970 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5971 */
5972TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
5973 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5974
5975 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5976 .Authorization(TAG_NO_AUTH_REQUIRED)
5977 .RsaSigningKey(1024, 65537)
5978 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005979 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
5980 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08005981
5982 // Check the usage count limit tag appears in the authorizations.
5983 AuthorizationSet auths;
5984 for (auto& entry : key_characteristics_) {
5985 auths.push_back(AuthorizationSet(entry.authorizations));
5986 }
5987 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5988 << "key usage count limit " << 3U << " missing";
5989
5990 string message = "1234567890123456";
5991 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5992
5993 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5994 AuthorizationSet keystore_auths =
5995 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5996
5997 SignMessage(message, params);
5998 SignMessage(message, params);
5999 SignMessage(message, params);
6000
6001 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6002 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6003 // must be invalidated from secure storage (such as RPMB partition).
6004 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6005 } else {
6006 // Usage count limit tag is enforced by keystore, keymint does nothing.
6007 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006008 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6009 }
6010}
6011
Qi Wu8e727f72021-02-11 02:49:33 +08006012/*
6013 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6014 *
6015 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6016 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6017 * in hardware.
6018 */
6019TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
6020 if (SecLevel() == SecurityLevel::STRONGBOX) return;
6021
6022 auto error = GenerateKey(AuthorizationSetBuilder()
6023 .RsaSigningKey(2048, 65537)
6024 .Digest(Digest::NONE)
6025 .Padding(PaddingMode::NONE)
6026 .Authorization(TAG_NO_AUTH_REQUIRED)
6027 .Authorization(TAG_ROLLBACK_RESISTANCE)
6028 .SetDefaultValidity());
6029 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6030
6031 if (error == ErrorCode::OK) {
6032 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6033 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6034 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6035 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6036
6037 // The KeyMint should also enforce single use key in hardware when it supports rollback
6038 // resistance.
6039 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6040 .Authorization(TAG_NO_AUTH_REQUIRED)
6041 .RsaSigningKey(1024, 65537)
6042 .NoDigestOrPadding()
6043 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6044 .SetDefaultValidity()));
6045
6046 // Check the usage count limit tag appears in the hardware authorizations.
6047 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6048 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6049 << "key usage count limit " << 1U << " missing";
6050
6051 string message = "1234567890123456";
6052 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6053
6054 // First usage of RSA key should work.
6055 SignMessage(message, params);
6056
6057 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6058 // must be invalidated from secure storage (such as RPMB partition).
6059 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6060 }
6061}
6062
Qi Wud22ec842020-11-26 13:27:53 +08006063INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6064
David Drysdale7de9feb2021-03-05 14:56:19 +00006065typedef KeyMintAidlTestBase GetHardwareInfoTest;
6066
6067TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6068 // Retrieving hardware info should give the same result each time.
6069 KeyMintHardwareInfo info;
6070 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6071 KeyMintHardwareInfo info2;
6072 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6073 EXPECT_EQ(info, info2);
6074}
6075
6076INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6077
Selene Huang31ab4042020-04-29 04:22:39 -07006078typedef KeyMintAidlTestBase AddEntropyTest;
6079
6080/*
6081 * AddEntropyTest.AddEntropy
6082 *
6083 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6084 * is actually added.
6085 */
6086TEST_P(AddEntropyTest, AddEntropy) {
6087 string data = "foo";
6088 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6089}
6090
6091/*
6092 * AddEntropyTest.AddEmptyEntropy
6093 *
6094 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6095 */
6096TEST_P(AddEntropyTest, AddEmptyEntropy) {
6097 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6098}
6099
6100/*
6101 * AddEntropyTest.AddLargeEntropy
6102 *
6103 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6104 */
6105TEST_P(AddEntropyTest, AddLargeEntropy) {
6106 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6107}
6108
David Drysdalebb3d85e2021-04-13 11:15:51 +01006109/*
6110 * AddEntropyTest.AddTooLargeEntropy
6111 *
6112 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6113 */
6114TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6115 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6116 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6117}
6118
Selene Huang31ab4042020-04-29 04:22:39 -07006119INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6120
Selene Huang31ab4042020-04-29 04:22:39 -07006121typedef KeyMintAidlTestBase KeyDeletionTest;
6122
6123/**
6124 * KeyDeletionTest.DeleteKey
6125 *
6126 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6127 * valid key blob.
6128 */
6129TEST_P(KeyDeletionTest, DeleteKey) {
6130 auto error = GenerateKey(AuthorizationSetBuilder()
6131 .RsaSigningKey(2048, 65537)
6132 .Digest(Digest::NONE)
6133 .Padding(PaddingMode::NONE)
6134 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006135 .Authorization(TAG_ROLLBACK_RESISTANCE)
6136 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006137 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6138
6139 // Delete must work if rollback protection is implemented
6140 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006141 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006142 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6143
6144 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
6145
6146 string message = "12345678901234567890123456789012";
6147 AuthorizationSet begin_out_params;
6148 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6149 Begin(KeyPurpose::SIGN, key_blob_,
6150 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6151 &begin_out_params));
6152 AbortIfNeeded();
6153 key_blob_ = AidlBuf();
6154 }
6155}
6156
6157/**
6158 * KeyDeletionTest.DeleteInvalidKey
6159 *
6160 * This test checks that the HAL excepts invalid key blobs..
6161 */
6162TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6163 // Generate key just to check if rollback protection is implemented
6164 auto error = GenerateKey(AuthorizationSetBuilder()
6165 .RsaSigningKey(2048, 65537)
6166 .Digest(Digest::NONE)
6167 .Padding(PaddingMode::NONE)
6168 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006169 .Authorization(TAG_ROLLBACK_RESISTANCE)
6170 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006171 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6172
6173 // Delete must work if rollback protection is implemented
6174 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006175 AuthorizationSet enforced(SecLevelAuthorizations());
6176 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006177
6178 // Delete the key we don't care about the result at this point.
6179 DeleteKey();
6180
6181 // Now create an invalid key blob and delete it.
6182 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
6183
6184 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6185 }
6186}
6187
6188/**
6189 * KeyDeletionTest.DeleteAllKeys
6190 *
6191 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6192 *
6193 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6194 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6195 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6196 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6197 * credentials stored in Keystore/Keymint.
6198 */
6199TEST_P(KeyDeletionTest, DeleteAllKeys) {
6200 if (!arm_deleteAllKeys) return;
6201 auto error = GenerateKey(AuthorizationSetBuilder()
6202 .RsaSigningKey(2048, 65537)
6203 .Digest(Digest::NONE)
6204 .Padding(PaddingMode::NONE)
6205 .Authorization(TAG_NO_AUTH_REQUIRED)
6206 .Authorization(TAG_ROLLBACK_RESISTANCE));
6207 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6208
6209 // Delete must work if rollback protection is implemented
6210 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006211 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006212 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6213
6214 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
6215
6216 string message = "12345678901234567890123456789012";
6217 AuthorizationSet begin_out_params;
6218
6219 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6220 Begin(KeyPurpose::SIGN, key_blob_,
6221 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6222 &begin_out_params));
6223 AbortIfNeeded();
6224 key_blob_ = AidlBuf();
6225 }
6226}
6227
6228INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6229
David Drysdaled2cc8c22021-04-15 13:29:45 +01006230typedef KeyMintAidlTestBase KeyUpgradeTest;
6231
6232/**
6233 * KeyUpgradeTest.UpgradeInvalidKey
6234 *
6235 * This test checks that the HAL excepts invalid key blobs..
6236 */
6237TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6238 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6239
6240 std::vector<uint8_t> new_blob;
6241 Status result = keymint_->upgradeKey(key_blob,
6242 AuthorizationSetBuilder()
6243 .Authorization(TAG_APPLICATION_ID, "clientid")
6244 .Authorization(TAG_APPLICATION_DATA, "appdata")
6245 .vector_data(),
6246 &new_blob);
6247 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6248}
6249
6250INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6251
Selene Huang31ab4042020-04-29 04:22:39 -07006252using UpgradeKeyTest = KeyMintAidlTestBase;
6253
6254/*
6255 * UpgradeKeyTest.UpgradeKey
6256 *
6257 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6258 */
6259TEST_P(UpgradeKeyTest, UpgradeKey) {
6260 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6261 .AesEncryptionKey(128)
6262 .Padding(PaddingMode::NONE)
6263 .Authorization(TAG_NO_AUTH_REQUIRED)));
6264
6265 auto result = UpgradeKey(key_blob_);
6266
6267 // Key doesn't need upgrading. Should get okay, but no new key blob.
6268 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6269}
6270
6271INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6272
6273using ClearOperationsTest = KeyMintAidlTestBase;
6274
6275/*
6276 * ClearSlotsTest.TooManyOperations
6277 *
6278 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6279 * operations are started without being finished or aborted. Also verifies
6280 * that aborting the operations clears the operations.
6281 *
6282 */
6283TEST_P(ClearOperationsTest, TooManyOperations) {
6284 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6285 .Authorization(TAG_NO_AUTH_REQUIRED)
6286 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006287 .Padding(PaddingMode::NONE)
6288 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006289
6290 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6291 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006292 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006293 AuthorizationSet out_params;
6294 ErrorCode result;
6295 size_t i;
6296
6297 for (i = 0; i < max_operations; i++) {
6298 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6299 if (ErrorCode::OK != result) {
6300 break;
6301 }
6302 }
6303 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6304 // Try again just in case there's a weird overflow bug
6305 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6306 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6307 for (size_t j = 0; j < i; j++) {
6308 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6309 << "Aboort failed for i = " << j << std::endl;
6310 }
6311 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6312 AbortIfNeeded();
6313}
6314
6315INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6316
6317typedef KeyMintAidlTestBase TransportLimitTest;
6318
6319/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006320 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006321 *
6322 * Verifies that passing input data to finish succeeds as expected.
6323 */
6324TEST_P(TransportLimitTest, LargeFinishInput) {
6325 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6326 .Authorization(TAG_NO_AUTH_REQUIRED)
6327 .AesEncryptionKey(128)
6328 .BlockMode(BlockMode::ECB)
6329 .Padding(PaddingMode::NONE)));
6330
6331 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6332 auto cipher_params =
6333 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6334
6335 AuthorizationSet out_params;
6336 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6337
6338 string plain_message = std::string(1 << msg_size, 'x');
6339 string encrypted_message;
6340 auto rc = Finish(plain_message, &encrypted_message);
6341
6342 EXPECT_EQ(ErrorCode::OK, rc);
6343 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6344 << "Encrypt finish returned OK, but did not consume all of the given input";
6345 cipher_params.push_back(out_params);
6346
6347 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6348
6349 string decrypted_message;
6350 rc = Finish(encrypted_message, &decrypted_message);
6351 EXPECT_EQ(ErrorCode::OK, rc);
6352 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6353 << "Decrypt finish returned OK, did not consume all of the given input";
6354 }
6355}
6356
6357INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6358
David Zeuthene0c40892021-01-08 12:54:11 -05006359typedef KeyMintAidlTestBase KeyAgreementTest;
6360
6361int CurveToOpenSslCurveName(EcCurve curve) {
6362 switch (curve) {
6363 case EcCurve::P_224:
6364 return NID_secp224r1;
6365 case EcCurve::P_256:
6366 return NID_X9_62_prime256v1;
6367 case EcCurve::P_384:
6368 return NID_secp384r1;
6369 case EcCurve::P_521:
6370 return NID_secp521r1;
6371 }
6372}
6373
6374/*
6375 * KeyAgreementTest.Ecdh
6376 *
6377 * Verifies that ECDH works for all curves
6378 */
6379TEST_P(KeyAgreementTest, Ecdh) {
6380 // Because it's possible to use this API with keys on different curves, we
6381 // check all N^2 combinations where N is the number of supported
6382 // curves.
6383 //
6384 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6385 // lot more curves we can be smart about things and just pick |otherCurve| so
6386 // it's not |curve| and that way we end up with only 2*N runs
6387 //
6388 for (auto curve : ValidCurves()) {
6389 for (auto localCurve : ValidCurves()) {
6390 // Generate EC key locally (with access to private key material)
6391 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6392 int curveName = CurveToOpenSslCurveName(localCurve);
6393 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6394 ASSERT_NE(group, nullptr);
6395 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6396 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6397 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6398 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6399
6400 // Get encoded form of the public part of the locally generated key...
6401 unsigned char* p = nullptr;
6402 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6403 ASSERT_GT(encodedPublicKeySize, 0);
6404 vector<uint8_t> encodedPublicKey(
6405 reinterpret_cast<const uint8_t*>(p),
6406 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6407 OPENSSL_free(p);
6408
6409 // Generate EC key in KeyMint (only access to public key material)
6410 vector<uint8_t> challenge = {0x41, 0x42};
6411 EXPECT_EQ(
6412 ErrorCode::OK,
6413 GenerateKey(AuthorizationSetBuilder()
6414 .Authorization(TAG_NO_AUTH_REQUIRED)
6415 .Authorization(TAG_EC_CURVE, curve)
6416 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6417 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6418 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006419 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6420 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006421 << "Failed to generate key";
6422 ASSERT_GT(cert_chain_.size(), 0);
6423 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6424 ASSERT_NE(kmKeyCert, nullptr);
6425 // Check that keyAgreement (bit 4) is set in KeyUsage
6426 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6427 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6428 ASSERT_NE(kmPkey, nullptr);
6429 if (dump_Attestations) {
6430 for (size_t n = 0; n < cert_chain_.size(); n++) {
6431 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6432 }
6433 }
6434
6435 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6436 if (curve != localCurve) {
6437 // If the keys are using different curves KeyMint should fail with
6438 // ErrorCode:INVALID_ARGUMENT. Check that.
6439 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6440 string ZabFromKeyMintStr;
6441 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6442 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6443 &ZabFromKeyMintStr));
6444
6445 } else {
6446 // Otherwise if the keys are using the same curve, it should work.
6447 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6448 string ZabFromKeyMintStr;
6449 EXPECT_EQ(ErrorCode::OK,
6450 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6451 &ZabFromKeyMintStr));
6452 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6453
6454 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6455 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6456 ASSERT_NE(ctx, nullptr);
6457 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6458 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6459 size_t ZabFromTestLen = 0;
6460 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6461 vector<uint8_t> ZabFromTest;
6462 ZabFromTest.resize(ZabFromTestLen);
6463 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6464
6465 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6466 }
6467
6468 CheckedDeleteKey();
6469 }
6470 }
6471}
6472
6473INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6474
David Drysdaled2cc8c22021-04-15 13:29:45 +01006475using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6476
6477// This is a problematic test, as it can render the device under test permanently unusable.
6478// Re-enable and run at your own risk.
6479TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6480 auto result = DestroyAttestationIds();
6481 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6482}
6483
6484INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6485
Shawn Willdend659c7c2021-02-19 14:51:51 -07006486using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006487
David Drysdaledb0dcf52021-05-18 11:43:31 +01006488/*
6489 * EarlyBootKeyTest.CreateEarlyBootKeys
6490 *
6491 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6492 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006493TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01006494 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006495 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6496 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6497
David Drysdaleadfe6112021-05-27 12:00:53 +01006498 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6499 ASSERT_GT(keyData.blob.size(), 0U);
6500 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6501 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6502 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006503 CheckedDeleteKey(&aesKeyData.blob);
6504 CheckedDeleteKey(&hmacKeyData.blob);
6505 CheckedDeleteKey(&rsaKeyData.blob);
6506 CheckedDeleteKey(&ecdsaKeyData.blob);
6507}
6508
David Drysdaledb0dcf52021-05-18 11:43:31 +01006509/*
David Drysdaleadfe6112021-05-27 12:00:53 +01006510 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6511 *
6512 * Verifies that creating an early boot key with attestation succeeds.
6513 */
6514TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6515 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6516 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6517 builder->AttestationChallenge("challenge");
6518 builder->AttestationApplicationId("app_id");
6519 });
6520
6521 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6522 ASSERT_GT(keyData.blob.size(), 0U);
6523 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6524 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6525 }
6526 CheckedDeleteKey(&aesKeyData.blob);
6527 CheckedDeleteKey(&hmacKeyData.blob);
6528 CheckedDeleteKey(&rsaKeyData.blob);
6529 CheckedDeleteKey(&ecdsaKeyData.blob);
6530}
6531
6532/*
6533 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01006534 *
6535 * Verifies that using early boot keys at a later stage fails.
6536 */
6537TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6538 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6539 .Authorization(TAG_NO_AUTH_REQUIRED)
6540 .Authorization(TAG_EARLY_BOOT_ONLY)
6541 .HmacKey(128)
6542 .Digest(Digest::SHA_2_256)
6543 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6544 AuthorizationSet output_params;
6545 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6546 AuthorizationSetBuilder()
6547 .Digest(Digest::SHA_2_256)
6548 .Authorization(TAG_MAC_LENGTH, 256),
6549 &output_params));
6550}
6551
6552/*
6553 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6554 *
6555 * Verifies that importing early boot keys fails.
6556 */
6557TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6558 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6559 .Authorization(TAG_NO_AUTH_REQUIRED)
6560 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01006561 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01006562 .Digest(Digest::SHA_2_256)
6563 .SetDefaultValidity(),
6564 KeyFormat::PKCS8, ec_256_key));
6565}
6566
David Drysdaled2cc8c22021-04-15 13:29:45 +01006567// 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 +00006568// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6569// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6570// early boot, so you'll have to reboot between runs.
6571TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6572 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6573 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6574 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6575 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6576 EXPECT_TRUE(
6577 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6578 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6579 EXPECT_TRUE(
6580 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6581
6582 // Should be able to use keys, since early boot has not ended
6583 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6584 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6585 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6586 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6587
6588 // End early boot
6589 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6590 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6591
6592 // Should not be able to use already-created keys.
6593 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6594 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6595 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6596 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6597
6598 CheckedDeleteKey(&aesKeyData.blob);
6599 CheckedDeleteKey(&hmacKeyData.blob);
6600 CheckedDeleteKey(&rsaKeyData.blob);
6601 CheckedDeleteKey(&ecdsaKeyData.blob);
6602
6603 // Should not be able to create new keys
6604 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6605 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6606
6607 CheckedDeleteKey(&aesKeyData.blob);
6608 CheckedDeleteKey(&hmacKeyData.blob);
6609 CheckedDeleteKey(&rsaKeyData.blob);
6610 CheckedDeleteKey(&ecdsaKeyData.blob);
6611}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006612
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006613INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6614
Shawn Willdend659c7c2021-02-19 14:51:51 -07006615using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006616
6617// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6618// between runs... and on most test devices there are no enrolled credentials so it can't be
6619// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6620// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6621// a manual test process, which includes unlocking between runs, which is why it's included here.
6622// Well, that and the fact that it's the only test we can do without also making calls into the
6623// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6624// implications might be, so that may or may not be a solution.
6625TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6626 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6627 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6628
6629 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6630 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6631 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6632 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6633
6634 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006635 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006636 ASSERT_EQ(ErrorCode::OK, rc);
6637 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6638 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6639 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6640 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6641
6642 CheckedDeleteKey(&aesKeyData.blob);
6643 CheckedDeleteKey(&hmacKeyData.blob);
6644 CheckedDeleteKey(&rsaKeyData.blob);
6645 CheckedDeleteKey(&ecdsaKeyData.blob);
6646}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006647
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006648INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6649
Janis Danisevskis24c04702020-12-16 18:28:39 -08006650} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006651
6652int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006653 std::cout << "Testing ";
6654 auto halInstances =
6655 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6656 std::cout << "HAL instances:\n";
6657 for (auto& entry : halInstances) {
6658 std::cout << " " << entry << '\n';
6659 }
6660
Selene Huang31ab4042020-04-29 04:22:39 -07006661 ::testing::InitGoogleTest(&argc, argv);
6662 for (int i = 1; i < argc; ++i) {
6663 if (argv[i][0] == '-') {
6664 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006665 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6666 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006667 }
6668 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006669 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6670 dump_Attestations = true;
6671 } else {
6672 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006673 }
David Drysdalebb3d85e2021-04-13 11:15:51 +01006674 // TODO(drysdale): Remove this flag when available KeyMint devices comply with spec
6675 if (std::string(argv[i]) == "--check_patchLevels") {
6676 aidl::android::hardware::security::keymint::test::check_patchLevels = true;
6677 }
Selene Huang31ab4042020-04-29 04:22:39 -07006678 }
6679 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006680 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006681}