blob: a90ee658432a04b721c5f7dcecb03edc2232fd99 [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.
David Drysdale0fce69d2021-04-13 17:22:13 +0100954 *
955 * This test is disabled because the KeyMint specification does not require that implementations
956 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
957 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +0100958 */
David Drysdale0fce69d2021-04-13 17:22:13 +0100959TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +0100960 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
961 // instance.
962 std::shared_ptr<IRemotelyProvisionedComponent> rp;
963 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
964 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
965
966 // Generate a P-256 keypair to use as an attestation key.
967 MacedPublicKey macedPubKey;
968 std::vector<uint8_t> privateKeyBlob;
969 auto status =
970 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
971 ASSERT_TRUE(status.isOk());
972 vector<uint8_t> coseKeyData;
973 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
974
975 AttestationKey attestation_key;
976 attestation_key.keyBlob = std::move(privateKeyBlob);
977 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
978
979 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
980 auto challenge = "hello";
981 auto app_id = "foo";
982
983 vector<uint8_t> key_blob;
984 vector<KeyCharacteristics> key_characteristics;
985 ASSERT_EQ(ErrorCode::OK,
986 GenerateKey(AuthorizationSetBuilder()
987 .RsaSigningKey(key_size, 65537)
988 .Digest(Digest::NONE)
989 .Padding(PaddingMode::NONE)
990 .AttestationChallenge(challenge)
991 .AttestationApplicationId(app_id)
992 .Authorization(TAG_NO_AUTH_REQUIRED)
993 .SetDefaultValidity(),
994 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
995
996 ASSERT_GT(key_blob.size(), 0U);
997 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100998 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +0100999
1000 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1001
1002 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1003 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1004 << "Key size " << key_size << "missing";
1005 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1006
1007 // Attestation by itself is not valid (last entry is not self-signed).
1008 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1009
1010 // The signature over the attested key should correspond to the P256 public key.
1011 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1012 ASSERT_TRUE(key_cert.get());
1013 EVP_PKEY_Ptr signing_pubkey;
1014 p256_pub_key(coseKeyData, &signing_pubkey);
1015 ASSERT_TRUE(signing_pubkey.get());
1016
1017 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1018 << "Verification of attested certificate failed "
1019 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1020
1021 CheckedDeleteKey(&key_blob);
1022 }
1023}
1024
1025/*
Selene Huang4f64c222021-04-13 19:54:36 -07001026 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1027 *
1028 * Verifies that keymint attestation for RSA encryption keys with challenge and
1029 * app id is also successful.
1030 */
1031TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1032 auto key_size = 2048;
1033 auto challenge = "hello";
1034 auto app_id = "foo";
1035
Selene Huang6e46f142021-04-20 19:20:11 -07001036 auto subject = "subj 2";
1037 vector<uint8_t> subject_der(make_name_from_str(subject));
1038
1039 uint64_t serial_int = 111166;
1040 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1041
Selene Huang4f64c222021-04-13 19:54:36 -07001042 vector<uint8_t> key_blob;
1043 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001044 ASSERT_EQ(ErrorCode::OK,
1045 GenerateKey(AuthorizationSetBuilder()
1046 .RsaEncryptionKey(key_size, 65537)
1047 .Padding(PaddingMode::NONE)
1048 .AttestationChallenge(challenge)
1049 .AttestationApplicationId(app_id)
1050 .Authorization(TAG_NO_AUTH_REQUIRED)
1051 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1052 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1053 .SetDefaultValidity(),
1054 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001055
1056 ASSERT_GT(key_blob.size(), 0U);
1057 AuthorizationSet auths;
1058 for (auto& entry : key_characteristics) {
1059 auths.push_back(AuthorizationSet(entry.authorizations));
1060 }
1061
1062 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1063 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1064
1065 // Verify that App data and ROT are NOT included.
1066 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1067 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1068
1069 // Check that some unexpected tags/values are NOT present.
1070 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1071 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1072
1073 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1074
1075 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1076 ASSERT_TRUE(os_ver);
1077 EXPECT_EQ(*os_ver, os_version());
1078
1079 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1080
1081 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1082 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1083 << "Key size " << key_size << "missing";
1084 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1085
Selene Huang6e46f142021-04-20 19:20:11 -07001086 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001087 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1088 ASSERT_GT(cert_chain_.size(), 0);
1089
1090 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1091 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1092 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1093 sw_enforced, hw_enforced, SecLevel(),
1094 cert_chain_[0].encodedCertificate));
1095
1096 CheckedDeleteKey(&key_blob);
1097}
1098
1099/*
1100 * NewKeyGenerationTest.RsaWithSelfSign
1101 *
1102 * Verifies that attesting to RSA key generation is successful, and returns
1103 * self signed certificate if no challenge is provided. And signing etc
1104 * works as expected.
1105 */
1106TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001107 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1108 vector<uint8_t> subject_der(make_name_from_str(subject));
1109
1110 uint64_t serial_int = 0;
1111 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1112
Selene Huang4f64c222021-04-13 19:54:36 -07001113 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1114 vector<uint8_t> key_blob;
1115 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001116 ASSERT_EQ(ErrorCode::OK,
1117 GenerateKey(AuthorizationSetBuilder()
1118 .RsaSigningKey(key_size, 65537)
1119 .Digest(Digest::NONE)
1120 .Padding(PaddingMode::NONE)
1121 .Authorization(TAG_NO_AUTH_REQUIRED)
1122 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1123 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1124 .SetDefaultValidity(),
1125 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001126
1127 ASSERT_GT(key_blob.size(), 0U);
1128 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001129 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001130
1131 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1132
1133 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1134 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1135 << "Key size " << key_size << "missing";
1136 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1137
Selene Huang6e46f142021-04-20 19:20:11 -07001138 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001139 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1140 ASSERT_EQ(cert_chain_.size(), 1);
1141
1142 CheckedDeleteKey(&key_blob);
1143 }
1144}
1145
1146/*
1147 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1148 *
1149 * Verifies that attesting to RSA checks for missing app ID.
1150 */
1151TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1152 auto challenge = "hello";
1153 vector<uint8_t> key_blob;
1154 vector<KeyCharacteristics> key_characteristics;
1155
1156 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1157 GenerateKey(AuthorizationSetBuilder()
1158 .RsaSigningKey(2048, 65537)
1159 .Digest(Digest::NONE)
1160 .Padding(PaddingMode::NONE)
1161 .AttestationChallenge(challenge)
1162 .Authorization(TAG_NO_AUTH_REQUIRED)
1163 .SetDefaultValidity(),
1164 &key_blob, &key_characteristics));
1165}
1166
1167/*
1168 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1169 *
1170 * Verifies that attesting to RSA ignores app id if challenge is missing.
1171 */
1172TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1173 auto key_size = 2048;
1174 auto app_id = "foo";
1175
Selene Huang6e46f142021-04-20 19:20:11 -07001176 auto subject = "cert subj 2";
1177 vector<uint8_t> subject_der(make_name_from_str(subject));
1178
1179 uint64_t serial_int = 1;
1180 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1181
Selene Huang4f64c222021-04-13 19:54:36 -07001182 vector<uint8_t> key_blob;
1183 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001184 ASSERT_EQ(ErrorCode::OK,
1185 GenerateKey(AuthorizationSetBuilder()
1186 .RsaSigningKey(key_size, 65537)
1187 .Digest(Digest::NONE)
1188 .Padding(PaddingMode::NONE)
1189 .AttestationApplicationId(app_id)
1190 .Authorization(TAG_NO_AUTH_REQUIRED)
1191 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1192 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1193 .SetDefaultValidity(),
1194 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001195
1196 ASSERT_GT(key_blob.size(), 0U);
1197 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001198 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001199
1200 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1201
1202 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1203 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1204 << "Key size " << key_size << "missing";
1205 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1206
Selene Huang6e46f142021-04-20 19:20:11 -07001207 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001208 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1209 ASSERT_EQ(cert_chain_.size(), 1);
1210
1211 CheckedDeleteKey(&key_blob);
1212}
1213
1214/*
Qi Wud22ec842020-11-26 13:27:53 +08001215 * NewKeyGenerationTest.LimitedUsageRsa
1216 *
1217 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1218 * resulting keys have correct characteristics.
1219 */
1220TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1221 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1222 vector<uint8_t> key_blob;
1223 vector<KeyCharacteristics> key_characteristics;
1224 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1225 .RsaSigningKey(key_size, 65537)
1226 .Digest(Digest::NONE)
1227 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001228 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1229 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001230 &key_blob, &key_characteristics));
1231
1232 ASSERT_GT(key_blob.size(), 0U);
1233 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001234 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001235
1236 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1237
1238 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1239 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1240 << "Key size " << key_size << "missing";
1241 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1242
1243 // Check the usage count limit tag appears in the authorizations.
1244 AuthorizationSet auths;
1245 for (auto& entry : key_characteristics) {
1246 auths.push_back(AuthorizationSet(entry.authorizations));
1247 }
1248 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1249 << "key usage count limit " << 1U << " missing";
1250
1251 CheckedDeleteKey(&key_blob);
1252 }
1253}
1254
1255/*
Qi Wubeefae42021-01-28 23:16:37 +08001256 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1257 *
1258 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1259 * resulting keys have correct characteristics and attestation.
1260 */
1261TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001262 auto challenge = "hello";
1263 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001264
Selene Huang6e46f142021-04-20 19:20:11 -07001265 auto subject = "cert subj 2";
1266 vector<uint8_t> subject_der(make_name_from_str(subject));
1267
1268 uint64_t serial_int = 66;
1269 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1270
Selene Huang4f64c222021-04-13 19:54:36 -07001271 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001272 vector<uint8_t> key_blob;
1273 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001274 ASSERT_EQ(ErrorCode::OK,
1275 GenerateKey(AuthorizationSetBuilder()
1276 .RsaSigningKey(key_size, 65537)
1277 .Digest(Digest::NONE)
1278 .Padding(PaddingMode::NONE)
1279 .AttestationChallenge(challenge)
1280 .AttestationApplicationId(app_id)
1281 .Authorization(TAG_NO_AUTH_REQUIRED)
1282 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1283 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1284 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1285 .SetDefaultValidity(),
1286 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001287
1288 ASSERT_GT(key_blob.size(), 0U);
1289 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001290 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001291
1292 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1293
1294 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1295 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1296 << "Key size " << key_size << "missing";
1297 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1298
1299 // Check the usage count limit tag appears in the authorizations.
1300 AuthorizationSet auths;
1301 for (auto& entry : key_characteristics) {
1302 auths.push_back(AuthorizationSet(entry.authorizations));
1303 }
1304 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1305 << "key usage count limit " << 1U << " missing";
1306
1307 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001308 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001309 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001310 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001311
1312 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1313 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1314 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1315 sw_enforced, hw_enforced, SecLevel(),
1316 cert_chain_[0].encodedCertificate));
1317
1318 CheckedDeleteKey(&key_blob);
1319 }
1320}
1321
1322/*
Selene Huang31ab4042020-04-29 04:22:39 -07001323 * NewKeyGenerationTest.NoInvalidRsaSizes
1324 *
1325 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1326 */
1327TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1328 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1329 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001330 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001331 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1332 GenerateKey(AuthorizationSetBuilder()
1333 .RsaSigningKey(key_size, 65537)
1334 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001335 .Padding(PaddingMode::NONE)
1336 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001337 &key_blob, &key_characteristics));
1338 }
1339}
1340
1341/*
1342 * NewKeyGenerationTest.RsaNoDefaultSize
1343 *
1344 * Verifies that failing to specify a key size for RSA key generation returns
1345 * UNSUPPORTED_KEY_SIZE.
1346 */
1347TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1348 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1349 GenerateKey(AuthorizationSetBuilder()
1350 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1351 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001352 .SigningKey()
1353 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001354}
1355
1356/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001357 * NewKeyGenerationTest.RsaMissingParams
1358 *
1359 * Verifies that omitting optional tags works.
1360 */
1361TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1362 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1363 ASSERT_EQ(ErrorCode::OK,
1364 GenerateKey(
1365 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1366 CheckedDeleteKey();
1367 }
1368}
1369
1370/*
Selene Huang31ab4042020-04-29 04:22:39 -07001371 * NewKeyGenerationTest.Ecdsa
1372 *
1373 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1374 * have correct characteristics.
1375 */
1376TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001377 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001378 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001379 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001380 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001381 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001382 .Digest(Digest::NONE)
1383 .SetDefaultValidity(),
1384 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001385 ASSERT_GT(key_blob.size(), 0U);
1386 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001387 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001388
Shawn Willden7f424372021-01-10 18:06:50 -07001389 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001390
1391 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001392 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001393
1394 CheckedDeleteKey(&key_blob);
1395 }
1396}
1397
1398/*
Selene Huang4f64c222021-04-13 19:54:36 -07001399 * NewKeyGenerationTest.EcdsaAttestation
1400 *
1401 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1402 * an attestation will be generated.
1403 */
1404TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1405 auto challenge = "hello";
1406 auto app_id = "foo";
1407
Selene Huang6e46f142021-04-20 19:20:11 -07001408 auto subject = "cert subj 2";
1409 vector<uint8_t> subject_der(make_name_from_str(subject));
1410
1411 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1412 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1413
David Drysdaledf09e542021-06-08 15:46:11 +01001414 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001415 vector<uint8_t> key_blob;
1416 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001417 ASSERT_EQ(ErrorCode::OK,
1418 GenerateKey(AuthorizationSetBuilder()
1419 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001420 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001421 .Digest(Digest::NONE)
1422 .AttestationChallenge(challenge)
1423 .AttestationApplicationId(app_id)
1424 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1425 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1426 .SetDefaultValidity(),
1427 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001428 ASSERT_GT(key_blob.size(), 0U);
1429 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001430 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001431
1432 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1433
1434 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001435 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001436
1437 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1438 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001439 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001440
1441 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1442 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1443 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1444 sw_enforced, hw_enforced, SecLevel(),
1445 cert_chain_[0].encodedCertificate));
1446
1447 CheckedDeleteKey(&key_blob);
1448 }
1449}
1450
1451/*
David Drysdale37af4b32021-05-14 16:46:59 +01001452 * NewKeyGenerationTest.EcdsaAttestationTags
1453 *
1454 * Verifies that creation of an attested ECDSA key includes various tags in the
1455 * attestation extension.
1456 */
1457TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1458 auto challenge = "hello";
1459 auto app_id = "foo";
1460 auto subject = "cert subj 2";
1461 vector<uint8_t> subject_der(make_name_from_str(subject));
1462 uint64_t serial_int = 0x1010;
1463 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1464 const AuthorizationSetBuilder base_builder =
1465 AuthorizationSetBuilder()
1466 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001467 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001468 .Digest(Digest::NONE)
1469 .AttestationChallenge(challenge)
1470 .AttestationApplicationId(app_id)
1471 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1472 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1473 .SetDefaultValidity();
1474
1475 // Various tags that map to fields in the attestation extension ASN.1 schema.
1476 auto extra_tags = AuthorizationSetBuilder()
1477 .Authorization(TAG_ROLLBACK_RESISTANCE)
1478 .Authorization(TAG_EARLY_BOOT_ONLY)
1479 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1480 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1481 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1482 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1483 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1484 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1485 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1486 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1487 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1488 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
1489 for (const KeyParameter& tag : extra_tags) {
1490 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1491 vector<uint8_t> key_blob;
1492 vector<KeyCharacteristics> key_characteristics;
1493 AuthorizationSetBuilder builder = base_builder;
1494 builder.push_back(tag);
1495 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1496 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1497 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1498 continue;
1499 }
Seth Mooreb393b082021-07-12 14:18:28 -07001500 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1501 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001502 continue;
1503 }
1504 ASSERT_EQ(result, ErrorCode::OK);
1505 ASSERT_GT(key_blob.size(), 0U);
1506
1507 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1508 ASSERT_GT(cert_chain_.size(), 0);
1509 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1510
1511 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1512 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001513 // Some tags are optional, so don't require them to be in the enforcements.
1514 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001515 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1516 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1517 }
1518
1519 // Verifying the attestation record will check for the specific tag because
1520 // it's included in the authorizations.
1521 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1522 SecLevel(), cert_chain_[0].encodedCertificate));
1523
1524 CheckedDeleteKey(&key_blob);
1525 }
1526
1527 // Device attestation IDs should be rejected for normal attestation requests; these fields
1528 // are only used for device unique attestation.
1529 auto invalid_tags = AuthorizationSetBuilder()
1530 .Authorization(TAG_ATTESTATION_ID_BRAND, "brand")
1531 .Authorization(TAG_ATTESTATION_ID_DEVICE, "device")
1532 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "product")
1533 .Authorization(TAG_ATTESTATION_ID_SERIAL, "serial")
1534 .Authorization(TAG_ATTESTATION_ID_IMEI, "imei")
1535 .Authorization(TAG_ATTESTATION_ID_MEID, "meid")
1536 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer")
1537 .Authorization(TAG_ATTESTATION_ID_MODEL, "model");
1538 for (const KeyParameter& tag : invalid_tags) {
1539 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1540 vector<uint8_t> key_blob;
1541 vector<KeyCharacteristics> key_characteristics;
1542 AuthorizationSetBuilder builder =
1543 AuthorizationSetBuilder()
1544 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001545 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001546 .Digest(Digest::NONE)
1547 .AttestationChallenge(challenge)
1548 .AttestationApplicationId(app_id)
1549 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1550 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1551 .SetDefaultValidity();
1552 builder.push_back(tag);
1553 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1554 GenerateKey(builder, &key_blob, &key_characteristics));
1555 }
1556}
1557
1558/*
1559 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1560 *
1561 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1562 */
1563TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1564 auto challenge = "hello";
1565 auto attest_app_id = "foo";
1566 auto subject = "cert subj 2";
1567 vector<uint8_t> subject_der(make_name_from_str(subject));
1568 uint64_t serial_int = 0x1010;
1569 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1570
1571 // Earlier versions of the attestation extension schema included a slot:
1572 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1573 // This should never have been included, and should never be filled in.
1574 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1575 // to confirm that this field never makes it into the attestation extension.
1576 vector<uint8_t> key_blob;
1577 vector<KeyCharacteristics> key_characteristics;
1578 auto result = GenerateKey(AuthorizationSetBuilder()
1579 .Authorization(TAG_NO_AUTH_REQUIRED)
1580 .EcdsaSigningKey(EcCurve::P_256)
1581 .Digest(Digest::NONE)
1582 .AttestationChallenge(challenge)
1583 .AttestationApplicationId(attest_app_id)
1584 .Authorization(TAG_APPLICATION_ID, "client_id")
1585 .Authorization(TAG_APPLICATION_DATA, "appdata")
1586 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1587 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1588 .SetDefaultValidity(),
1589 &key_blob, &key_characteristics);
1590 ASSERT_EQ(result, ErrorCode::OK);
1591 ASSERT_GT(key_blob.size(), 0U);
1592
1593 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1594 ASSERT_GT(cert_chain_.size(), 0);
1595 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1596
1597 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1598 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1599 EXPECT_TRUE(verify_attestation_record(challenge, attest_app_id, sw_enforced, hw_enforced,
1600 SecLevel(), cert_chain_[0].encodedCertificate));
1601
1602 // Check that the app id is not in the cert.
1603 string app_id = "clientid";
1604 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1605 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1606 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1607 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1608 cert_chain_[0].encodedCertificate.end());
1609
1610 CheckedDeleteKey(&key_blob);
1611}
1612
1613/*
Selene Huang4f64c222021-04-13 19:54:36 -07001614 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1615 *
1616 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1617 * the key will generate a self signed attestation.
1618 */
1619TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001620 auto subject = "cert subj 2";
1621 vector<uint8_t> subject_der(make_name_from_str(subject));
1622
1623 uint64_t serial_int = 0x123456FFF1234;
1624 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1625
David Drysdaledf09e542021-06-08 15:46:11 +01001626 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001627 vector<uint8_t> key_blob;
1628 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001629 ASSERT_EQ(ErrorCode::OK,
1630 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001631 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001632 .Digest(Digest::NONE)
1633 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1634 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1635 .SetDefaultValidity(),
1636 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001637 ASSERT_GT(key_blob.size(), 0U);
1638 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001639 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001640
1641 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1642
1643 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001644 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001645
1646 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001647 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001648 ASSERT_EQ(cert_chain_.size(), 1);
1649
1650 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1651 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1652
1653 CheckedDeleteKey(&key_blob);
1654 }
1655}
1656
1657/*
1658 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1659 *
1660 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1661 * app id must also be provided or else it will fail.
1662 */
1663TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1664 auto challenge = "hello";
1665 vector<uint8_t> key_blob;
1666 vector<KeyCharacteristics> key_characteristics;
1667
1668 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1669 GenerateKey(AuthorizationSetBuilder()
1670 .EcdsaSigningKey(EcCurve::P_256)
1671 .Digest(Digest::NONE)
1672 .AttestationChallenge(challenge)
1673 .SetDefaultValidity(),
1674 &key_blob, &key_characteristics));
1675}
1676
1677/*
1678 * NewKeyGenerationTest.EcdsaIgnoreAppId
1679 *
1680 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1681 * any appid will be ignored, and keymint will generate a self sign certificate.
1682 */
1683TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1684 auto app_id = "foo";
1685
David Drysdaledf09e542021-06-08 15:46:11 +01001686 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001687 vector<uint8_t> key_blob;
1688 vector<KeyCharacteristics> key_characteristics;
1689 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001690 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001691 .Digest(Digest::NONE)
1692 .AttestationApplicationId(app_id)
1693 .SetDefaultValidity(),
1694 &key_blob, &key_characteristics));
1695
1696 ASSERT_GT(key_blob.size(), 0U);
1697 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001698 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001699
1700 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1701
1702 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001703 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001704
1705 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1706 ASSERT_EQ(cert_chain_.size(), 1);
1707
1708 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1709 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1710
1711 CheckedDeleteKey(&key_blob);
1712 }
1713}
1714
1715/*
1716 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1717 *
1718 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1719 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1720 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1721 * to specify how many following bytes will be used to encode the length.
1722 */
1723TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1724 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001725 std::vector<uint32_t> app_id_lengths{143, 258};
1726
1727 for (uint32_t length : app_id_lengths) {
1728 const string app_id(length, 'a');
1729 vector<uint8_t> key_blob;
1730 vector<KeyCharacteristics> key_characteristics;
1731 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1732 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001733 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001734 .Digest(Digest::NONE)
1735 .AttestationChallenge(challenge)
1736 .AttestationApplicationId(app_id)
1737 .SetDefaultValidity(),
1738 &key_blob, &key_characteristics));
1739 ASSERT_GT(key_blob.size(), 0U);
1740 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001741 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001742
1743 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1744
1745 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001746 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001747
1748 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1749 ASSERT_GT(cert_chain_.size(), 0);
1750
1751 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1752 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1753 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1754 sw_enforced, hw_enforced, SecLevel(),
1755 cert_chain_[0].encodedCertificate));
1756
1757 CheckedDeleteKey(&key_blob);
1758 }
1759}
1760
1761/*
Qi Wud22ec842020-11-26 13:27:53 +08001762 * NewKeyGenerationTest.LimitedUsageEcdsa
1763 *
1764 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1765 * resulting keys have correct characteristics.
1766 */
1767TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001768 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001769 vector<uint8_t> key_blob;
1770 vector<KeyCharacteristics> key_characteristics;
1771 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001772 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001773 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001774 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1775 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001776 &key_blob, &key_characteristics));
1777
1778 ASSERT_GT(key_blob.size(), 0U);
1779 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001780 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001781
1782 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1783
1784 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001785 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001786
1787 // Check the usage count limit tag appears in the authorizations.
1788 AuthorizationSet auths;
1789 for (auto& entry : key_characteristics) {
1790 auths.push_back(AuthorizationSet(entry.authorizations));
1791 }
1792 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1793 << "key usage count limit " << 1U << " missing";
1794
1795 CheckedDeleteKey(&key_blob);
1796 }
1797}
1798
1799/*
Selene Huang31ab4042020-04-29 04:22:39 -07001800 * NewKeyGenerationTest.EcdsaDefaultSize
1801 *
David Drysdaledf09e542021-06-08 15:46:11 +01001802 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001803 * UNSUPPORTED_KEY_SIZE.
1804 */
1805TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1806 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1807 GenerateKey(AuthorizationSetBuilder()
1808 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1809 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001810 .Digest(Digest::NONE)
1811 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001812}
1813
1814/*
1815 * NewKeyGenerationTest.EcdsaInvalidSize
1816 *
1817 * Verifies that specifying an invalid key size for EC key generation returns
1818 * UNSUPPORTED_KEY_SIZE.
1819 */
1820TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdaledf09e542021-06-08 15:46:11 +01001821 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001822 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001823 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001824 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001825 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001826 .Digest(Digest::NONE)
1827 .SetDefaultValidity(),
1828 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001829 }
1830
David Drysdaledf09e542021-06-08 15:46:11 +01001831 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1832 GenerateKey(AuthorizationSetBuilder()
1833 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1834 .Authorization(TAG_KEY_SIZE, 190)
1835 .SigningKey()
1836 .Digest(Digest::NONE)
1837 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001838}
1839
1840/*
1841 * NewKeyGenerationTest.EcdsaMismatchKeySize
1842 *
1843 * Verifies that specifying mismatched key size and curve for EC key generation returns
1844 * INVALID_ARGUMENT.
1845 */
1846TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1847 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1848
David Drysdaledf09e542021-06-08 15:46:11 +01001849 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01001850 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01001851 .Authorization(TAG_KEY_SIZE, 224)
1852 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01001853 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01001854 .Digest(Digest::NONE)
1855 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01001856 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07001857}
1858
1859/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001860 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07001861 *
1862 * Verifies that keymint does not support any curve designated as unsupported.
1863 */
1864TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1865 Digest digest;
1866 if (SecLevel() == SecurityLevel::STRONGBOX) {
1867 digest = Digest::SHA_2_256;
1868 } else {
1869 digest = Digest::SHA_2_512;
1870 }
1871 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001872 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1873 .EcdsaSigningKey(curve)
1874 .Digest(digest)
1875 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001876 << "Failed to generate key on curve: " << curve;
1877 CheckedDeleteKey();
1878 }
1879}
1880
1881/*
1882 * NewKeyGenerationTest.Hmac
1883 *
1884 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1885 * characteristics.
1886 */
1887TEST_P(NewKeyGenerationTest, Hmac) {
1888 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1889 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001890 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001891 constexpr size_t key_size = 128;
1892 ASSERT_EQ(ErrorCode::OK,
1893 GenerateKey(
1894 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1895 TAG_MIN_MAC_LENGTH, 128),
1896 &key_blob, &key_characteristics));
1897
1898 ASSERT_GT(key_blob.size(), 0U);
1899 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001900 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001901
Shawn Willden7f424372021-01-10 18:06:50 -07001902 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1903 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1904 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1905 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001906
1907 CheckedDeleteKey(&key_blob);
1908 }
1909}
1910
1911/*
Selene Huang4f64c222021-04-13 19:54:36 -07001912 * NewKeyGenerationTest.HmacNoAttestation
1913 *
1914 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1915 * and app id are provided.
1916 */
1917TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1918 auto challenge = "hello";
1919 auto app_id = "foo";
1920
1921 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1922 vector<uint8_t> key_blob;
1923 vector<KeyCharacteristics> key_characteristics;
1924 constexpr size_t key_size = 128;
1925 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1926 .HmacKey(key_size)
1927 .Digest(digest)
1928 .AttestationChallenge(challenge)
1929 .AttestationApplicationId(app_id)
1930 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1931 &key_blob, &key_characteristics));
1932
1933 ASSERT_GT(key_blob.size(), 0U);
1934 ASSERT_EQ(cert_chain_.size(), 0);
1935 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001936 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001937
1938 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1939 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1940 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1941 << "Key size " << key_size << "missing";
1942
1943 CheckedDeleteKey(&key_blob);
1944 }
1945}
1946
1947/*
Qi Wud22ec842020-11-26 13:27:53 +08001948 * NewKeyGenerationTest.LimitedUsageHmac
1949 *
1950 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1951 * resulting keys have correct characteristics.
1952 */
1953TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1954 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1955 vector<uint8_t> key_blob;
1956 vector<KeyCharacteristics> key_characteristics;
1957 constexpr size_t key_size = 128;
1958 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1959 .HmacKey(key_size)
1960 .Digest(digest)
1961 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1962 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1963 &key_blob, &key_characteristics));
1964
1965 ASSERT_GT(key_blob.size(), 0U);
1966 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001967 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001968
1969 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1970 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1971 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1972 << "Key size " << key_size << "missing";
1973
1974 // Check the usage count limit tag appears in the authorizations.
1975 AuthorizationSet auths;
1976 for (auto& entry : key_characteristics) {
1977 auths.push_back(AuthorizationSet(entry.authorizations));
1978 }
1979 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1980 << "key usage count limit " << 1U << " missing";
1981
1982 CheckedDeleteKey(&key_blob);
1983 }
1984}
1985
1986/*
Selene Huang31ab4042020-04-29 04:22:39 -07001987 * NewKeyGenerationTest.HmacCheckKeySizes
1988 *
1989 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1990 */
1991TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1992 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1993 if (key_size < 64 || key_size % 8 != 0) {
1994 // To keep this test from being very slow, we only test a random fraction of
1995 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1996 // them, we expect to run ~40 of them in each run.
1997 if (key_size % 8 == 0 || random() % 10 == 0) {
1998 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1999 GenerateKey(AuthorizationSetBuilder()
2000 .HmacKey(key_size)
2001 .Digest(Digest::SHA_2_256)
2002 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2003 << "HMAC key size " << key_size << " invalid";
2004 }
2005 } else {
2006 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2007 .HmacKey(key_size)
2008 .Digest(Digest::SHA_2_256)
2009 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2010 << "Failed to generate HMAC key of size " << key_size;
2011 CheckedDeleteKey();
2012 }
2013 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002014 if (SecLevel() == SecurityLevel::STRONGBOX) {
2015 // STRONGBOX devices must not support keys larger than 512 bits.
2016 size_t key_size = 520;
2017 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2018 GenerateKey(AuthorizationSetBuilder()
2019 .HmacKey(key_size)
2020 .Digest(Digest::SHA_2_256)
2021 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2022 << "HMAC key size " << key_size << " unexpectedly valid";
2023 }
Selene Huang31ab4042020-04-29 04:22:39 -07002024}
2025
2026/*
2027 * NewKeyGenerationTest.HmacCheckMinMacLengths
2028 *
2029 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2030 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2031 * specific MAC length that failed, so reproducing a failed run will be easy.
2032 */
2033TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2034 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2035 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2036 // To keep this test from being very long, we only test a random fraction of
2037 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2038 // we expect to run ~17 of them in each run.
2039 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2040 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2041 GenerateKey(AuthorizationSetBuilder()
2042 .HmacKey(128)
2043 .Digest(Digest::SHA_2_256)
2044 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2045 << "HMAC min mac length " << min_mac_length << " invalid.";
2046 }
2047 } else {
2048 EXPECT_EQ(ErrorCode::OK,
2049 GenerateKey(AuthorizationSetBuilder()
2050 .HmacKey(128)
2051 .Digest(Digest::SHA_2_256)
2052 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2053 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2054 CheckedDeleteKey();
2055 }
2056 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002057
2058 // Minimum MAC length must be no more than 512 bits.
2059 size_t min_mac_length = 520;
2060 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2061 GenerateKey(AuthorizationSetBuilder()
2062 .HmacKey(128)
2063 .Digest(Digest::SHA_2_256)
2064 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2065 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002066}
2067
2068/*
2069 * NewKeyGenerationTest.HmacMultipleDigests
2070 *
2071 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2072 */
2073TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
2074 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2075
2076 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2077 GenerateKey(AuthorizationSetBuilder()
2078 .HmacKey(128)
2079 .Digest(Digest::SHA1)
2080 .Digest(Digest::SHA_2_256)
2081 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2082}
2083
2084/*
2085 * NewKeyGenerationTest.HmacDigestNone
2086 *
2087 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2088 */
2089TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2090 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2091 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2092 128)));
2093
2094 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2095 GenerateKey(AuthorizationSetBuilder()
2096 .HmacKey(128)
2097 .Digest(Digest::NONE)
2098 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2099}
2100
Selene Huang4f64c222021-04-13 19:54:36 -07002101/*
2102 * NewKeyGenerationTest.AesNoAttestation
2103 *
2104 * Verifies that attestation parameters to AES keys are ignored and generateKey
2105 * will succeed.
2106 */
2107TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2108 auto challenge = "hello";
2109 auto app_id = "foo";
2110
2111 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2112 .Authorization(TAG_NO_AUTH_REQUIRED)
2113 .AesEncryptionKey(128)
2114 .EcbMode()
2115 .Padding(PaddingMode::PKCS7)
2116 .AttestationChallenge(challenge)
2117 .AttestationApplicationId(app_id)));
2118
2119 ASSERT_EQ(cert_chain_.size(), 0);
2120}
2121
2122/*
2123 * NewKeyGenerationTest.TripleDesNoAttestation
2124 *
2125 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2126 * will be successful. No attestation should be generated.
2127 */
2128TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2129 auto challenge = "hello";
2130 auto app_id = "foo";
2131
2132 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2133 .TripleDesEncryptionKey(168)
2134 .BlockMode(BlockMode::ECB)
2135 .Authorization(TAG_NO_AUTH_REQUIRED)
2136 .Padding(PaddingMode::NONE)
2137 .AttestationChallenge(challenge)
2138 .AttestationApplicationId(app_id)));
2139 ASSERT_EQ(cert_chain_.size(), 0);
2140}
2141
Selene Huang31ab4042020-04-29 04:22:39 -07002142INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2143
2144typedef KeyMintAidlTestBase SigningOperationsTest;
2145
2146/*
2147 * SigningOperationsTest.RsaSuccess
2148 *
2149 * Verifies that raw RSA signature operations succeed.
2150 */
2151TEST_P(SigningOperationsTest, RsaSuccess) {
2152 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2153 .RsaSigningKey(2048, 65537)
2154 .Digest(Digest::NONE)
2155 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002156 .Authorization(TAG_NO_AUTH_REQUIRED)
2157 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002158 string message = "12345678901234567890123456789012";
2159 string signature = SignMessage(
2160 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002161 LocalVerifyMessage(message, signature,
2162 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2163}
2164
2165/*
2166 * SigningOperationsTest.RsaAllPaddingsAndDigests
2167 *
2168 * Verifies RSA signature/verification for all padding modes and digests.
2169 */
2170TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2171 auto authorizations = AuthorizationSetBuilder()
2172 .Authorization(TAG_NO_AUTH_REQUIRED)
2173 .RsaSigningKey(2048, 65537)
2174 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2175 .Padding(PaddingMode::NONE)
2176 .Padding(PaddingMode::RSA_PSS)
2177 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2178 .SetDefaultValidity();
2179
2180 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2181
2182 string message(128, 'a');
2183 string corrupt_message(message);
2184 ++corrupt_message[corrupt_message.size() / 2];
2185
2186 for (auto padding :
2187 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2188 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2189 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2190 // Digesting only makes sense with padding.
2191 continue;
2192 }
2193
2194 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2195 // PSS requires digesting.
2196 continue;
2197 }
2198
2199 string signature =
2200 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2201 LocalVerifyMessage(message, signature,
2202 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2203 }
2204 }
Selene Huang31ab4042020-04-29 04:22:39 -07002205}
2206
2207/*
2208 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2209 *
Shawn Willden7f424372021-01-10 18:06:50 -07002210 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002211 */
2212TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2213 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2214 .Authorization(TAG_NO_AUTH_REQUIRED)
2215 .RsaSigningKey(2048, 65537)
2216 .Digest(Digest::NONE)
2217 .Padding(PaddingMode::NONE)
2218 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002219 .Authorization(TAG_APPLICATION_DATA, "appdata")
2220 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002221
2222 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2223
Selene Huang31ab4042020-04-29 04:22:39 -07002224 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2225 Begin(KeyPurpose::SIGN,
2226 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2227 AbortIfNeeded();
2228 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2229 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2230 .Digest(Digest::NONE)
2231 .Padding(PaddingMode::NONE)
2232 .Authorization(TAG_APPLICATION_ID, "clientid")));
2233 AbortIfNeeded();
2234 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2235 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2236 .Digest(Digest::NONE)
2237 .Padding(PaddingMode::NONE)
2238 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2239 AbortIfNeeded();
2240 EXPECT_EQ(ErrorCode::OK,
2241 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2242 .Digest(Digest::NONE)
2243 .Padding(PaddingMode::NONE)
2244 .Authorization(TAG_APPLICATION_DATA, "appdata")
2245 .Authorization(TAG_APPLICATION_ID, "clientid")));
2246 AbortIfNeeded();
2247}
2248
2249/*
2250 * SigningOperationsTest.RsaPssSha256Success
2251 *
2252 * Verifies that RSA-PSS signature operations succeed.
2253 */
2254TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2255 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2256 .RsaSigningKey(2048, 65537)
2257 .Digest(Digest::SHA_2_256)
2258 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002259 .Authorization(TAG_NO_AUTH_REQUIRED)
2260 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002261 // Use large message, which won't work without digesting.
2262 string message(1024, 'a');
2263 string signature = SignMessage(
2264 message,
2265 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2266}
2267
2268/*
2269 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2270 *
2271 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2272 * supports only unpadded operations.
2273 */
2274TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2275 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2276 .RsaSigningKey(2048, 65537)
2277 .Digest(Digest::NONE)
2278 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002279 .Padding(PaddingMode::NONE)
2280 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002281 string message = "12345678901234567890123456789012";
2282 string signature;
2283
2284 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2285 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2286 .Digest(Digest::NONE)
2287 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2288}
2289
2290/*
2291 * SigningOperationsTest.NoUserConfirmation
2292 *
2293 * Verifies that keymint rejects signing operations for keys with
2294 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2295 * presented.
2296 */
2297TEST_P(SigningOperationsTest, NoUserConfirmation) {
2298 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08002299 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2300 .RsaSigningKey(1024, 65537)
2301 .Digest(Digest::NONE)
2302 .Padding(PaddingMode::NONE)
2303 .Authorization(TAG_NO_AUTH_REQUIRED)
2304 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2305 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002306
2307 const string message = "12345678901234567890123456789012";
2308 EXPECT_EQ(ErrorCode::OK,
2309 Begin(KeyPurpose::SIGN,
2310 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2311 string signature;
2312 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2313}
2314
2315/*
2316 * SigningOperationsTest.RsaPkcs1Sha256Success
2317 *
2318 * Verifies that digested RSA-PKCS1 signature operations succeed.
2319 */
2320TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2321 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2322 .RsaSigningKey(2048, 65537)
2323 .Digest(Digest::SHA_2_256)
2324 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002325 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2326 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002327 string message(1024, 'a');
2328 string signature = SignMessage(message, AuthorizationSetBuilder()
2329 .Digest(Digest::SHA_2_256)
2330 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2331}
2332
2333/*
2334 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2335 *
2336 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2337 */
2338TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2339 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2340 .RsaSigningKey(2048, 65537)
2341 .Digest(Digest::NONE)
2342 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002343 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2344 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002345 string message(53, 'a');
2346 string signature = SignMessage(message, AuthorizationSetBuilder()
2347 .Digest(Digest::NONE)
2348 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2349}
2350
2351/*
2352 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2353 *
2354 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2355 * given a too-long message.
2356 */
2357TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2358 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2359 .RsaSigningKey(2048, 65537)
2360 .Digest(Digest::NONE)
2361 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002362 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2363 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002364 string message(257, 'a');
2365
2366 EXPECT_EQ(ErrorCode::OK,
2367 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2368 .Digest(Digest::NONE)
2369 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2370 string signature;
2371 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2372}
2373
2374/*
2375 * SigningOperationsTest.RsaPssSha512TooSmallKey
2376 *
2377 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2378 * used with a key that is too small for the message.
2379 *
2380 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2381 * keymint specification requires that salt_size == digest_size, so the message will be
2382 * digest_size * 2 +
2383 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2384 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2385 * for a 1024-bit key.
2386 */
2387TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
2388 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2389 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2390 .RsaSigningKey(1024, 65537)
2391 .Digest(Digest::SHA_2_512)
2392 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002393 .Padding(PaddingMode::RSA_PSS)
2394 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002395 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2396 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2397 .Digest(Digest::SHA_2_512)
2398 .Padding(PaddingMode::RSA_PSS)));
2399}
2400
2401/*
2402 * SigningOperationsTest.RsaNoPaddingTooLong
2403 *
2404 * Verifies that raw RSA signature operations fail with the correct error code when
2405 * given a too-long message.
2406 */
2407TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2408 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2409 .RsaSigningKey(2048, 65537)
2410 .Digest(Digest::NONE)
2411 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002412 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2413 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002414 // One byte too long
2415 string message(2048 / 8 + 1, 'a');
2416 ASSERT_EQ(ErrorCode::OK,
2417 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2418 .Digest(Digest::NONE)
2419 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2420 string result;
2421 ErrorCode finish_error_code = Finish(message, &result);
2422 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2423 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2424
2425 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2426 message = string(128 * 1024, 'a');
2427 ASSERT_EQ(ErrorCode::OK,
2428 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2429 .Digest(Digest::NONE)
2430 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2431 finish_error_code = Finish(message, &result);
2432 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2433 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2434}
2435
2436/*
2437 * SigningOperationsTest.RsaAbort
2438 *
2439 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2440 * test, but the behavior should be algorithm and purpose-independent.
2441 */
2442TEST_P(SigningOperationsTest, RsaAbort) {
2443 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2444 .RsaSigningKey(2048, 65537)
2445 .Digest(Digest::NONE)
2446 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002447 .Padding(PaddingMode::NONE)
2448 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002449
2450 ASSERT_EQ(ErrorCode::OK,
2451 Begin(KeyPurpose::SIGN,
2452 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2453 EXPECT_EQ(ErrorCode::OK, Abort());
2454
2455 // Another abort should fail
2456 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2457
2458 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002459 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002460}
2461
2462/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002463 * SigningOperationsTest.RsaNonUniqueParams
2464 *
2465 * Verifies that an operation with multiple padding modes is rejected.
2466 */
2467TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2468 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2469 .RsaSigningKey(2048, 65537)
2470 .Digest(Digest::NONE)
2471 .Digest(Digest::SHA1)
2472 .Authorization(TAG_NO_AUTH_REQUIRED)
2473 .Padding(PaddingMode::NONE)
2474 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2475 .SetDefaultValidity()));
2476
2477 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2478 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2479 .Digest(Digest::NONE)
2480 .Padding(PaddingMode::NONE)
2481 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2482
Tommy Chiuc93c4392021-05-11 18:36:50 +08002483 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2484 .Digest(Digest::NONE)
2485 .Digest(Digest::SHA1)
2486 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2487 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002488
2489 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2490 Begin(KeyPurpose::SIGN,
2491 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2492}
2493
2494/*
Selene Huang31ab4042020-04-29 04:22:39 -07002495 * SigningOperationsTest.RsaUnsupportedPadding
2496 *
2497 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2498 * with a padding mode inappropriate for RSA.
2499 */
2500TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2501 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2502 .RsaSigningKey(2048, 65537)
2503 .Authorization(TAG_NO_AUTH_REQUIRED)
2504 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002505 .Padding(PaddingMode::PKCS7)
2506 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002507 ASSERT_EQ(
2508 ErrorCode::UNSUPPORTED_PADDING_MODE,
2509 Begin(KeyPurpose::SIGN,
2510 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002511 CheckedDeleteKey();
2512
2513 ASSERT_EQ(ErrorCode::OK,
2514 GenerateKey(
2515 AuthorizationSetBuilder()
2516 .RsaSigningKey(2048, 65537)
2517 .Authorization(TAG_NO_AUTH_REQUIRED)
2518 .Digest(Digest::SHA_2_256 /* supported digest */)
2519 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2520 .SetDefaultValidity()));
2521 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2522 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2523 .Digest(Digest::SHA_2_256)
2524 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002525}
2526
2527/*
2528 * SigningOperationsTest.RsaPssNoDigest
2529 *
2530 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2531 */
2532TEST_P(SigningOperationsTest, RsaNoDigest) {
2533 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2534 .RsaSigningKey(2048, 65537)
2535 .Authorization(TAG_NO_AUTH_REQUIRED)
2536 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002537 .Padding(PaddingMode::RSA_PSS)
2538 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002539 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2540 Begin(KeyPurpose::SIGN,
2541 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2542
2543 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2544 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2545}
2546
2547/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002548 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002549 *
2550 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2551 * supported in some cases (as validated in other tests), but a mode must be specified.
2552 */
2553TEST_P(SigningOperationsTest, RsaNoPadding) {
2554 // Padding must be specified
2555 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2556 .RsaKey(2048, 65537)
2557 .Authorization(TAG_NO_AUTH_REQUIRED)
2558 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002559 .Digest(Digest::NONE)
2560 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002561 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2562 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2563}
2564
2565/*
2566 * SigningOperationsTest.RsaShortMessage
2567 *
2568 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2569 */
2570TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2571 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2572 .Authorization(TAG_NO_AUTH_REQUIRED)
2573 .RsaSigningKey(2048, 65537)
2574 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002575 .Padding(PaddingMode::NONE)
2576 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002577
2578 // Barely shorter
2579 string message(2048 / 8 - 1, 'a');
2580 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2581
2582 // Much shorter
2583 message = "a";
2584 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2585}
2586
2587/*
2588 * SigningOperationsTest.RsaSignWithEncryptionKey
2589 *
2590 * Verifies that RSA encryption keys cannot be used to sign.
2591 */
2592TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2593 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2594 .Authorization(TAG_NO_AUTH_REQUIRED)
2595 .RsaEncryptionKey(2048, 65537)
2596 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002597 .Padding(PaddingMode::NONE)
2598 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002599 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2600 Begin(KeyPurpose::SIGN,
2601 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2602}
2603
2604/*
2605 * SigningOperationsTest.RsaSignTooLargeMessage
2606 *
2607 * Verifies that attempting a raw signature of a message which is the same length as the key,
2608 * but numerically larger than the public modulus, fails with the correct error.
2609 */
2610TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2611 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2612 .Authorization(TAG_NO_AUTH_REQUIRED)
2613 .RsaSigningKey(2048, 65537)
2614 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002615 .Padding(PaddingMode::NONE)
2616 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002617
2618 // Largest possible message will always be larger than the public modulus.
2619 string message(2048 / 8, static_cast<char>(0xff));
2620 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2621 .Authorization(TAG_NO_AUTH_REQUIRED)
2622 .Digest(Digest::NONE)
2623 .Padding(PaddingMode::NONE)));
2624 string signature;
2625 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2626}
2627
2628/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01002629 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2630 *
2631 * Verifies ECDSA signature/verification for all digests and curves.
2632 */
2633TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2634 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2635
2636 string message = "1234567890";
2637 string corrupt_message = "2234567890";
2638 for (auto curve : ValidCurves()) {
2639 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2640 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2641 .Authorization(TAG_NO_AUTH_REQUIRED)
2642 .EcdsaSigningKey(curve)
2643 .Digest(digests)
2644 .SetDefaultValidity());
2645 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2646 if (error != ErrorCode::OK) {
2647 continue;
2648 }
2649
2650 for (auto digest : digests) {
2651 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2652 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2653 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2654 }
2655
2656 auto rc = DeleteKey();
2657 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2658 }
2659}
2660
2661/*
Selene Huang31ab4042020-04-29 04:22:39 -07002662 * SigningOperationsTest.EcdsaAllCurves
2663 *
2664 * Verifies that ECDSA operations succeed with all possible curves.
2665 */
2666TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2667 for (auto curve : ValidCurves()) {
2668 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2669 .Authorization(TAG_NO_AUTH_REQUIRED)
2670 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002671 .Digest(Digest::SHA_2_256)
2672 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002673 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2674 if (error != ErrorCode::OK) continue;
2675
2676 string message(1024, 'a');
2677 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2678 CheckedDeleteKey();
2679 }
2680}
2681
2682/*
2683 * SigningOperationsTest.EcdsaNoDigestHugeData
2684 *
2685 * Verifies that ECDSA operations support very large messages, even without digesting. This
2686 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2687 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2688 * the framework.
2689 */
2690TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2691 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2692 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002693 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002694 .Digest(Digest::NONE)
2695 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002696 string message(1 * 1024, 'a');
2697 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2698}
2699
2700/*
2701 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2702 *
2703 * Verifies that using an EC key requires the correct app ID/data.
2704 */
2705TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2706 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2707 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002708 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002709 .Digest(Digest::NONE)
2710 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002711 .Authorization(TAG_APPLICATION_DATA, "appdata")
2712 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002713
2714 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2715
Selene Huang31ab4042020-04-29 04:22:39 -07002716 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2717 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2718 AbortIfNeeded();
2719 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2720 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2721 .Digest(Digest::NONE)
2722 .Authorization(TAG_APPLICATION_ID, "clientid")));
2723 AbortIfNeeded();
2724 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2725 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2726 .Digest(Digest::NONE)
2727 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2728 AbortIfNeeded();
2729 EXPECT_EQ(ErrorCode::OK,
2730 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2731 .Digest(Digest::NONE)
2732 .Authorization(TAG_APPLICATION_DATA, "appdata")
2733 .Authorization(TAG_APPLICATION_ID, "clientid")));
2734 AbortIfNeeded();
2735}
2736
2737/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002738 * SigningOperationsTest.EcdsaIncompatibleDigest
2739 *
2740 * Verifies that using an EC key requires compatible digest.
2741 */
2742TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2743 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2744 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002745 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002746 .Digest(Digest::NONE)
2747 .Digest(Digest::SHA1)
2748 .SetDefaultValidity()));
2749 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2750 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2751 AbortIfNeeded();
2752}
2753
2754/*
Selene Huang31ab4042020-04-29 04:22:39 -07002755 * SigningOperationsTest.AesEcbSign
2756 *
2757 * Verifies that attempts to use AES keys to sign fail in the correct way.
2758 */
2759TEST_P(SigningOperationsTest, AesEcbSign) {
2760 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2761 .Authorization(TAG_NO_AUTH_REQUIRED)
2762 .SigningKey()
2763 .AesEncryptionKey(128)
2764 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2765
2766 AuthorizationSet out_params;
2767 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2768 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2769 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2770 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2771}
2772
2773/*
2774 * SigningOperationsTest.HmacAllDigests
2775 *
2776 * Verifies that HMAC works with all digests.
2777 */
2778TEST_P(SigningOperationsTest, HmacAllDigests) {
2779 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2780 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2781 .Authorization(TAG_NO_AUTH_REQUIRED)
2782 .HmacKey(128)
2783 .Digest(digest)
2784 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2785 << "Failed to create HMAC key with digest " << digest;
2786 string message = "12345678901234567890123456789012";
2787 string signature = MacMessage(message, digest, 160);
2788 EXPECT_EQ(160U / 8U, signature.size())
2789 << "Failed to sign with HMAC key with digest " << digest;
2790 CheckedDeleteKey();
2791 }
2792}
2793
2794/*
2795 * SigningOperationsTest.HmacSha256TooLargeMacLength
2796 *
2797 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2798 * digest size.
2799 */
2800TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2801 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2802 .Authorization(TAG_NO_AUTH_REQUIRED)
2803 .HmacKey(128)
2804 .Digest(Digest::SHA_2_256)
2805 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2806 AuthorizationSet output_params;
2807 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2808 AuthorizationSetBuilder()
2809 .Digest(Digest::SHA_2_256)
2810 .Authorization(TAG_MAC_LENGTH, 264),
2811 &output_params));
2812}
2813
2814/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002815 * SigningOperationsTest.HmacSha256InvalidMacLength
2816 *
2817 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2818 * not a multiple of 8.
2819 */
2820TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2821 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2822 .Authorization(TAG_NO_AUTH_REQUIRED)
2823 .HmacKey(128)
2824 .Digest(Digest::SHA_2_256)
2825 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2826 AuthorizationSet output_params;
2827 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2828 AuthorizationSetBuilder()
2829 .Digest(Digest::SHA_2_256)
2830 .Authorization(TAG_MAC_LENGTH, 161),
2831 &output_params));
2832}
2833
2834/*
Selene Huang31ab4042020-04-29 04:22:39 -07002835 * SigningOperationsTest.HmacSha256TooSmallMacLength
2836 *
2837 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2838 * specified minimum MAC length.
2839 */
2840TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2841 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2842 .Authorization(TAG_NO_AUTH_REQUIRED)
2843 .HmacKey(128)
2844 .Digest(Digest::SHA_2_256)
2845 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2846 AuthorizationSet output_params;
2847 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2848 AuthorizationSetBuilder()
2849 .Digest(Digest::SHA_2_256)
2850 .Authorization(TAG_MAC_LENGTH, 120),
2851 &output_params));
2852}
2853
2854/*
2855 * SigningOperationsTest.HmacRfc4231TestCase3
2856 *
2857 * Validates against the test vectors from RFC 4231 test case 3.
2858 */
2859TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2860 string key(20, 0xaa);
2861 string message(50, 0xdd);
2862 uint8_t sha_224_expected[] = {
2863 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2864 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2865 };
2866 uint8_t sha_256_expected[] = {
2867 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2868 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2869 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2870 };
2871 uint8_t sha_384_expected[] = {
2872 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2873 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2874 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2875 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2876 };
2877 uint8_t sha_512_expected[] = {
2878 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2879 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2880 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2881 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2882 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2883 };
2884
2885 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2886 if (SecLevel() != SecurityLevel::STRONGBOX) {
2887 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2888 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2889 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2890 }
2891}
2892
2893/*
2894 * SigningOperationsTest.HmacRfc4231TestCase5
2895 *
2896 * Validates against the test vectors from RFC 4231 test case 5.
2897 */
2898TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2899 string key(20, 0x0c);
2900 string message = "Test With Truncation";
2901
2902 uint8_t sha_224_expected[] = {
2903 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2904 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2905 };
2906 uint8_t sha_256_expected[] = {
2907 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2908 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2909 };
2910 uint8_t sha_384_expected[] = {
2911 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2912 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2913 };
2914 uint8_t sha_512_expected[] = {
2915 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2916 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2917 };
2918
2919 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2920 if (SecLevel() != SecurityLevel::STRONGBOX) {
2921 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2922 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2923 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2924 }
2925}
2926
2927INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2928
2929typedef KeyMintAidlTestBase VerificationOperationsTest;
2930
2931/*
Selene Huang31ab4042020-04-29 04:22:39 -07002932 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2933 *
2934 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2935 */
2936TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2937 string key_material = "HelloThisIsAKey";
2938
2939 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002940 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002941 EXPECT_EQ(ErrorCode::OK,
2942 ImportKey(AuthorizationSetBuilder()
2943 .Authorization(TAG_NO_AUTH_REQUIRED)
2944 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2945 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2946 .Digest(Digest::SHA_2_256)
2947 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2948 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2949 EXPECT_EQ(ErrorCode::OK,
2950 ImportKey(AuthorizationSetBuilder()
2951 .Authorization(TAG_NO_AUTH_REQUIRED)
2952 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2953 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2954 .Digest(Digest::SHA_2_256)
2955 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2956 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2957
2958 string message = "This is a message.";
2959 string signature = SignMessage(
2960 signing_key, message,
2961 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2962
2963 // Signing key should not work.
2964 AuthorizationSet out_params;
2965 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2966 Begin(KeyPurpose::VERIFY, signing_key,
2967 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2968
2969 // Verification key should work.
2970 VerifyMessage(verification_key, message, signature,
2971 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2972
2973 CheckedDeleteKey(&signing_key);
2974 CheckedDeleteKey(&verification_key);
2975}
2976
2977INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2978
2979typedef KeyMintAidlTestBase ExportKeyTest;
2980
2981/*
2982 * ExportKeyTest.RsaUnsupportedKeyFormat
2983 *
2984 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2985 */
2986// TODO(seleneh) add ExportKey to GenerateKey
2987// check result
2988
2989class ImportKeyTest : public KeyMintAidlTestBase {
2990 public:
2991 template <TagType tag_type, Tag tag, typename ValueT>
2992 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2993 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002994 for (auto& entry : key_characteristics_) {
2995 if (entry.securityLevel == SecLevel()) {
2996 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2997 << "Tag " << tag << " with value " << expected
2998 << " not found at security level" << entry.securityLevel;
2999 } else {
3000 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3001 << "Tag " << tag << " found at security level " << entry.securityLevel;
3002 }
Selene Huang31ab4042020-04-29 04:22:39 -07003003 }
3004 }
3005
3006 void CheckOrigin() {
3007 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003008 // Origin isn't a crypto param, but it always lives with them.
3009 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003010 }
3011};
3012
3013/*
3014 * ImportKeyTest.RsaSuccess
3015 *
3016 * Verifies that importing and using an RSA key pair works correctly.
3017 */
3018TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003019 uint32_t key_size;
3020 string key;
3021
3022 if (SecLevel() == SecurityLevel::STRONGBOX) {
3023 key_size = 2048;
3024 key = rsa_2048_key;
3025 } else {
3026 key_size = 1024;
3027 key = rsa_key;
3028 }
3029
Selene Huang31ab4042020-04-29 04:22:39 -07003030 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3031 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003032 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003033 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003034 .Padding(PaddingMode::RSA_PSS)
3035 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003036 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003037
3038 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003039 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003040 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3041 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3042 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3043 CheckOrigin();
3044
3045 string message(1024 / 8, 'a');
3046 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3047 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003048 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003049}
3050
3051/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003052 * ImportKeyTest.RsaSuccessWithoutParams
3053 *
3054 * Verifies that importing and using an RSA key pair without specifying parameters
3055 * works correctly.
3056 */
3057TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3058 uint32_t key_size;
3059 string key;
3060
3061 if (SecLevel() == SecurityLevel::STRONGBOX) {
3062 key_size = 2048;
3063 key = rsa_2048_key;
3064 } else {
3065 key_size = 1024;
3066 key = rsa_key;
3067 }
3068
3069 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3070 .Authorization(TAG_NO_AUTH_REQUIRED)
3071 .SigningKey()
3072 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3073 .Digest(Digest::SHA_2_256)
3074 .Padding(PaddingMode::RSA_PSS)
3075 .SetDefaultValidity(),
3076 KeyFormat::PKCS8, key));
3077
3078 // Key size and public exponent are determined from the imported key material.
3079 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3080 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3081
3082 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3083 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3084 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3085 CheckOrigin();
3086
3087 string message(1024 / 8, 'a');
3088 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3089 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003090 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003091}
3092
3093/*
Selene Huang31ab4042020-04-29 04:22:39 -07003094 * ImportKeyTest.RsaKeySizeMismatch
3095 *
3096 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3097 * correct way.
3098 */
3099TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3100 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3101 ImportKey(AuthorizationSetBuilder()
3102 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3103 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003104 .Padding(PaddingMode::NONE)
3105 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003106 KeyFormat::PKCS8, rsa_key));
3107}
3108
3109/*
3110 * ImportKeyTest.RsaPublicExponentMismatch
3111 *
3112 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3113 * fails in the correct way.
3114 */
3115TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3116 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3117 ImportKey(AuthorizationSetBuilder()
3118 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3119 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003120 .Padding(PaddingMode::NONE)
3121 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003122 KeyFormat::PKCS8, rsa_key));
3123}
3124
3125/*
3126 * ImportKeyTest.EcdsaSuccess
3127 *
3128 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3129 */
3130TEST_P(ImportKeyTest, EcdsaSuccess) {
3131 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3132 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003133 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003134 .Digest(Digest::SHA_2_256)
3135 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003136 KeyFormat::PKCS8, ec_256_key));
3137
3138 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003139 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3140 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3141
3142 CheckOrigin();
3143
3144 string message(32, 'a');
3145 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3146 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003147 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003148}
3149
3150/*
3151 * ImportKeyTest.EcdsaP256RFC5915Success
3152 *
3153 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3154 * correctly.
3155 */
3156TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3157 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3158 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003159 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003160 .Digest(Digest::SHA_2_256)
3161 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003162 KeyFormat::PKCS8, ec_256_key_rfc5915));
3163
3164 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003165 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3166 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3167
3168 CheckOrigin();
3169
3170 string message(32, 'a');
3171 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3172 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003173 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003174}
3175
3176/*
3177 * ImportKeyTest.EcdsaP256SEC1Success
3178 *
3179 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3180 */
3181TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3182 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3183 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003184 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003185 .Digest(Digest::SHA_2_256)
3186 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003187 KeyFormat::PKCS8, ec_256_key_sec1));
3188
3189 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003190 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3191 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3192
3193 CheckOrigin();
3194
3195 string message(32, 'a');
3196 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3197 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003198 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003199}
3200
3201/*
3202 * ImportKeyTest.Ecdsa521Success
3203 *
3204 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3205 */
3206TEST_P(ImportKeyTest, Ecdsa521Success) {
3207 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3208 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3209 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003210 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003211 .Digest(Digest::SHA_2_256)
3212 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003213 KeyFormat::PKCS8, ec_521_key));
3214
3215 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003216 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3217 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3218 CheckOrigin();
3219
3220 string message(32, 'a');
3221 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3222 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003223 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003224}
3225
3226/*
Selene Huang31ab4042020-04-29 04:22:39 -07003227 * ImportKeyTest.EcdsaCurveMismatch
3228 *
3229 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3230 * the correct way.
3231 */
3232TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3233 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3234 ImportKey(AuthorizationSetBuilder()
3235 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003236 .Digest(Digest::NONE)
3237 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003238 KeyFormat::PKCS8, ec_256_key));
3239}
3240
3241/*
3242 * ImportKeyTest.AesSuccess
3243 *
3244 * Verifies that importing and using an AES key works.
3245 */
3246TEST_P(ImportKeyTest, AesSuccess) {
3247 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3248 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3249 .Authorization(TAG_NO_AUTH_REQUIRED)
3250 .AesEncryptionKey(key.size() * 8)
3251 .EcbMode()
3252 .Padding(PaddingMode::PKCS7),
3253 KeyFormat::RAW, key));
3254
3255 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3256 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3257 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3258 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3259 CheckOrigin();
3260
3261 string message = "Hello World!";
3262 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3263 string ciphertext = EncryptMessage(message, params);
3264 string plaintext = DecryptMessage(ciphertext, params);
3265 EXPECT_EQ(message, plaintext);
3266}
3267
3268/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003269 * ImportKeyTest.AesFailure
3270 *
3271 * Verifies that importing an invalid AES key fails.
3272 */
3273TEST_P(ImportKeyTest, AesFailure) {
3274 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3275 uint32_t bitlen = key.size() * 8;
3276 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003277 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003278 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003279 .Authorization(TAG_NO_AUTH_REQUIRED)
3280 .AesEncryptionKey(key_size)
3281 .EcbMode()
3282 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003283 KeyFormat::RAW, key);
3284 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003285 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3286 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003287 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003288
3289 // Explicit key size matches that of the provided key, but it's not a valid size.
3290 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3291 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3292 ImportKey(AuthorizationSetBuilder()
3293 .Authorization(TAG_NO_AUTH_REQUIRED)
3294 .AesEncryptionKey(long_key.size() * 8)
3295 .EcbMode()
3296 .Padding(PaddingMode::PKCS7),
3297 KeyFormat::RAW, long_key));
3298 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3299 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3300 ImportKey(AuthorizationSetBuilder()
3301 .Authorization(TAG_NO_AUTH_REQUIRED)
3302 .AesEncryptionKey(short_key.size() * 8)
3303 .EcbMode()
3304 .Padding(PaddingMode::PKCS7),
3305 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003306}
3307
3308/*
3309 * ImportKeyTest.TripleDesSuccess
3310 *
3311 * Verifies that importing and using a 3DES key works.
3312 */
3313TEST_P(ImportKeyTest, TripleDesSuccess) {
3314 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3315 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3316 .Authorization(TAG_NO_AUTH_REQUIRED)
3317 .TripleDesEncryptionKey(168)
3318 .EcbMode()
3319 .Padding(PaddingMode::PKCS7),
3320 KeyFormat::RAW, key));
3321
3322 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3323 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3324 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3325 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3326 CheckOrigin();
3327
3328 string message = "Hello World!";
3329 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3330 string ciphertext = EncryptMessage(message, params);
3331 string plaintext = DecryptMessage(ciphertext, params);
3332 EXPECT_EQ(message, plaintext);
3333}
3334
3335/*
3336 * ImportKeyTest.TripleDesFailure
3337 *
3338 * Verifies that importing an invalid 3DES key fails.
3339 */
3340TEST_P(ImportKeyTest, TripleDesFailure) {
3341 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003342 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003343 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003344 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003345 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003346 .Authorization(TAG_NO_AUTH_REQUIRED)
3347 .TripleDesEncryptionKey(key_size)
3348 .EcbMode()
3349 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003350 KeyFormat::RAW, key);
3351 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003352 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3353 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003354 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003355 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003356 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003357 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3358 ImportKey(AuthorizationSetBuilder()
3359 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003360 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003361 .EcbMode()
3362 .Padding(PaddingMode::PKCS7),
3363 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003364 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003365 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3366 ImportKey(AuthorizationSetBuilder()
3367 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003368 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003369 .EcbMode()
3370 .Padding(PaddingMode::PKCS7),
3371 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003372}
3373
3374/*
3375 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003376 *
3377 * Verifies that importing and using an HMAC key works.
3378 */
3379TEST_P(ImportKeyTest, HmacKeySuccess) {
3380 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3381 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3382 .Authorization(TAG_NO_AUTH_REQUIRED)
3383 .HmacKey(key.size() * 8)
3384 .Digest(Digest::SHA_2_256)
3385 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3386 KeyFormat::RAW, key));
3387
3388 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3389 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3390 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3391 CheckOrigin();
3392
3393 string message = "Hello World!";
3394 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3395 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3396}
3397
3398INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3399
3400auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003401 // IKeyMintDevice.aidl
3402 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3403 "020100" // INTEGER length 1 value 0x00 (version)
3404 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3405 "934bf94e2aa28a3f83c9f79297250262"
3406 "fbe3276b5a1c91159bbfa3ef8957aac8"
3407 "4b59b30b455a79c2973480823d8b3863"
3408 "c3deef4a8e243590268d80e18751a0e1"
3409 "30f67ce6a1ace9f79b95e097474febc9"
3410 "81195b1d13a69086c0863f66a7b7fdb4"
3411 "8792227b1ac5e2489febdf087ab54864"
3412 "83033a6f001ca5d1ec1e27f5c30f4cec"
3413 "2642074a39ae68aee552e196627a8e3d"
3414 "867e67a8c01b11e75f13cca0a97ab668"
3415 "b50cda07a8ecb7cd8e3dd7009c963653"
3416 "4f6f239cffe1fc8daa466f78b676c711"
3417 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3418 "99b801597d5220e307eaa5bee507fb94"
3419 "d1fa69f9e519b2de315bac92c36f2ea1"
3420 "fa1df4478c0ddedeae8c70e0233cd098"
3421 "040c" // OCTET STRING length 0x0c (initializationVector)
3422 "d796b02c370f1fa4cc0124f1"
3423 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3424 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3425 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3426 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3427 "3106" // SET length 0x06
3428 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3429 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3430 // } end SET
3431 // } end [1]
3432 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3433 "020120" // INTEGER length 1 value 0x20 (AES)
3434 // } end [2]
3435 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3436 "02020100" // INTEGER length 2 value 0x100
3437 // } end [3]
3438 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3439 "3103" // SET length 0x03 {
3440 "020101" // INTEGER length 1 value 0x01 (ECB)
3441 // } end SET
3442 // } end [4]
3443 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3444 "3103" // SET length 0x03 {
3445 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3446 // } end SET
3447 // } end [5]
3448 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3449 // (noAuthRequired)
3450 "0500" // NULL
3451 // } end [503]
3452 // } end SEQUENCE (AuthorizationList)
3453 // } end SEQUENCE (KeyDescription)
3454 "0420" // OCTET STRING length 0x20 (encryptedKey)
3455 "ccd540855f833a5e1480bfd2d36faf3a"
3456 "eee15df5beabe2691bc82dde2a7aa910"
3457 "0410" // OCTET STRING length 0x10 (tag)
3458 "64c9f689c60ff6223ab6e6999e0eb6e5"
3459 // } SEQUENCE (SecureKeyWrapper)
3460);
Selene Huang31ab4042020-04-29 04:22:39 -07003461
3462auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003463 // IKeyMintDevice.aidl
3464 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3465 "020100" // INTEGER length 1 value 0x00 (version)
3466 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3467 "aad93ed5924f283b4bb5526fbe7a1412"
3468 "f9d9749ec30db9062b29e574a8546f33"
3469 "c88732452f5b8e6a391ee76c39ed1712"
3470 "c61d8df6213dec1cffbc17a8c6d04c7b"
3471 "30893d8daa9b2015213e219468215532"
3472 "07f8f9931c4caba23ed3bee28b36947e"
3473 "47f10e0a5c3dc51c988a628daad3e5e1"
3474 "f4005e79c2d5a96c284b4b8d7e4948f3"
3475 "31e5b85dd5a236f85579f3ea1d1b8484"
3476 "87470bdb0ab4f81a12bee42c99fe0df4"
3477 "bee3759453e69ad1d68a809ce06b949f"
3478 "7694a990429b2fe81e066ff43e56a216"
3479 "02db70757922a4bcc23ab89f1e35da77"
3480 "586775f423e519c2ea394caf48a28d0c"
3481 "8020f1dcf6b3a68ec246f615ae96dae9"
3482 "a079b1f6eb959033c1af5c125fd94168"
3483 "040c" // OCTET STRING length 0x0c (initializationVector)
3484 "6d9721d08589581ab49204a3"
3485 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3486 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3487 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3488 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3489 "3106" // SET length 0x06
3490 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3491 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3492 // } end SET
3493 // } end [1]
3494 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3495 "020120" // INTEGER length 1 value 0x20 (AES)
3496 // } end [2]
3497 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3498 "02020100" // INTEGER length 2 value 0x100
3499 // } end [3]
3500 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3501 "3103" // SET length 0x03 {
3502 "020101" // INTEGER length 1 value 0x01 (ECB)
3503 // } end SET
3504 // } end [4]
3505 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3506 "3103" // SET length 0x03 {
3507 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3508 // } end SET
3509 // } end [5]
3510 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3511 // (noAuthRequired)
3512 "0500" // NULL
3513 // } end [503]
3514 // } end SEQUENCE (AuthorizationList)
3515 // } end SEQUENCE (KeyDescription)
3516 "0420" // OCTET STRING length 0x20 (encryptedKey)
3517 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3518 "c20d1f99a9a024a76f35c8e2cab9b68d"
3519 "0410" // OCTET STRING length 0x10 (tag)
3520 "2560c70109ae67c030f00b98b512a670"
3521 // } SEQUENCE (SecureKeyWrapper)
3522);
Selene Huang31ab4042020-04-29 04:22:39 -07003523
3524auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003525 // RFC 5208 s5
3526 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3527 "020100" // INTEGER length 1 value 0x00 (version)
3528 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3529 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3530 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3531 "0500" // NULL (parameters)
3532 // } SEQUENCE (AlgorithmIdentifier)
3533 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3534 // RFC 8017 A.1.2
3535 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3536 "020100" // INTEGER length 1 value 0x00 (version)
3537 "02820101" // INTEGER length 0x0101 (modulus) value...
3538 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3539 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3540 "7b06e673a837313d56b1c725150a3fef" // 0x30
3541 "86acbddc41bb759c2854eae32d35841e" // 0x40
3542 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3543 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3544 "312d7bd5921ffaea1347c157406fef71" // 0x70
3545 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3546 "f4645c11f5c1374c3886427411c44979" // 0x90
3547 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3548 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3549 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3550 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3551 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3552 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3553 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3554 "55" // 0x101
3555 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3556 "02820100" // INTEGER length 0x100 (privateExponent) value...
3557 "431447b6251908112b1ee76f99f3711a" // 0x10
3558 "52b6630960046c2de70de188d833f8b8" // 0x20
3559 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3560 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3561 "e710b630a03adc683b5d2c43080e52be" // 0x50
3562 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3563 "822bccff087d63c940ba8a45f670feb2" // 0x70
3564 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3565 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3566 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3567 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3568 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3569 "52659d5a5ba05b663737a8696281865b" // 0xd0
3570 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3571 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3572 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3573 "028181" // INTEGER length 0x81 (prime1) value...
3574 "00de392e18d682c829266cc3454e1d61" // 0x10
3575 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3576 "ff841be5bac82a164c5970007047b8c5" // 0x30
3577 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3578 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3579 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3580 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3581 "9e91346130748a6e3c124f9149d71c74" // 0x80
3582 "35"
3583 "028181" // INTEGER length 0x81 (prime2) value...
3584 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3585 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3586 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3587 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3588 "9ed39a2d934c880440aed8832f984316" // 0x50
3589 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3590 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3591 "b880677c068e1be936e81288815252a8" // 0x80
3592 "a1"
3593 "028180" // INTEGER length 0x80 (exponent1) value...
3594 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3595 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3596 "5a063212a4f105a3764743e53281988a" // 0x30
3597 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3598 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3599 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3600 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3601 "4719d6e2b9439823719cd08bcd031781" // 0x80
3602 "028181" // INTEGER length 0x81 (exponent2) value...
3603 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3604 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3605 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3606 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3607 "1254186af30b22c10582a8a43e34fe94" // 0x50
3608 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3609 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3610 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3611 "61"
3612 "028181" // INTEGER length 0x81 (coefficient) value...
3613 "00c931617c77829dfb1270502be9195c" // 0x10
3614 "8f2830885f57dba869536811e6864236" // 0x20
3615 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3616 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3617 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3618 "959356210723287b0affcc9f727044d4" // 0x60
3619 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3620 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3621 "22"
3622 // } SEQUENCE
3623 // } SEQUENCE ()
3624);
Selene Huang31ab4042020-04-29 04:22:39 -07003625
3626string zero_masking_key =
3627 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3628string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3629
3630class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3631
3632TEST_P(ImportWrappedKeyTest, Success) {
3633 auto wrapping_key_desc = AuthorizationSetBuilder()
3634 .RsaEncryptionKey(2048, 65537)
3635 .Digest(Digest::SHA_2_256)
3636 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003637 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3638 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003639
3640 ASSERT_EQ(ErrorCode::OK,
3641 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3642 AuthorizationSetBuilder()
3643 .Digest(Digest::SHA_2_256)
3644 .Padding(PaddingMode::RSA_OAEP)));
3645
3646 string message = "Hello World!";
3647 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3648 string ciphertext = EncryptMessage(message, params);
3649 string plaintext = DecryptMessage(ciphertext, params);
3650 EXPECT_EQ(message, plaintext);
3651}
3652
David Drysdaled2cc8c22021-04-15 13:29:45 +01003653/*
3654 * ImportWrappedKeyTest.SuccessSidsIgnored
3655 *
3656 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3657 * include Tag:USER_SECURE_ID.
3658 */
3659TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3660 auto wrapping_key_desc = AuthorizationSetBuilder()
3661 .RsaEncryptionKey(2048, 65537)
3662 .Digest(Digest::SHA_2_256)
3663 .Padding(PaddingMode::RSA_OAEP)
3664 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3665 .SetDefaultValidity();
3666
3667 int64_t password_sid = 42;
3668 int64_t biometric_sid = 24;
3669 ASSERT_EQ(ErrorCode::OK,
3670 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3671 AuthorizationSetBuilder()
3672 .Digest(Digest::SHA_2_256)
3673 .Padding(PaddingMode::RSA_OAEP),
3674 password_sid, biometric_sid));
3675
3676 string message = "Hello World!";
3677 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3678 string ciphertext = EncryptMessage(message, params);
3679 string plaintext = DecryptMessage(ciphertext, params);
3680 EXPECT_EQ(message, plaintext);
3681}
3682
Selene Huang31ab4042020-04-29 04:22:39 -07003683TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3684 auto wrapping_key_desc = AuthorizationSetBuilder()
3685 .RsaEncryptionKey(2048, 65537)
3686 .Digest(Digest::SHA_2_256)
3687 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003688 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3689 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003690
3691 ASSERT_EQ(ErrorCode::OK,
3692 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3693 AuthorizationSetBuilder()
3694 .Digest(Digest::SHA_2_256)
3695 .Padding(PaddingMode::RSA_OAEP)));
3696}
3697
3698TEST_P(ImportWrappedKeyTest, WrongMask) {
3699 auto wrapping_key_desc = AuthorizationSetBuilder()
3700 .RsaEncryptionKey(2048, 65537)
3701 .Digest(Digest::SHA_2_256)
3702 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003703 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3704 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003705
3706 ASSERT_EQ(
3707 ErrorCode::VERIFICATION_FAILED,
3708 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3709 AuthorizationSetBuilder()
3710 .Digest(Digest::SHA_2_256)
3711 .Padding(PaddingMode::RSA_OAEP)));
3712}
3713
3714TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3715 auto wrapping_key_desc = AuthorizationSetBuilder()
3716 .RsaEncryptionKey(2048, 65537)
3717 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003718 .Padding(PaddingMode::RSA_OAEP)
3719 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003720
3721 ASSERT_EQ(
3722 ErrorCode::INCOMPATIBLE_PURPOSE,
3723 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3724 AuthorizationSetBuilder()
3725 .Digest(Digest::SHA_2_256)
3726 .Padding(PaddingMode::RSA_OAEP)));
3727}
3728
David Drysdaled2cc8c22021-04-15 13:29:45 +01003729TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3730 auto wrapping_key_desc = AuthorizationSetBuilder()
3731 .RsaEncryptionKey(2048, 65537)
3732 .Digest(Digest::SHA_2_256)
3733 .Padding(PaddingMode::RSA_PSS)
3734 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3735 .SetDefaultValidity();
3736
3737 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3738 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3739 AuthorizationSetBuilder()
3740 .Digest(Digest::SHA_2_256)
3741 .Padding(PaddingMode::RSA_OAEP)));
3742}
3743
3744TEST_P(ImportWrappedKeyTest, WrongDigest) {
3745 auto wrapping_key_desc = AuthorizationSetBuilder()
3746 .RsaEncryptionKey(2048, 65537)
3747 .Digest(Digest::SHA_2_512)
3748 .Padding(PaddingMode::RSA_OAEP)
3749 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3750 .SetDefaultValidity();
3751
3752 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3753 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3754 AuthorizationSetBuilder()
3755 .Digest(Digest::SHA_2_256)
3756 .Padding(PaddingMode::RSA_OAEP)));
3757}
3758
Selene Huang31ab4042020-04-29 04:22:39 -07003759INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3760
3761typedef KeyMintAidlTestBase EncryptionOperationsTest;
3762
3763/*
3764 * EncryptionOperationsTest.RsaNoPaddingSuccess
3765 *
David Drysdale59cae642021-05-12 13:52:03 +01003766 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003767 */
3768TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003769 for (uint64_t exponent : {3, 65537}) {
3770 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3771 .Authorization(TAG_NO_AUTH_REQUIRED)
3772 .RsaEncryptionKey(2048, exponent)
3773 .Padding(PaddingMode::NONE)
3774 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003775
David Drysdaled2cc8c22021-04-15 13:29:45 +01003776 string message = string(2048 / 8, 'a');
3777 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003778 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003779 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003780
David Drysdale59cae642021-05-12 13:52:03 +01003781 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003782 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003783
David Drysdaled2cc8c22021-04-15 13:29:45 +01003784 // Unpadded RSA is deterministic
3785 EXPECT_EQ(ciphertext1, ciphertext2);
3786
3787 CheckedDeleteKey();
3788 }
Selene Huang31ab4042020-04-29 04:22:39 -07003789}
3790
3791/*
3792 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3793 *
David Drysdale59cae642021-05-12 13:52:03 +01003794 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003795 */
3796TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3797 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3798 .Authorization(TAG_NO_AUTH_REQUIRED)
3799 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003800 .Padding(PaddingMode::NONE)
3801 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003802
3803 string message = "1";
3804 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3805
David Drysdale59cae642021-05-12 13:52:03 +01003806 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003807 EXPECT_EQ(2048U / 8, ciphertext.size());
3808
3809 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3810 string plaintext = DecryptMessage(ciphertext, params);
3811
3812 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07003813}
3814
3815/*
Selene Huang31ab4042020-04-29 04:22:39 -07003816 * EncryptionOperationsTest.RsaOaepSuccess
3817 *
David Drysdale59cae642021-05-12 13:52:03 +01003818 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07003819 */
3820TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3821 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3822
3823 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01003824 ASSERT_EQ(ErrorCode::OK,
3825 GenerateKey(AuthorizationSetBuilder()
3826 .Authorization(TAG_NO_AUTH_REQUIRED)
3827 .RsaEncryptionKey(key_size, 65537)
3828 .Padding(PaddingMode::RSA_OAEP)
3829 .Digest(digests)
3830 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
3831 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003832
3833 string message = "Hello";
3834
3835 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01003836 SCOPED_TRACE(testing::Message() << "digest-" << digest);
3837
3838 auto params = AuthorizationSetBuilder()
3839 .Digest(digest)
3840 .Padding(PaddingMode::RSA_OAEP)
3841 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
3842 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003843 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3844 EXPECT_EQ(key_size / 8, ciphertext1.size());
3845
David Drysdale59cae642021-05-12 13:52:03 +01003846 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003847 EXPECT_EQ(key_size / 8, ciphertext2.size());
3848
3849 // OAEP randomizes padding so every result should be different (with astronomically high
3850 // probability).
3851 EXPECT_NE(ciphertext1, ciphertext2);
3852
3853 string plaintext1 = DecryptMessage(ciphertext1, params);
3854 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3855 string plaintext2 = DecryptMessage(ciphertext2, params);
3856 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3857
3858 // Decrypting corrupted ciphertext should fail.
3859 size_t offset_to_corrupt = random() % ciphertext1.size();
3860 char corrupt_byte;
3861 do {
3862 corrupt_byte = static_cast<char>(random() % 256);
3863 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3864 ciphertext1[offset_to_corrupt] = corrupt_byte;
3865
3866 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3867 string result;
3868 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3869 EXPECT_EQ(0U, result.size());
3870 }
3871}
3872
3873/*
3874 * EncryptionOperationsTest.RsaOaepInvalidDigest
3875 *
David Drysdale59cae642021-05-12 13:52:03 +01003876 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07003877 * without a digest.
3878 */
3879TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3880 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3881 .Authorization(TAG_NO_AUTH_REQUIRED)
3882 .RsaEncryptionKey(2048, 65537)
3883 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003884 .Digest(Digest::NONE)
3885 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003886
3887 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003888 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07003889}
3890
3891/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003892 * EncryptionOperationsTest.RsaOaepInvalidPadding
3893 *
David Drysdale59cae642021-05-12 13:52:03 +01003894 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01003895 * with a padding value that is only suitable for signing/verifying.
3896 */
3897TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3898 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3899 .Authorization(TAG_NO_AUTH_REQUIRED)
3900 .RsaEncryptionKey(2048, 65537)
3901 .Padding(PaddingMode::RSA_PSS)
3902 .Digest(Digest::NONE)
3903 .SetDefaultValidity()));
3904
3905 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003906 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003907}
3908
3909/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003910 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003911 *
David Drysdale59cae642021-05-12 13:52:03 +01003912 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07003913 * with a different digest than was used to encrypt.
3914 */
3915TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3916 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3917
3918 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3919 .Authorization(TAG_NO_AUTH_REQUIRED)
3920 .RsaEncryptionKey(1024, 65537)
3921 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003922 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3923 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003924 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01003925 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07003926 message,
3927 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3928
3929 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3930 .Digest(Digest::SHA_2_256)
3931 .Padding(PaddingMode::RSA_OAEP)));
3932 string result;
3933 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3934 EXPECT_EQ(0U, result.size());
3935}
3936
3937/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003938 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3939 *
David Drysdale59cae642021-05-12 13:52:03 +01003940 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003941 * digests.
3942 */
3943TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3944 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3945
3946 size_t key_size = 2048; // Need largish key for SHA-512 test.
3947 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3948 .OaepMGFDigest(digests)
3949 .Authorization(TAG_NO_AUTH_REQUIRED)
3950 .RsaEncryptionKey(key_size, 65537)
3951 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003952 .Digest(Digest::SHA_2_256)
3953 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003954
3955 string message = "Hello";
3956
3957 for (auto digest : digests) {
3958 auto params = AuthorizationSetBuilder()
3959 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
3960 .Digest(Digest::SHA_2_256)
3961 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01003962 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003963 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3964 EXPECT_EQ(key_size / 8, ciphertext1.size());
3965
David Drysdale59cae642021-05-12 13:52:03 +01003966 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003967 EXPECT_EQ(key_size / 8, ciphertext2.size());
3968
3969 // OAEP randomizes padding so every result should be different (with astronomically high
3970 // probability).
3971 EXPECT_NE(ciphertext1, ciphertext2);
3972
3973 string plaintext1 = DecryptMessage(ciphertext1, params);
3974 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3975 string plaintext2 = DecryptMessage(ciphertext2, params);
3976 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3977
3978 // Decrypting corrupted ciphertext should fail.
3979 size_t offset_to_corrupt = random() % ciphertext1.size();
3980 char corrupt_byte;
3981 do {
3982 corrupt_byte = static_cast<char>(random() % 256);
3983 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3984 ciphertext1[offset_to_corrupt] = corrupt_byte;
3985
3986 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3987 string result;
3988 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3989 EXPECT_EQ(0U, result.size());
3990 }
3991}
3992
3993/*
3994 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
3995 *
David Drysdale59cae642021-05-12 13:52:03 +01003996 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003997 * with incompatible MGF digest.
3998 */
3999TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4000 ASSERT_EQ(ErrorCode::OK,
4001 GenerateKey(AuthorizationSetBuilder()
4002 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4003 .Authorization(TAG_NO_AUTH_REQUIRED)
4004 .RsaEncryptionKey(2048, 65537)
4005 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004006 .Digest(Digest::SHA_2_256)
4007 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004008 string message = "Hello World!";
4009
4010 auto params = AuthorizationSetBuilder()
4011 .Padding(PaddingMode::RSA_OAEP)
4012 .Digest(Digest::SHA_2_256)
4013 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004014 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004015}
4016
4017/*
4018 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4019 *
4020 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4021 * with unsupported MGF digest.
4022 */
4023TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4024 ASSERT_EQ(ErrorCode::OK,
4025 GenerateKey(AuthorizationSetBuilder()
4026 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4027 .Authorization(TAG_NO_AUTH_REQUIRED)
4028 .RsaEncryptionKey(2048, 65537)
4029 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004030 .Digest(Digest::SHA_2_256)
4031 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004032 string message = "Hello World!";
4033
4034 auto params = AuthorizationSetBuilder()
4035 .Padding(PaddingMode::RSA_OAEP)
4036 .Digest(Digest::SHA_2_256)
4037 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004038 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004039}
4040
4041/*
Selene Huang31ab4042020-04-29 04:22:39 -07004042 * EncryptionOperationsTest.RsaPkcs1Success
4043 *
4044 * Verifies that RSA PKCS encryption/decrypts works.
4045 */
4046TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4047 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4048 .Authorization(TAG_NO_AUTH_REQUIRED)
4049 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004050 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4051 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004052
4053 string message = "Hello World!";
4054 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01004055 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004056 EXPECT_EQ(2048U / 8, ciphertext1.size());
4057
David Drysdale59cae642021-05-12 13:52:03 +01004058 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004059 EXPECT_EQ(2048U / 8, ciphertext2.size());
4060
4061 // PKCS1 v1.5 randomizes padding so every result should be different.
4062 EXPECT_NE(ciphertext1, ciphertext2);
4063
4064 string plaintext = DecryptMessage(ciphertext1, params);
4065 EXPECT_EQ(message, plaintext);
4066
4067 // Decrypting corrupted ciphertext should fail.
4068 size_t offset_to_corrupt = random() % ciphertext1.size();
4069 char corrupt_byte;
4070 do {
4071 corrupt_byte = static_cast<char>(random() % 256);
4072 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4073 ciphertext1[offset_to_corrupt] = corrupt_byte;
4074
4075 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4076 string result;
4077 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4078 EXPECT_EQ(0U, result.size());
4079}
4080
4081/*
Selene Huang31ab4042020-04-29 04:22:39 -07004082 * EncryptionOperationsTest.EcdsaEncrypt
4083 *
4084 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4085 */
4086TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4087 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4088 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004089 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004090 .Digest(Digest::NONE)
4091 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004092 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4093 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4094 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4095}
4096
4097/*
4098 * EncryptionOperationsTest.HmacEncrypt
4099 *
4100 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4101 */
4102TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4103 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4104 .Authorization(TAG_NO_AUTH_REQUIRED)
4105 .HmacKey(128)
4106 .Digest(Digest::SHA_2_256)
4107 .Padding(PaddingMode::NONE)
4108 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4109 auto params = AuthorizationSetBuilder()
4110 .Digest(Digest::SHA_2_256)
4111 .Padding(PaddingMode::NONE)
4112 .Authorization(TAG_MAC_LENGTH, 128);
4113 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4114 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4115}
4116
4117/*
4118 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4119 *
4120 * Verifies that AES ECB mode works.
4121 */
4122TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4123 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4124 .Authorization(TAG_NO_AUTH_REQUIRED)
4125 .AesEncryptionKey(128)
4126 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4127 .Padding(PaddingMode::NONE)));
4128
4129 ASSERT_GT(key_blob_.size(), 0U);
4130 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4131
4132 // Two-block message.
4133 string message = "12345678901234567890123456789012";
4134 string ciphertext1 = EncryptMessage(message, params);
4135 EXPECT_EQ(message.size(), ciphertext1.size());
4136
4137 string ciphertext2 = EncryptMessage(string(message), params);
4138 EXPECT_EQ(message.size(), ciphertext2.size());
4139
4140 // ECB is deterministic.
4141 EXPECT_EQ(ciphertext1, ciphertext2);
4142
4143 string plaintext = DecryptMessage(ciphertext1, params);
4144 EXPECT_EQ(message, plaintext);
4145}
4146
4147/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004148 * EncryptionOperationsTest.AesEcbUnknownTag
4149 *
4150 * Verifies that AES ECB operations ignore unknown tags.
4151 */
4152TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4153 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4154 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4155 KeyParameter unknown_param;
4156 unknown_param.tag = unknown_tag;
4157
4158 vector<KeyCharacteristics> key_characteristics;
4159 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4160 .Authorization(TAG_NO_AUTH_REQUIRED)
4161 .AesEncryptionKey(128)
4162 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4163 .Padding(PaddingMode::NONE)
4164 .Authorization(unknown_param),
4165 &key_blob_, &key_characteristics));
4166 ASSERT_GT(key_blob_.size(), 0U);
4167
4168 // Unknown tags should not be returned in key characteristics.
4169 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4170 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4171 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4172 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4173
4174 // Encrypt without mentioning the unknown parameter.
4175 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4176 string message = "12345678901234567890123456789012";
4177 string ciphertext = EncryptMessage(message, params);
4178 EXPECT_EQ(message.size(), ciphertext.size());
4179
4180 // Decrypt including the unknown parameter.
4181 auto decrypt_params = AuthorizationSetBuilder()
4182 .BlockMode(BlockMode::ECB)
4183 .Padding(PaddingMode::NONE)
4184 .Authorization(unknown_param);
4185 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4186 EXPECT_EQ(message, plaintext);
4187}
4188
4189/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004190 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004191 *
4192 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4193 */
4194TEST_P(EncryptionOperationsTest, AesWrongMode) {
4195 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4196 .Authorization(TAG_NO_AUTH_REQUIRED)
4197 .AesEncryptionKey(128)
4198 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4199 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004200 ASSERT_GT(key_blob_.size(), 0U);
4201
Selene Huang31ab4042020-04-29 04:22:39 -07004202 EXPECT_EQ(
4203 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4204 Begin(KeyPurpose::ENCRYPT,
4205 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4206}
4207
4208/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004209 * EncryptionOperationsTest.AesWrongPadding
4210 *
4211 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4212 */
4213TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4215 .Authorization(TAG_NO_AUTH_REQUIRED)
4216 .AesEncryptionKey(128)
4217 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4218 .Padding(PaddingMode::NONE)));
4219 ASSERT_GT(key_blob_.size(), 0U);
4220
4221 EXPECT_EQ(
4222 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4223 Begin(KeyPurpose::ENCRYPT,
4224 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4225}
4226
4227/*
4228 * EncryptionOperationsTest.AesInvalidParams
4229 *
4230 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4231 */
4232TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4233 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4234 .Authorization(TAG_NO_AUTH_REQUIRED)
4235 .AesEncryptionKey(128)
4236 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4237 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4238 .Padding(PaddingMode::NONE)
4239 .Padding(PaddingMode::PKCS7)));
4240 ASSERT_GT(key_blob_.size(), 0U);
4241
4242 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4243 .BlockMode(BlockMode::CBC)
4244 .BlockMode(BlockMode::ECB)
4245 .Padding(PaddingMode::NONE));
4246 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4247 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4248
4249 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4250 .BlockMode(BlockMode::ECB)
4251 .Padding(PaddingMode::NONE)
4252 .Padding(PaddingMode::PKCS7));
4253 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4254 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4255}
4256
4257/*
Selene Huang31ab4042020-04-29 04:22:39 -07004258 * EncryptionOperationsTest.AesWrongPurpose
4259 *
4260 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4261 * specified.
4262 */
4263TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4264 auto err = GenerateKey(AuthorizationSetBuilder()
4265 .Authorization(TAG_NO_AUTH_REQUIRED)
4266 .AesKey(128)
4267 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4268 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4269 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4270 .Padding(PaddingMode::NONE));
4271 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4272 ASSERT_GT(key_blob_.size(), 0U);
4273
4274 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4275 .BlockMode(BlockMode::GCM)
4276 .Padding(PaddingMode::NONE)
4277 .Authorization(TAG_MAC_LENGTH, 128));
4278 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4279
4280 CheckedDeleteKey();
4281
4282 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4283 .Authorization(TAG_NO_AUTH_REQUIRED)
4284 .AesKey(128)
4285 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4286 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4287 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4288 .Padding(PaddingMode::NONE)));
4289
4290 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4291 .BlockMode(BlockMode::GCM)
4292 .Padding(PaddingMode::NONE)
4293 .Authorization(TAG_MAC_LENGTH, 128));
4294 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4295}
4296
4297/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004298 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004299 *
4300 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4301 * multiple of the block size and no padding is specified.
4302 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004303TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4304 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4305 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4306 .Authorization(TAG_NO_AUTH_REQUIRED)
4307 .AesEncryptionKey(128)
4308 .Authorization(TAG_BLOCK_MODE, blockMode)
4309 .Padding(PaddingMode::NONE)));
4310 // Message is slightly shorter than two blocks.
4311 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004312
David Drysdaled2cc8c22021-04-15 13:29:45 +01004313 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4314 AuthorizationSet out_params;
4315 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4316 string ciphertext;
4317 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4318 EXPECT_EQ(0U, ciphertext.size());
4319
4320 CheckedDeleteKey();
4321 }
Selene Huang31ab4042020-04-29 04:22:39 -07004322}
4323
4324/*
4325 * EncryptionOperationsTest.AesEcbPkcs7Padding
4326 *
4327 * Verifies that AES PKCS7 padding works for any message length.
4328 */
4329TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4330 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4331 .Authorization(TAG_NO_AUTH_REQUIRED)
4332 .AesEncryptionKey(128)
4333 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4334 .Padding(PaddingMode::PKCS7)));
4335
4336 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4337
4338 // Try various message lengths; all should work.
4339 for (size_t i = 0; i < 32; ++i) {
4340 string message(i, 'a');
4341 string ciphertext = EncryptMessage(message, params);
4342 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4343 string plaintext = DecryptMessage(ciphertext, params);
4344 EXPECT_EQ(message, plaintext);
4345 }
4346}
4347
4348/*
4349 * EncryptionOperationsTest.AesEcbWrongPadding
4350 *
4351 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4352 * specified.
4353 */
4354TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4355 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4356 .Authorization(TAG_NO_AUTH_REQUIRED)
4357 .AesEncryptionKey(128)
4358 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4359 .Padding(PaddingMode::NONE)));
4360
4361 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4362
4363 // Try various message lengths; all should fail
4364 for (size_t i = 0; i < 32; ++i) {
4365 string message(i, 'a');
4366 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4367 }
4368}
4369
4370/*
4371 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4372 *
4373 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4374 */
4375TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4376 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4377 .Authorization(TAG_NO_AUTH_REQUIRED)
4378 .AesEncryptionKey(128)
4379 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4380 .Padding(PaddingMode::PKCS7)));
4381
4382 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4383
4384 string message = "a";
4385 string ciphertext = EncryptMessage(message, params);
4386 EXPECT_EQ(16U, ciphertext.size());
4387 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07004388
Seth Moore7a55ae32021-06-23 14:28:11 -07004389 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
4390 ++ciphertext[ciphertext.size() / 2];
4391
4392 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4393 string plaintext;
4394 ErrorCode error = Finish(message, &plaintext);
4395 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
4396 // This is the expected error, we can exit the test now.
4397 return;
4398 } else {
4399 // Very small chance we got valid decryption, so try again.
4400 ASSERT_EQ(error, ErrorCode::OK);
4401 }
4402 }
4403 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07004404}
4405
4406vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4407 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004408 EXPECT_TRUE(iv);
4409 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004410}
4411
4412/*
4413 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4414 *
4415 * Verifies that AES CTR mode works.
4416 */
4417TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4418 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4419 .Authorization(TAG_NO_AUTH_REQUIRED)
4420 .AesEncryptionKey(128)
4421 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4422 .Padding(PaddingMode::NONE)));
4423
4424 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4425
4426 string message = "123";
4427 AuthorizationSet out_params;
4428 string ciphertext1 = EncryptMessage(message, params, &out_params);
4429 vector<uint8_t> iv1 = CopyIv(out_params);
4430 EXPECT_EQ(16U, iv1.size());
4431
4432 EXPECT_EQ(message.size(), ciphertext1.size());
4433
4434 out_params.Clear();
4435 string ciphertext2 = EncryptMessage(message, params, &out_params);
4436 vector<uint8_t> iv2 = CopyIv(out_params);
4437 EXPECT_EQ(16U, iv2.size());
4438
4439 // IVs should be random, so ciphertexts should differ.
4440 EXPECT_NE(ciphertext1, ciphertext2);
4441
4442 auto params_iv1 =
4443 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4444 auto params_iv2 =
4445 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4446
4447 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4448 EXPECT_EQ(message, plaintext);
4449 plaintext = DecryptMessage(ciphertext2, params_iv2);
4450 EXPECT_EQ(message, plaintext);
4451
4452 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4453 plaintext = DecryptMessage(ciphertext1, params_iv2);
4454 EXPECT_NE(message, plaintext);
4455 plaintext = DecryptMessage(ciphertext2, params_iv1);
4456 EXPECT_NE(message, plaintext);
4457}
4458
4459/*
4460 * EncryptionOperationsTest.AesIncremental
4461 *
4462 * Verifies that AES works, all modes, when provided data in various size increments.
4463 */
4464TEST_P(EncryptionOperationsTest, AesIncremental) {
4465 auto block_modes = {
4466 BlockMode::ECB,
4467 BlockMode::CBC,
4468 BlockMode::CTR,
4469 BlockMode::GCM,
4470 };
4471
4472 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4473 .Authorization(TAG_NO_AUTH_REQUIRED)
4474 .AesEncryptionKey(128)
4475 .BlockMode(block_modes)
4476 .Padding(PaddingMode::NONE)
4477 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4478
4479 for (int increment = 1; increment <= 240; ++increment) {
4480 for (auto block_mode : block_modes) {
4481 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004482 auto params =
4483 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4484 if (block_mode == BlockMode::GCM) {
4485 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4486 }
Selene Huang31ab4042020-04-29 04:22:39 -07004487
4488 AuthorizationSet output_params;
4489 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4490
4491 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004492 string to_send;
4493 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004494 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004495 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004496 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4497 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004498
4499 switch (block_mode) {
4500 case BlockMode::GCM:
4501 EXPECT_EQ(message.size() + 16, ciphertext.size());
4502 break;
4503 case BlockMode::CTR:
4504 EXPECT_EQ(message.size(), ciphertext.size());
4505 break;
4506 case BlockMode::CBC:
4507 case BlockMode::ECB:
4508 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4509 break;
4510 }
4511
4512 auto iv = output_params.GetTagValue(TAG_NONCE);
4513 switch (block_mode) {
4514 case BlockMode::CBC:
4515 case BlockMode::GCM:
4516 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004517 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4518 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4519 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004520 break;
4521
4522 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004523 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004524 break;
4525 }
4526
4527 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4528 << "Decrypt begin() failed for block mode " << block_mode;
4529
4530 string plaintext;
4531 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004532 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004533 }
4534 ErrorCode error = Finish(to_send, &plaintext);
4535 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4536 << " and increment " << increment;
4537 if (error == ErrorCode::OK) {
4538 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4539 << block_mode << " and increment " << increment;
4540 }
4541 }
4542 }
4543}
4544
4545struct AesCtrSp80038aTestVector {
4546 const char* key;
4547 const char* nonce;
4548 const char* plaintext;
4549 const char* ciphertext;
4550};
4551
4552// These test vectors are taken from
4553// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4554static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4555 // AES-128
4556 {
4557 "2b7e151628aed2a6abf7158809cf4f3c",
4558 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4559 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4560 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4561 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4562 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4563 },
4564 // AES-192
4565 {
4566 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4567 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4568 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4569 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4570 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4571 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4572 },
4573 // AES-256
4574 {
4575 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4576 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4577 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4578 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4579 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4580 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4581 },
4582};
4583
4584/*
4585 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4586 *
4587 * Verifies AES CTR implementation against SP800-38A test vectors.
4588 */
4589TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4590 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4591 for (size_t i = 0; i < 3; i++) {
4592 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4593 const string key = hex2str(test.key);
4594 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4595 InvalidSizes.end())
4596 continue;
4597 const string nonce = hex2str(test.nonce);
4598 const string plaintext = hex2str(test.plaintext);
4599 const string ciphertext = hex2str(test.ciphertext);
4600 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4601 }
4602}
4603
4604/*
4605 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4606 *
4607 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4608 */
4609TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4610 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4611 .Authorization(TAG_NO_AUTH_REQUIRED)
4612 .AesEncryptionKey(128)
4613 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4614 .Padding(PaddingMode::PKCS7)));
4615 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4616 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4617}
4618
4619/*
4620 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4621 *
4622 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4623 */
4624TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4625 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4626 .Authorization(TAG_NO_AUTH_REQUIRED)
4627 .AesEncryptionKey(128)
4628 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4629 .Authorization(TAG_CALLER_NONCE)
4630 .Padding(PaddingMode::NONE)));
4631
4632 auto params = AuthorizationSetBuilder()
4633 .BlockMode(BlockMode::CTR)
4634 .Padding(PaddingMode::NONE)
4635 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4636 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4637
4638 params = AuthorizationSetBuilder()
4639 .BlockMode(BlockMode::CTR)
4640 .Padding(PaddingMode::NONE)
4641 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4642 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4643
4644 params = AuthorizationSetBuilder()
4645 .BlockMode(BlockMode::CTR)
4646 .Padding(PaddingMode::NONE)
4647 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4648 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4649}
4650
4651/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004652 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004653 *
4654 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4655 */
4656TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4657 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4658 .Authorization(TAG_NO_AUTH_REQUIRED)
4659 .AesEncryptionKey(128)
4660 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4661 .Padding(PaddingMode::NONE)));
4662 // Two-block message.
4663 string message = "12345678901234567890123456789012";
4664 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4665 AuthorizationSet out_params;
4666 string ciphertext1 = EncryptMessage(message, params, &out_params);
4667 vector<uint8_t> iv1 = CopyIv(out_params);
4668 EXPECT_EQ(message.size(), ciphertext1.size());
4669
4670 out_params.Clear();
4671
4672 string ciphertext2 = EncryptMessage(message, params, &out_params);
4673 vector<uint8_t> iv2 = CopyIv(out_params);
4674 EXPECT_EQ(message.size(), ciphertext2.size());
4675
4676 // IVs should be random, so ciphertexts should differ.
4677 EXPECT_NE(ciphertext1, ciphertext2);
4678
4679 params.push_back(TAG_NONCE, iv1);
4680 string plaintext = DecryptMessage(ciphertext1, params);
4681 EXPECT_EQ(message, plaintext);
4682}
4683
4684/*
4685 * EncryptionOperationsTest.AesCallerNonce
4686 *
4687 * Verifies that AES caller-provided nonces work correctly.
4688 */
4689TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4690 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4691 .Authorization(TAG_NO_AUTH_REQUIRED)
4692 .AesEncryptionKey(128)
4693 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4694 .Authorization(TAG_CALLER_NONCE)
4695 .Padding(PaddingMode::NONE)));
4696
4697 string message = "12345678901234567890123456789012";
4698
4699 // Don't specify nonce, should get a random one.
4700 AuthorizationSetBuilder params =
4701 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4702 AuthorizationSet out_params;
4703 string ciphertext = EncryptMessage(message, params, &out_params);
4704 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004705 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004706
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004707 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004708 string plaintext = DecryptMessage(ciphertext, params);
4709 EXPECT_EQ(message, plaintext);
4710
4711 // Now specify a nonce, should also work.
4712 params = AuthorizationSetBuilder()
4713 .BlockMode(BlockMode::CBC)
4714 .Padding(PaddingMode::NONE)
4715 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4716 out_params.Clear();
4717 ciphertext = EncryptMessage(message, params, &out_params);
4718
4719 // Decrypt with correct nonce.
4720 plaintext = DecryptMessage(ciphertext, params);
4721 EXPECT_EQ(message, plaintext);
4722
4723 // Try with wrong nonce.
4724 params = AuthorizationSetBuilder()
4725 .BlockMode(BlockMode::CBC)
4726 .Padding(PaddingMode::NONE)
4727 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4728 plaintext = DecryptMessage(ciphertext, params);
4729 EXPECT_NE(message, plaintext);
4730}
4731
4732/*
4733 * EncryptionOperationsTest.AesCallerNonceProhibited
4734 *
4735 * Verifies that caller-provided nonces are not permitted when not specified in the key
4736 * authorizations.
4737 */
4738TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4739 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4740 .Authorization(TAG_NO_AUTH_REQUIRED)
4741 .AesEncryptionKey(128)
4742 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4743 .Padding(PaddingMode::NONE)));
4744
4745 string message = "12345678901234567890123456789012";
4746
4747 // Don't specify nonce, should get a random one.
4748 AuthorizationSetBuilder params =
4749 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4750 AuthorizationSet out_params;
4751 string ciphertext = EncryptMessage(message, params, &out_params);
4752 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004753 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004754
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004755 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004756 string plaintext = DecryptMessage(ciphertext, params);
4757 EXPECT_EQ(message, plaintext);
4758
4759 // Now specify a nonce, should fail
4760 params = AuthorizationSetBuilder()
4761 .BlockMode(BlockMode::CBC)
4762 .Padding(PaddingMode::NONE)
4763 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4764 out_params.Clear();
4765 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4766}
4767
4768/*
4769 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4770 *
4771 * Verifies that AES GCM mode works.
4772 */
4773TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4774 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4775 .Authorization(TAG_NO_AUTH_REQUIRED)
4776 .AesEncryptionKey(128)
4777 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4778 .Padding(PaddingMode::NONE)
4779 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4780
4781 string aad = "foobar";
4782 string message = "123456789012345678901234567890123456";
4783
4784 auto begin_params = AuthorizationSetBuilder()
4785 .BlockMode(BlockMode::GCM)
4786 .Padding(PaddingMode::NONE)
4787 .Authorization(TAG_MAC_LENGTH, 128);
4788
Selene Huang31ab4042020-04-29 04:22:39 -07004789 // Encrypt
4790 AuthorizationSet begin_out_params;
4791 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4792 << "Begin encrypt";
4793 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004794 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4795 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004796 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4797
4798 // Grab nonce
4799 begin_params.push_back(begin_out_params);
4800
4801 // Decrypt.
4802 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004803 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004804 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004805 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004806 EXPECT_EQ(message.length(), plaintext.length());
4807 EXPECT_EQ(message, plaintext);
4808}
4809
4810/*
4811 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4812 *
4813 * Verifies that AES GCM mode works, even when there's a long delay
4814 * between operations.
4815 */
4816TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4817 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4818 .Authorization(TAG_NO_AUTH_REQUIRED)
4819 .AesEncryptionKey(128)
4820 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4821 .Padding(PaddingMode::NONE)
4822 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4823
4824 string aad = "foobar";
4825 string message = "123456789012345678901234567890123456";
4826
4827 auto begin_params = AuthorizationSetBuilder()
4828 .BlockMode(BlockMode::GCM)
4829 .Padding(PaddingMode::NONE)
4830 .Authorization(TAG_MAC_LENGTH, 128);
4831
Selene Huang31ab4042020-04-29 04:22:39 -07004832 // Encrypt
4833 AuthorizationSet begin_out_params;
4834 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4835 << "Begin encrypt";
4836 string ciphertext;
4837 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004838 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004839 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004840 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004841
4842 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4843
4844 // Grab nonce
4845 begin_params.push_back(begin_out_params);
4846
4847 // Decrypt.
4848 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4849 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004850 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004851 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004852 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004853 sleep(5);
4854 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4855 EXPECT_EQ(message.length(), plaintext.length());
4856 EXPECT_EQ(message, plaintext);
4857}
4858
4859/*
4860 * EncryptionOperationsTest.AesGcmDifferentNonces
4861 *
4862 * Verifies that encrypting the same data with different nonces produces different outputs.
4863 */
4864TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4865 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4866 .Authorization(TAG_NO_AUTH_REQUIRED)
4867 .AesEncryptionKey(128)
4868 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4869 .Padding(PaddingMode::NONE)
4870 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4871 .Authorization(TAG_CALLER_NONCE)));
4872
4873 string aad = "foobar";
4874 string message = "123456789012345678901234567890123456";
4875 string nonce1 = "000000000000";
4876 string nonce2 = "111111111111";
4877 string nonce3 = "222222222222";
4878
4879 string ciphertext1 =
4880 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4881 string ciphertext2 =
4882 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4883 string ciphertext3 =
4884 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4885
4886 ASSERT_NE(ciphertext1, ciphertext2);
4887 ASSERT_NE(ciphertext1, ciphertext3);
4888 ASSERT_NE(ciphertext2, ciphertext3);
4889}
4890
4891/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004892 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4893 *
4894 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4895 */
4896TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4897 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4898 .Authorization(TAG_NO_AUTH_REQUIRED)
4899 .AesEncryptionKey(128)
4900 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4901 .Padding(PaddingMode::NONE)
4902 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4903
4904 string aad = "foobar";
4905 string message = "123456789012345678901234567890123456";
4906
4907 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4908 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4909 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4910
4911 ASSERT_NE(ciphertext1, ciphertext2);
4912 ASSERT_NE(ciphertext1, ciphertext3);
4913 ASSERT_NE(ciphertext2, ciphertext3);
4914}
4915
4916/*
Selene Huang31ab4042020-04-29 04:22:39 -07004917 * EncryptionOperationsTest.AesGcmTooShortTag
4918 *
4919 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4920 */
4921TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4922 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4923 .Authorization(TAG_NO_AUTH_REQUIRED)
4924 .AesEncryptionKey(128)
4925 .BlockMode(BlockMode::GCM)
4926 .Padding(PaddingMode::NONE)
4927 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4928 string message = "123456789012345678901234567890123456";
4929 auto params = AuthorizationSetBuilder()
4930 .BlockMode(BlockMode::GCM)
4931 .Padding(PaddingMode::NONE)
4932 .Authorization(TAG_MAC_LENGTH, 96);
4933
4934 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4935}
4936
4937/*
4938 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4939 *
4940 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4941 */
4942TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4943 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4944 .Authorization(TAG_NO_AUTH_REQUIRED)
4945 .AesEncryptionKey(128)
4946 .BlockMode(BlockMode::GCM)
4947 .Padding(PaddingMode::NONE)
4948 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4949 string aad = "foobar";
4950 string message = "123456789012345678901234567890123456";
4951 auto params = AuthorizationSetBuilder()
4952 .BlockMode(BlockMode::GCM)
4953 .Padding(PaddingMode::NONE)
4954 .Authorization(TAG_MAC_LENGTH, 128);
4955
Selene Huang31ab4042020-04-29 04:22:39 -07004956 // Encrypt
4957 AuthorizationSet begin_out_params;
4958 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4959 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004960 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004961
4962 AuthorizationSet finish_out_params;
4963 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004964 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4965 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004966
4967 params = AuthorizationSetBuilder()
4968 .Authorizations(begin_out_params)
4969 .BlockMode(BlockMode::GCM)
4970 .Padding(PaddingMode::NONE)
4971 .Authorization(TAG_MAC_LENGTH, 96);
4972
4973 // Decrypt.
4974 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
4975}
4976
4977/*
4978 * EncryptionOperationsTest.AesGcmCorruptKey
4979 *
4980 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
4981 */
4982TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
4983 const uint8_t nonce_bytes[] = {
4984 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
4985 };
4986 string nonce = make_string(nonce_bytes);
4987 const uint8_t ciphertext_bytes[] = {
4988 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
4989 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
4990 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
4991 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
4992 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
4993 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
4994 };
4995 string ciphertext = make_string(ciphertext_bytes);
4996
4997 auto params = AuthorizationSetBuilder()
4998 .BlockMode(BlockMode::GCM)
4999 .Padding(PaddingMode::NONE)
5000 .Authorization(TAG_MAC_LENGTH, 128)
5001 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5002
5003 auto import_params = AuthorizationSetBuilder()
5004 .Authorization(TAG_NO_AUTH_REQUIRED)
5005 .AesEncryptionKey(128)
5006 .BlockMode(BlockMode::GCM)
5007 .Padding(PaddingMode::NONE)
5008 .Authorization(TAG_CALLER_NONCE)
5009 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5010
5011 // Import correct key and decrypt
5012 const uint8_t key_bytes[] = {
5013 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5014 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5015 };
5016 string key = make_string(key_bytes);
5017 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5018 string plaintext = DecryptMessage(ciphertext, params);
5019 CheckedDeleteKey();
5020
5021 // Corrupt key and attempt to decrypt
5022 key[0] = 0;
5023 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5024 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5025 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5026 CheckedDeleteKey();
5027}
5028
5029/*
5030 * EncryptionOperationsTest.AesGcmAadNoData
5031 *
5032 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5033 * encrypt.
5034 */
5035TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5036 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5037 .Authorization(TAG_NO_AUTH_REQUIRED)
5038 .AesEncryptionKey(128)
5039 .BlockMode(BlockMode::GCM)
5040 .Padding(PaddingMode::NONE)
5041 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5042
5043 string aad = "1234567890123456";
5044 auto params = AuthorizationSetBuilder()
5045 .BlockMode(BlockMode::GCM)
5046 .Padding(PaddingMode::NONE)
5047 .Authorization(TAG_MAC_LENGTH, 128);
5048
Selene Huang31ab4042020-04-29 04:22:39 -07005049 // Encrypt
5050 AuthorizationSet begin_out_params;
5051 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5052 string ciphertext;
5053 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005054 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5055 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005056 EXPECT_TRUE(finish_out_params.empty());
5057
5058 // Grab nonce
5059 params.push_back(begin_out_params);
5060
5061 // Decrypt.
5062 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005063 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005064 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005065 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005066
5067 EXPECT_TRUE(finish_out_params.empty());
5068
5069 EXPECT_EQ("", plaintext);
5070}
5071
5072/*
5073 * EncryptionOperationsTest.AesGcmMultiPartAad
5074 *
5075 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5076 * chunks.
5077 */
5078TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5079 const size_t tag_bits = 128;
5080 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5081 .Authorization(TAG_NO_AUTH_REQUIRED)
5082 .AesEncryptionKey(128)
5083 .BlockMode(BlockMode::GCM)
5084 .Padding(PaddingMode::NONE)
5085 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5086
5087 string message = "123456789012345678901234567890123456";
5088 auto begin_params = AuthorizationSetBuilder()
5089 .BlockMode(BlockMode::GCM)
5090 .Padding(PaddingMode::NONE)
5091 .Authorization(TAG_MAC_LENGTH, tag_bits);
5092 AuthorizationSet begin_out_params;
5093
Selene Huang31ab4042020-04-29 04:22:39 -07005094 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5095
5096 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005097 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5098 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005099 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005100 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5101 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005102
Selene Huang31ab4042020-04-29 04:22:39 -07005103 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005104 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005105
5106 // Grab nonce.
5107 begin_params.push_back(begin_out_params);
5108
5109 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005110 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005111 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005112 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005113 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005114 EXPECT_EQ(message, plaintext);
5115}
5116
5117/*
5118 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5119 *
5120 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5121 */
5122TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5123 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5124 .Authorization(TAG_NO_AUTH_REQUIRED)
5125 .AesEncryptionKey(128)
5126 .BlockMode(BlockMode::GCM)
5127 .Padding(PaddingMode::NONE)
5128 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5129
5130 string message = "123456789012345678901234567890123456";
5131 auto begin_params = AuthorizationSetBuilder()
5132 .BlockMode(BlockMode::GCM)
5133 .Padding(PaddingMode::NONE)
5134 .Authorization(TAG_MAC_LENGTH, 128);
5135 AuthorizationSet begin_out_params;
5136
Selene Huang31ab4042020-04-29 04:22:39 -07005137 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5138
Shawn Willden92d79c02021-02-19 07:31:55 -07005139 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005140 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005141 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5142 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005143
David Drysdaled2cc8c22021-04-15 13:29:45 +01005144 // The failure should have already cancelled the operation.
5145 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5146
Shawn Willden92d79c02021-02-19 07:31:55 -07005147 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005148}
5149
5150/*
5151 * EncryptionOperationsTest.AesGcmBadAad
5152 *
5153 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5154 */
5155TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5156 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5157 .Authorization(TAG_NO_AUTH_REQUIRED)
5158 .AesEncryptionKey(128)
5159 .BlockMode(BlockMode::GCM)
5160 .Padding(PaddingMode::NONE)
5161 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5162
5163 string message = "12345678901234567890123456789012";
5164 auto begin_params = AuthorizationSetBuilder()
5165 .BlockMode(BlockMode::GCM)
5166 .Padding(PaddingMode::NONE)
5167 .Authorization(TAG_MAC_LENGTH, 128);
5168
Selene Huang31ab4042020-04-29 04:22:39 -07005169 // Encrypt
5170 AuthorizationSet begin_out_params;
5171 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005172 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005173 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005174 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005175
5176 // Grab nonce
5177 begin_params.push_back(begin_out_params);
5178
Selene Huang31ab4042020-04-29 04:22:39 -07005179 // Decrypt.
5180 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005181 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005182 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005183 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005184}
5185
5186/*
5187 * EncryptionOperationsTest.AesGcmWrongNonce
5188 *
5189 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5190 */
5191TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5192 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5193 .Authorization(TAG_NO_AUTH_REQUIRED)
5194 .AesEncryptionKey(128)
5195 .BlockMode(BlockMode::GCM)
5196 .Padding(PaddingMode::NONE)
5197 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5198
5199 string message = "12345678901234567890123456789012";
5200 auto begin_params = AuthorizationSetBuilder()
5201 .BlockMode(BlockMode::GCM)
5202 .Padding(PaddingMode::NONE)
5203 .Authorization(TAG_MAC_LENGTH, 128);
5204
Selene Huang31ab4042020-04-29 04:22:39 -07005205 // Encrypt
5206 AuthorizationSet begin_out_params;
5207 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005208 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005209 string ciphertext;
5210 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005211 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005212
5213 // Wrong nonce
5214 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5215
5216 // Decrypt.
5217 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005218 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005219 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005220 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005221
5222 // With wrong nonce, should have gotten garbage plaintext (or none).
5223 EXPECT_NE(message, plaintext);
5224}
5225
5226/*
5227 * EncryptionOperationsTest.AesGcmCorruptTag
5228 *
5229 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5230 */
5231TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5232 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5233 .Authorization(TAG_NO_AUTH_REQUIRED)
5234 .AesEncryptionKey(128)
5235 .BlockMode(BlockMode::GCM)
5236 .Padding(PaddingMode::NONE)
5237 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5238
5239 string aad = "1234567890123456";
5240 string message = "123456789012345678901234567890123456";
5241
5242 auto params = AuthorizationSetBuilder()
5243 .BlockMode(BlockMode::GCM)
5244 .Padding(PaddingMode::NONE)
5245 .Authorization(TAG_MAC_LENGTH, 128);
5246
Selene Huang31ab4042020-04-29 04:22:39 -07005247 // Encrypt
5248 AuthorizationSet begin_out_params;
5249 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005250 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005251 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005252 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005253
5254 // Corrupt tag
5255 ++(*ciphertext.rbegin());
5256
5257 // Grab nonce
5258 params.push_back(begin_out_params);
5259
5260 // Decrypt.
5261 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005262 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005263 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005264 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005265}
5266
5267/*
5268 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5269 *
5270 * Verifies that 3DES is basically functional.
5271 */
5272TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5273 auto auths = AuthorizationSetBuilder()
5274 .TripleDesEncryptionKey(168)
5275 .BlockMode(BlockMode::ECB)
5276 .Authorization(TAG_NO_AUTH_REQUIRED)
5277 .Padding(PaddingMode::NONE);
5278
5279 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5280 // Two-block message.
5281 string message = "1234567890123456";
5282 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5283 string ciphertext1 = EncryptMessage(message, inParams);
5284 EXPECT_EQ(message.size(), ciphertext1.size());
5285
5286 string ciphertext2 = EncryptMessage(string(message), inParams);
5287 EXPECT_EQ(message.size(), ciphertext2.size());
5288
5289 // ECB is deterministic.
5290 EXPECT_EQ(ciphertext1, ciphertext2);
5291
5292 string plaintext = DecryptMessage(ciphertext1, inParams);
5293 EXPECT_EQ(message, plaintext);
5294}
5295
5296/*
5297 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5298 *
5299 * Verifies that CBC keys reject ECB usage.
5300 */
5301TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5302 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5303 .TripleDesEncryptionKey(168)
5304 .BlockMode(BlockMode::CBC)
5305 .Authorization(TAG_NO_AUTH_REQUIRED)
5306 .Padding(PaddingMode::NONE)));
5307
5308 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5309 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5310}
5311
5312/*
5313 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5314 *
5315 * Tests ECB mode with PKCS#7 padding, various message sizes.
5316 */
5317TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5318 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5319 .TripleDesEncryptionKey(168)
5320 .BlockMode(BlockMode::ECB)
5321 .Authorization(TAG_NO_AUTH_REQUIRED)
5322 .Padding(PaddingMode::PKCS7)));
5323
5324 for (size_t i = 0; i < 32; ++i) {
5325 string message(i, 'a');
5326 auto inParams =
5327 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5328 string ciphertext = EncryptMessage(message, inParams);
5329 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5330 string plaintext = DecryptMessage(ciphertext, inParams);
5331 EXPECT_EQ(message, plaintext);
5332 }
5333}
5334
5335/*
5336 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5337 *
5338 * Verifies that keys configured for no padding reject PKCS7 padding
5339 */
5340TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5341 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5342 .TripleDesEncryptionKey(168)
5343 .BlockMode(BlockMode::ECB)
5344 .Authorization(TAG_NO_AUTH_REQUIRED)
5345 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005346 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5347 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005348}
5349
5350/*
5351 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5352 *
5353 * Verifies that corrupted padding is detected.
5354 */
5355TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5356 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5357 .TripleDesEncryptionKey(168)
5358 .BlockMode(BlockMode::ECB)
5359 .Authorization(TAG_NO_AUTH_REQUIRED)
5360 .Padding(PaddingMode::PKCS7)));
5361
5362 string message = "a";
5363 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5364 EXPECT_EQ(8U, ciphertext.size());
5365 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005366
5367 AuthorizationSetBuilder begin_params;
5368 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5369 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07005370
5371 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5372 ++ciphertext[ciphertext.size() / 2];
5373
5374 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5375 string plaintext;
5376 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5377 ErrorCode error = Finish(&plaintext);
5378 if (error == ErrorCode::INVALID_ARGUMENT) {
5379 // This is the expected error, we can exit the test now.
5380 return;
5381 } else {
5382 // Very small chance we got valid decryption, so try again.
5383 ASSERT_EQ(error, ErrorCode::OK);
5384 }
5385 }
5386 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005387}
5388
5389struct TripleDesTestVector {
5390 const char* name;
5391 const KeyPurpose purpose;
5392 const BlockMode block_mode;
5393 const PaddingMode padding_mode;
5394 const char* key;
5395 const char* iv;
5396 const char* input;
5397 const char* output;
5398};
5399
5400// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5401// of the NIST vectors are multiples of the block size.
5402static const TripleDesTestVector kTripleDesTestVectors[] = {
5403 {
5404 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5405 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5406 "", // IV
5407 "329d86bdf1bc5af4", // input
5408 "d946c2756d78633f", // output
5409 },
5410 {
5411 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5412 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5413 "", // IV
5414 "6b1540781b01ce1997adae102dbf3c5b", // input
5415 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5416 },
5417 {
5418 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5419 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5420 "", // IV
5421 "6daad94ce08acfe7", // input
5422 "660e7d32dcc90e79", // output
5423 },
5424 {
5425 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5426 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5427 "", // IV
5428 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5429 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5430 },
5431 {
5432 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5433 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5434 "43f791134c5647ba", // IV
5435 "dcc153cef81d6f24", // input
5436 "92538bd8af18d3ba", // output
5437 },
5438 {
5439 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5440 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5441 "c2e999cb6249023c", // IV
5442 "c689aee38a301bb316da75db36f110b5", // input
5443 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5444 },
5445 {
5446 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5447 PaddingMode::PKCS7,
5448 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5449 "c2e999cb6249023c", // IV
5450 "c689aee38a301bb316da75db36f110b500", // input
5451 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5452 },
5453 {
5454 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5455 PaddingMode::PKCS7,
5456 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5457 "c2e999cb6249023c", // IV
5458 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5459 "c689aee38a301bb316da75db36f110b500", // output
5460 },
5461 {
5462 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5463 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5464 "41746c7e442d3681", // IV
5465 "c53a7b0ec40600fe", // input
5466 "d4f00eb455de1034", // output
5467 },
5468 {
5469 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5470 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5471 "3982bc02c3727d45", // IV
5472 "6006f10adef52991fcc777a1238bbb65", // input
5473 "edae09288e9e3bc05746d872b48e3b29", // output
5474 },
5475};
5476
5477/*
5478 * EncryptionOperationsTest.TripleDesTestVector
5479 *
5480 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5481 */
5482TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5483 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5484 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5485 SCOPED_TRACE(test->name);
5486 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5487 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5488 hex2str(test->output));
5489 }
5490}
5491
5492/*
5493 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5494 *
5495 * Validates CBC mode functionality.
5496 */
5497TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5498 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5499 .TripleDesEncryptionKey(168)
5500 .BlockMode(BlockMode::CBC)
5501 .Authorization(TAG_NO_AUTH_REQUIRED)
5502 .Padding(PaddingMode::NONE)));
5503
5504 ASSERT_GT(key_blob_.size(), 0U);
5505
5506 // Two-block message.
5507 string message = "1234567890123456";
5508 vector<uint8_t> iv1;
5509 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5510 EXPECT_EQ(message.size(), ciphertext1.size());
5511
5512 vector<uint8_t> iv2;
5513 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5514 EXPECT_EQ(message.size(), ciphertext2.size());
5515
5516 // IVs should be random, so ciphertexts should differ.
5517 EXPECT_NE(iv1, iv2);
5518 EXPECT_NE(ciphertext1, ciphertext2);
5519
5520 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5521 EXPECT_EQ(message, plaintext);
5522}
5523
5524/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005525 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5526 *
5527 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5528 */
5529TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5530 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5531 .TripleDesEncryptionKey(168)
5532 .BlockMode(BlockMode::CBC)
5533 .Authorization(TAG_NO_AUTH_REQUIRED)
5534 .Authorization(TAG_CALLER_NONCE)
5535 .Padding(PaddingMode::NONE)));
5536 auto params = AuthorizationSetBuilder()
5537 .BlockMode(BlockMode::CBC)
5538 .Padding(PaddingMode::NONE)
5539 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5540 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5541}
5542
5543/*
Selene Huang31ab4042020-04-29 04:22:39 -07005544 * EncryptionOperationsTest.TripleDesCallerIv
5545 *
5546 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5547 */
5548TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5549 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5550 .TripleDesEncryptionKey(168)
5551 .BlockMode(BlockMode::CBC)
5552 .Authorization(TAG_NO_AUTH_REQUIRED)
5553 .Authorization(TAG_CALLER_NONCE)
5554 .Padding(PaddingMode::NONE)));
5555 string message = "1234567890123456";
5556 vector<uint8_t> iv;
5557 // Don't specify IV, should get a random one.
5558 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5559 EXPECT_EQ(message.size(), ciphertext1.size());
5560 EXPECT_EQ(8U, iv.size());
5561
5562 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5563 EXPECT_EQ(message, plaintext);
5564
5565 // Now specify an IV, should also work.
5566 iv = AidlBuf("abcdefgh");
5567 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5568
5569 // Decrypt with correct IV.
5570 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5571 EXPECT_EQ(message, plaintext);
5572
5573 // Now try with wrong IV.
5574 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5575 EXPECT_NE(message, plaintext);
5576}
5577
5578/*
5579 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5580 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005581 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005582 */
5583TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5584 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5585 .TripleDesEncryptionKey(168)
5586 .BlockMode(BlockMode::CBC)
5587 .Authorization(TAG_NO_AUTH_REQUIRED)
5588 .Padding(PaddingMode::NONE)));
5589
5590 string message = "12345678901234567890123456789012";
5591 vector<uint8_t> iv;
5592 // Don't specify nonce, should get a random one.
5593 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5594 EXPECT_EQ(message.size(), ciphertext1.size());
5595 EXPECT_EQ(8U, iv.size());
5596
5597 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5598 EXPECT_EQ(message, plaintext);
5599
5600 // Now specify a nonce, should fail.
5601 auto input_params = AuthorizationSetBuilder()
5602 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5603 .BlockMode(BlockMode::CBC)
5604 .Padding(PaddingMode::NONE);
5605 AuthorizationSet output_params;
5606 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5607 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5608}
5609
5610/*
5611 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5612 *
5613 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5614 */
5615TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5616 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5617 .TripleDesEncryptionKey(168)
5618 .BlockMode(BlockMode::ECB)
5619 .Authorization(TAG_NO_AUTH_REQUIRED)
5620 .Padding(PaddingMode::NONE)));
5621 // Two-block message.
5622 string message = "1234567890123456";
5623 auto begin_params =
5624 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5625 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5626}
5627
5628/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005629 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005630 *
5631 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5632 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005633TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5634 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5635 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5636 .TripleDesEncryptionKey(168)
5637 .BlockMode(blockMode)
5638 .Authorization(TAG_NO_AUTH_REQUIRED)
5639 .Padding(PaddingMode::NONE)));
5640 // Message is slightly shorter than two blocks.
5641 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005642
David Drysdaled2cc8c22021-04-15 13:29:45 +01005643 auto begin_params =
5644 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5645 AuthorizationSet output_params;
5646 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5647 string ciphertext;
5648 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5649
5650 CheckedDeleteKey();
5651 }
Selene Huang31ab4042020-04-29 04:22:39 -07005652}
5653
5654/*
5655 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5656 *
5657 * Verifies that PKCS7 padding works correctly in CBC mode.
5658 */
5659TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5660 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5661 .TripleDesEncryptionKey(168)
5662 .BlockMode(BlockMode::CBC)
5663 .Authorization(TAG_NO_AUTH_REQUIRED)
5664 .Padding(PaddingMode::PKCS7)));
5665
5666 // Try various message lengths; all should work.
5667 for (size_t i = 0; i < 32; ++i) {
5668 string message(i, 'a');
5669 vector<uint8_t> iv;
5670 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5671 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5672 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5673 EXPECT_EQ(message, plaintext);
5674 }
5675}
5676
5677/*
5678 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5679 *
5680 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5681 */
5682TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5683 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5684 .TripleDesEncryptionKey(168)
5685 .BlockMode(BlockMode::CBC)
5686 .Authorization(TAG_NO_AUTH_REQUIRED)
5687 .Padding(PaddingMode::NONE)));
5688
5689 // Try various message lengths; all should fail.
5690 for (size_t i = 0; i < 32; ++i) {
5691 auto begin_params =
5692 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5693 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5694 }
5695}
5696
5697/*
5698 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5699 *
5700 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5701 */
5702TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5703 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5704 .TripleDesEncryptionKey(168)
5705 .BlockMode(BlockMode::CBC)
5706 .Authorization(TAG_NO_AUTH_REQUIRED)
5707 .Padding(PaddingMode::PKCS7)));
5708
5709 string message = "a";
5710 vector<uint8_t> iv;
5711 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5712 EXPECT_EQ(8U, ciphertext.size());
5713 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005714
5715 auto begin_params = AuthorizationSetBuilder()
5716 .BlockMode(BlockMode::CBC)
5717 .Padding(PaddingMode::PKCS7)
5718 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07005719
5720 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5721 ++ciphertext[ciphertext.size() / 2];
5722 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5723 string plaintext;
5724 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5725 ErrorCode error = Finish(&plaintext);
5726 if (error == ErrorCode::INVALID_ARGUMENT) {
5727 // This is the expected error, we can exit the test now.
5728 return;
5729 } else {
5730 // Very small chance we got valid decryption, so try again.
5731 ASSERT_EQ(error, ErrorCode::OK);
5732 }
5733 }
5734 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005735}
5736
5737/*
5738 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5739 *
5740 * Verifies that 3DES CBC works with many different input sizes.
5741 */
5742TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5743 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5744 .TripleDesEncryptionKey(168)
5745 .BlockMode(BlockMode::CBC)
5746 .Authorization(TAG_NO_AUTH_REQUIRED)
5747 .Padding(PaddingMode::NONE)));
5748
5749 int increment = 7;
5750 string message(240, 'a');
5751 AuthorizationSet input_params =
5752 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5753 AuthorizationSet output_params;
5754 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5755
5756 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005757 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005758 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005759 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5760 EXPECT_EQ(message.size(), ciphertext.size());
5761
5762 // Move TAG_NONCE into input_params
5763 input_params = output_params;
5764 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5765 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5766 output_params.Clear();
5767
5768 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5769 string plaintext;
5770 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005771 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005772 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5773 EXPECT_EQ(ciphertext.size(), plaintext.size());
5774 EXPECT_EQ(message, plaintext);
5775}
5776
5777INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5778
5779typedef KeyMintAidlTestBase MaxOperationsTest;
5780
5781/*
5782 * MaxOperationsTest.TestLimitAes
5783 *
5784 * Verifies that the max uses per boot tag works correctly with AES keys.
5785 */
5786TEST_P(MaxOperationsTest, TestLimitAes) {
5787 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5788
5789 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5790 .Authorization(TAG_NO_AUTH_REQUIRED)
5791 .AesEncryptionKey(128)
5792 .EcbMode()
5793 .Padding(PaddingMode::NONE)
5794 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5795
5796 string message = "1234567890123456";
5797
5798 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5799
5800 EncryptMessage(message, params);
5801 EncryptMessage(message, params);
5802 EncryptMessage(message, params);
5803
5804 // Fourth time should fail.
5805 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5806}
5807
5808/*
Qi Wud22ec842020-11-26 13:27:53 +08005809 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005810 *
5811 * Verifies that the max uses per boot tag works correctly with RSA keys.
5812 */
5813TEST_P(MaxOperationsTest, TestLimitRsa) {
5814 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5815
5816 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5817 .Authorization(TAG_NO_AUTH_REQUIRED)
5818 .RsaSigningKey(1024, 65537)
5819 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005820 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5821 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005822
5823 string message = "1234567890123456";
5824
5825 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5826
5827 SignMessage(message, params);
5828 SignMessage(message, params);
5829 SignMessage(message, params);
5830
5831 // Fourth time should fail.
5832 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5833}
5834
5835INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5836
Qi Wud22ec842020-11-26 13:27:53 +08005837typedef KeyMintAidlTestBase UsageCountLimitTest;
5838
5839/*
Qi Wubeefae42021-01-28 23:16:37 +08005840 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005841 *
Qi Wubeefae42021-01-28 23:16:37 +08005842 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005843 */
Qi Wubeefae42021-01-28 23:16:37 +08005844TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005845 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5846
5847 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5848 .Authorization(TAG_NO_AUTH_REQUIRED)
5849 .AesEncryptionKey(128)
5850 .EcbMode()
5851 .Padding(PaddingMode::NONE)
5852 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5853
5854 // Check the usage count limit tag appears in the authorizations.
5855 AuthorizationSet auths;
5856 for (auto& entry : key_characteristics_) {
5857 auths.push_back(AuthorizationSet(entry.authorizations));
5858 }
5859 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5860 << "key usage count limit " << 1U << " missing";
5861
5862 string message = "1234567890123456";
5863 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5864
Qi Wubeefae42021-01-28 23:16:37 +08005865 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5866 AuthorizationSet keystore_auths =
5867 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5868
Qi Wud22ec842020-11-26 13:27:53 +08005869 // First usage of AES key should work.
5870 EncryptMessage(message, params);
5871
Qi Wud22ec842020-11-26 13:27:53 +08005872 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5873 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5874 // must be invalidated from secure storage (such as RPMB partition).
5875 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5876 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005877 // Usage count limit tag is enforced by keystore, keymint does nothing.
5878 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005879 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5880 }
5881}
5882
5883/*
Qi Wubeefae42021-01-28 23:16:37 +08005884 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005885 *
Qi Wubeefae42021-01-28 23:16:37 +08005886 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005887 */
Qi Wubeefae42021-01-28 23:16:37 +08005888TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5889 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5890
5891 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5892 .Authorization(TAG_NO_AUTH_REQUIRED)
5893 .AesEncryptionKey(128)
5894 .EcbMode()
5895 .Padding(PaddingMode::NONE)
5896 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5897
5898 // Check the usage count limit tag appears in the authorizations.
5899 AuthorizationSet auths;
5900 for (auto& entry : key_characteristics_) {
5901 auths.push_back(AuthorizationSet(entry.authorizations));
5902 }
5903 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5904 << "key usage count limit " << 3U << " missing";
5905
5906 string message = "1234567890123456";
5907 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5908
5909 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5910 AuthorizationSet keystore_auths =
5911 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5912
5913 EncryptMessage(message, params);
5914 EncryptMessage(message, params);
5915 EncryptMessage(message, params);
5916
5917 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5918 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5919 // must be invalidated from secure storage (such as RPMB partition).
5920 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5921 } else {
5922 // Usage count limit tag is enforced by keystore, keymint does nothing.
5923 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5924 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5925 }
5926}
5927
5928/*
5929 * UsageCountLimitTest.TestSingleUseRsa
5930 *
5931 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5932 */
5933TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005934 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5935
5936 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5937 .Authorization(TAG_NO_AUTH_REQUIRED)
5938 .RsaSigningKey(1024, 65537)
5939 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005940 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5941 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005942
5943 // Check the usage count limit tag appears in the authorizations.
5944 AuthorizationSet auths;
5945 for (auto& entry : key_characteristics_) {
5946 auths.push_back(AuthorizationSet(entry.authorizations));
5947 }
5948 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5949 << "key usage count limit " << 1U << " missing";
5950
5951 string message = "1234567890123456";
5952 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5953
Qi Wubeefae42021-01-28 23:16:37 +08005954 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5955 AuthorizationSet keystore_auths =
5956 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5957
Qi Wud22ec842020-11-26 13:27:53 +08005958 // First usage of RSA key should work.
5959 SignMessage(message, params);
5960
Qi Wud22ec842020-11-26 13:27:53 +08005961 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5962 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5963 // must be invalidated from secure storage (such as RPMB partition).
5964 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5965 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005966 // Usage count limit tag is enforced by keystore, keymint does nothing.
5967 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5968 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5969 }
5970}
5971
5972/*
5973 * UsageCountLimitTest.TestLimitUseRsa
5974 *
5975 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5976 */
5977TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
5978 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5979
5980 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5981 .Authorization(TAG_NO_AUTH_REQUIRED)
5982 .RsaSigningKey(1024, 65537)
5983 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005984 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
5985 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08005986
5987 // Check the usage count limit tag appears in the authorizations.
5988 AuthorizationSet auths;
5989 for (auto& entry : key_characteristics_) {
5990 auths.push_back(AuthorizationSet(entry.authorizations));
5991 }
5992 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5993 << "key usage count limit " << 3U << " missing";
5994
5995 string message = "1234567890123456";
5996 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5997
5998 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5999 AuthorizationSet keystore_auths =
6000 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6001
6002 SignMessage(message, params);
6003 SignMessage(message, params);
6004 SignMessage(message, params);
6005
6006 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6007 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6008 // must be invalidated from secure storage (such as RPMB partition).
6009 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6010 } else {
6011 // Usage count limit tag is enforced by keystore, keymint does nothing.
6012 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006013 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6014 }
6015}
6016
Qi Wu8e727f72021-02-11 02:49:33 +08006017/*
6018 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6019 *
6020 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6021 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6022 * in hardware.
6023 */
6024TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
6025 if (SecLevel() == SecurityLevel::STRONGBOX) return;
6026
6027 auto error = GenerateKey(AuthorizationSetBuilder()
6028 .RsaSigningKey(2048, 65537)
6029 .Digest(Digest::NONE)
6030 .Padding(PaddingMode::NONE)
6031 .Authorization(TAG_NO_AUTH_REQUIRED)
6032 .Authorization(TAG_ROLLBACK_RESISTANCE)
6033 .SetDefaultValidity());
6034 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6035
6036 if (error == ErrorCode::OK) {
6037 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6038 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6039 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6040 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6041
6042 // The KeyMint should also enforce single use key in hardware when it supports rollback
6043 // resistance.
6044 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6045 .Authorization(TAG_NO_AUTH_REQUIRED)
6046 .RsaSigningKey(1024, 65537)
6047 .NoDigestOrPadding()
6048 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6049 .SetDefaultValidity()));
6050
6051 // Check the usage count limit tag appears in the hardware authorizations.
6052 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6053 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6054 << "key usage count limit " << 1U << " missing";
6055
6056 string message = "1234567890123456";
6057 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6058
6059 // First usage of RSA key should work.
6060 SignMessage(message, params);
6061
6062 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6063 // must be invalidated from secure storage (such as RPMB partition).
6064 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6065 }
6066}
6067
Qi Wud22ec842020-11-26 13:27:53 +08006068INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6069
David Drysdale7de9feb2021-03-05 14:56:19 +00006070typedef KeyMintAidlTestBase GetHardwareInfoTest;
6071
6072TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6073 // Retrieving hardware info should give the same result each time.
6074 KeyMintHardwareInfo info;
6075 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6076 KeyMintHardwareInfo info2;
6077 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6078 EXPECT_EQ(info, info2);
6079}
6080
6081INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6082
Selene Huang31ab4042020-04-29 04:22:39 -07006083typedef KeyMintAidlTestBase AddEntropyTest;
6084
6085/*
6086 * AddEntropyTest.AddEntropy
6087 *
6088 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6089 * is actually added.
6090 */
6091TEST_P(AddEntropyTest, AddEntropy) {
6092 string data = "foo";
6093 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6094}
6095
6096/*
6097 * AddEntropyTest.AddEmptyEntropy
6098 *
6099 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6100 */
6101TEST_P(AddEntropyTest, AddEmptyEntropy) {
6102 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6103}
6104
6105/*
6106 * AddEntropyTest.AddLargeEntropy
6107 *
6108 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6109 */
6110TEST_P(AddEntropyTest, AddLargeEntropy) {
6111 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6112}
6113
David Drysdalebb3d85e2021-04-13 11:15:51 +01006114/*
6115 * AddEntropyTest.AddTooLargeEntropy
6116 *
6117 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6118 */
6119TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6120 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6121 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6122}
6123
Selene Huang31ab4042020-04-29 04:22:39 -07006124INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6125
Selene Huang31ab4042020-04-29 04:22:39 -07006126typedef KeyMintAidlTestBase KeyDeletionTest;
6127
6128/**
6129 * KeyDeletionTest.DeleteKey
6130 *
6131 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6132 * valid key blob.
6133 */
6134TEST_P(KeyDeletionTest, DeleteKey) {
6135 auto error = GenerateKey(AuthorizationSetBuilder()
6136 .RsaSigningKey(2048, 65537)
6137 .Digest(Digest::NONE)
6138 .Padding(PaddingMode::NONE)
6139 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006140 .Authorization(TAG_ROLLBACK_RESISTANCE)
6141 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006142 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6143
6144 // Delete must work if rollback protection is implemented
6145 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006146 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006147 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6148
6149 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
6150
6151 string message = "12345678901234567890123456789012";
6152 AuthorizationSet begin_out_params;
6153 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6154 Begin(KeyPurpose::SIGN, key_blob_,
6155 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6156 &begin_out_params));
6157 AbortIfNeeded();
6158 key_blob_ = AidlBuf();
6159 }
6160}
6161
6162/**
6163 * KeyDeletionTest.DeleteInvalidKey
6164 *
6165 * This test checks that the HAL excepts invalid key blobs..
6166 */
6167TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6168 // Generate key just to check if rollback protection is implemented
6169 auto error = GenerateKey(AuthorizationSetBuilder()
6170 .RsaSigningKey(2048, 65537)
6171 .Digest(Digest::NONE)
6172 .Padding(PaddingMode::NONE)
6173 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006174 .Authorization(TAG_ROLLBACK_RESISTANCE)
6175 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006176 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6177
6178 // Delete must work if rollback protection is implemented
6179 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006180 AuthorizationSet enforced(SecLevelAuthorizations());
6181 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006182
6183 // Delete the key we don't care about the result at this point.
6184 DeleteKey();
6185
6186 // Now create an invalid key blob and delete it.
6187 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
6188
6189 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6190 }
6191}
6192
6193/**
6194 * KeyDeletionTest.DeleteAllKeys
6195 *
6196 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6197 *
6198 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6199 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6200 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6201 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6202 * credentials stored in Keystore/Keymint.
6203 */
6204TEST_P(KeyDeletionTest, DeleteAllKeys) {
6205 if (!arm_deleteAllKeys) return;
6206 auto error = GenerateKey(AuthorizationSetBuilder()
6207 .RsaSigningKey(2048, 65537)
6208 .Digest(Digest::NONE)
6209 .Padding(PaddingMode::NONE)
6210 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06006211 .Authorization(TAG_ROLLBACK_RESISTANCE)
6212 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006213 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6214
6215 // Delete must work if rollback protection is implemented
6216 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006217 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006218 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6219
6220 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
6221
6222 string message = "12345678901234567890123456789012";
6223 AuthorizationSet begin_out_params;
6224
6225 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6226 Begin(KeyPurpose::SIGN, key_blob_,
6227 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6228 &begin_out_params));
6229 AbortIfNeeded();
6230 key_blob_ = AidlBuf();
6231 }
6232}
6233
6234INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6235
David Drysdaled2cc8c22021-04-15 13:29:45 +01006236typedef KeyMintAidlTestBase KeyUpgradeTest;
6237
6238/**
6239 * KeyUpgradeTest.UpgradeInvalidKey
6240 *
6241 * This test checks that the HAL excepts invalid key blobs..
6242 */
6243TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6244 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6245
6246 std::vector<uint8_t> new_blob;
6247 Status result = keymint_->upgradeKey(key_blob,
6248 AuthorizationSetBuilder()
6249 .Authorization(TAG_APPLICATION_ID, "clientid")
6250 .Authorization(TAG_APPLICATION_DATA, "appdata")
6251 .vector_data(),
6252 &new_blob);
6253 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6254}
6255
6256INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6257
Selene Huang31ab4042020-04-29 04:22:39 -07006258using UpgradeKeyTest = KeyMintAidlTestBase;
6259
6260/*
6261 * UpgradeKeyTest.UpgradeKey
6262 *
6263 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6264 */
6265TEST_P(UpgradeKeyTest, UpgradeKey) {
6266 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6267 .AesEncryptionKey(128)
6268 .Padding(PaddingMode::NONE)
6269 .Authorization(TAG_NO_AUTH_REQUIRED)));
6270
6271 auto result = UpgradeKey(key_blob_);
6272
6273 // Key doesn't need upgrading. Should get okay, but no new key blob.
6274 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6275}
6276
6277INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6278
6279using ClearOperationsTest = KeyMintAidlTestBase;
6280
6281/*
6282 * ClearSlotsTest.TooManyOperations
6283 *
6284 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6285 * operations are started without being finished or aborted. Also verifies
6286 * that aborting the operations clears the operations.
6287 *
6288 */
6289TEST_P(ClearOperationsTest, TooManyOperations) {
6290 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6291 .Authorization(TAG_NO_AUTH_REQUIRED)
6292 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006293 .Padding(PaddingMode::NONE)
6294 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006295
6296 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6297 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006298 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006299 AuthorizationSet out_params;
6300 ErrorCode result;
6301 size_t i;
6302
6303 for (i = 0; i < max_operations; i++) {
6304 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6305 if (ErrorCode::OK != result) {
6306 break;
6307 }
6308 }
6309 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6310 // Try again just in case there's a weird overflow bug
6311 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6312 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6313 for (size_t j = 0; j < i; j++) {
6314 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6315 << "Aboort failed for i = " << j << std::endl;
6316 }
6317 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6318 AbortIfNeeded();
6319}
6320
6321INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6322
6323typedef KeyMintAidlTestBase TransportLimitTest;
6324
6325/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006326 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006327 *
6328 * Verifies that passing input data to finish succeeds as expected.
6329 */
6330TEST_P(TransportLimitTest, LargeFinishInput) {
6331 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6332 .Authorization(TAG_NO_AUTH_REQUIRED)
6333 .AesEncryptionKey(128)
6334 .BlockMode(BlockMode::ECB)
6335 .Padding(PaddingMode::NONE)));
6336
6337 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6338 auto cipher_params =
6339 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6340
6341 AuthorizationSet out_params;
6342 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6343
6344 string plain_message = std::string(1 << msg_size, 'x');
6345 string encrypted_message;
6346 auto rc = Finish(plain_message, &encrypted_message);
6347
6348 EXPECT_EQ(ErrorCode::OK, rc);
6349 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6350 << "Encrypt finish returned OK, but did not consume all of the given input";
6351 cipher_params.push_back(out_params);
6352
6353 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6354
6355 string decrypted_message;
6356 rc = Finish(encrypted_message, &decrypted_message);
6357 EXPECT_EQ(ErrorCode::OK, rc);
6358 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6359 << "Decrypt finish returned OK, did not consume all of the given input";
6360 }
6361}
6362
6363INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6364
David Zeuthene0c40892021-01-08 12:54:11 -05006365typedef KeyMintAidlTestBase KeyAgreementTest;
6366
6367int CurveToOpenSslCurveName(EcCurve curve) {
6368 switch (curve) {
6369 case EcCurve::P_224:
6370 return NID_secp224r1;
6371 case EcCurve::P_256:
6372 return NID_X9_62_prime256v1;
6373 case EcCurve::P_384:
6374 return NID_secp384r1;
6375 case EcCurve::P_521:
6376 return NID_secp521r1;
6377 }
6378}
6379
6380/*
6381 * KeyAgreementTest.Ecdh
6382 *
6383 * Verifies that ECDH works for all curves
6384 */
6385TEST_P(KeyAgreementTest, Ecdh) {
6386 // Because it's possible to use this API with keys on different curves, we
6387 // check all N^2 combinations where N is the number of supported
6388 // curves.
6389 //
6390 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6391 // lot more curves we can be smart about things and just pick |otherCurve| so
6392 // it's not |curve| and that way we end up with only 2*N runs
6393 //
6394 for (auto curve : ValidCurves()) {
6395 for (auto localCurve : ValidCurves()) {
6396 // Generate EC key locally (with access to private key material)
6397 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6398 int curveName = CurveToOpenSslCurveName(localCurve);
6399 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6400 ASSERT_NE(group, nullptr);
6401 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6402 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6403 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6404 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6405
6406 // Get encoded form of the public part of the locally generated key...
6407 unsigned char* p = nullptr;
6408 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6409 ASSERT_GT(encodedPublicKeySize, 0);
6410 vector<uint8_t> encodedPublicKey(
6411 reinterpret_cast<const uint8_t*>(p),
6412 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6413 OPENSSL_free(p);
6414
6415 // Generate EC key in KeyMint (only access to public key material)
6416 vector<uint8_t> challenge = {0x41, 0x42};
6417 EXPECT_EQ(
6418 ErrorCode::OK,
6419 GenerateKey(AuthorizationSetBuilder()
6420 .Authorization(TAG_NO_AUTH_REQUIRED)
6421 .Authorization(TAG_EC_CURVE, curve)
6422 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6423 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6424 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006425 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6426 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006427 << "Failed to generate key";
6428 ASSERT_GT(cert_chain_.size(), 0);
6429 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6430 ASSERT_NE(kmKeyCert, nullptr);
6431 // Check that keyAgreement (bit 4) is set in KeyUsage
6432 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6433 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6434 ASSERT_NE(kmPkey, nullptr);
6435 if (dump_Attestations) {
6436 for (size_t n = 0; n < cert_chain_.size(); n++) {
6437 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6438 }
6439 }
6440
6441 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6442 if (curve != localCurve) {
6443 // If the keys are using different curves KeyMint should fail with
6444 // ErrorCode:INVALID_ARGUMENT. Check that.
6445 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6446 string ZabFromKeyMintStr;
6447 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6448 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6449 &ZabFromKeyMintStr));
6450
6451 } else {
6452 // Otherwise if the keys are using the same curve, it should work.
6453 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6454 string ZabFromKeyMintStr;
6455 EXPECT_EQ(ErrorCode::OK,
6456 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6457 &ZabFromKeyMintStr));
6458 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6459
6460 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6461 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6462 ASSERT_NE(ctx, nullptr);
6463 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6464 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6465 size_t ZabFromTestLen = 0;
6466 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6467 vector<uint8_t> ZabFromTest;
6468 ZabFromTest.resize(ZabFromTestLen);
6469 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6470
6471 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6472 }
6473
6474 CheckedDeleteKey();
6475 }
6476 }
6477}
6478
6479INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6480
David Drysdaled2cc8c22021-04-15 13:29:45 +01006481using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6482
6483// This is a problematic test, as it can render the device under test permanently unusable.
6484// Re-enable and run at your own risk.
6485TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6486 auto result = DestroyAttestationIds();
6487 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6488}
6489
6490INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6491
Shawn Willdend659c7c2021-02-19 14:51:51 -07006492using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006493
David Drysdaledb0dcf52021-05-18 11:43:31 +01006494/*
6495 * EarlyBootKeyTest.CreateEarlyBootKeys
6496 *
6497 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6498 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006499TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01006500 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006501 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6502 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6503
David Drysdaleadfe6112021-05-27 12:00:53 +01006504 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6505 ASSERT_GT(keyData.blob.size(), 0U);
6506 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6507 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6508 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006509 CheckedDeleteKey(&aesKeyData.blob);
6510 CheckedDeleteKey(&hmacKeyData.blob);
6511 CheckedDeleteKey(&rsaKeyData.blob);
6512 CheckedDeleteKey(&ecdsaKeyData.blob);
6513}
6514
David Drysdaledb0dcf52021-05-18 11:43:31 +01006515/*
David Drysdaleadfe6112021-05-27 12:00:53 +01006516 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6517 *
6518 * Verifies that creating an early boot key with attestation succeeds.
6519 */
6520TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6521 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6522 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6523 builder->AttestationChallenge("challenge");
6524 builder->AttestationApplicationId("app_id");
6525 });
6526
6527 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6528 ASSERT_GT(keyData.blob.size(), 0U);
6529 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6530 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6531 }
6532 CheckedDeleteKey(&aesKeyData.blob);
6533 CheckedDeleteKey(&hmacKeyData.blob);
6534 CheckedDeleteKey(&rsaKeyData.blob);
6535 CheckedDeleteKey(&ecdsaKeyData.blob);
6536}
6537
6538/*
6539 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01006540 *
6541 * Verifies that using early boot keys at a later stage fails.
6542 */
6543TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6544 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6545 .Authorization(TAG_NO_AUTH_REQUIRED)
6546 .Authorization(TAG_EARLY_BOOT_ONLY)
6547 .HmacKey(128)
6548 .Digest(Digest::SHA_2_256)
6549 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6550 AuthorizationSet output_params;
6551 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6552 AuthorizationSetBuilder()
6553 .Digest(Digest::SHA_2_256)
6554 .Authorization(TAG_MAC_LENGTH, 256),
6555 &output_params));
6556}
6557
6558/*
6559 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6560 *
6561 * Verifies that importing early boot keys fails.
6562 */
6563TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6564 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6565 .Authorization(TAG_NO_AUTH_REQUIRED)
6566 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01006567 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01006568 .Digest(Digest::SHA_2_256)
6569 .SetDefaultValidity(),
6570 KeyFormat::PKCS8, ec_256_key));
6571}
6572
David Drysdaled2cc8c22021-04-15 13:29:45 +01006573// 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 +00006574// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6575// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6576// early boot, so you'll have to reboot between runs.
6577TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6578 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6579 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6580 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6581 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6582 EXPECT_TRUE(
6583 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6584 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6585 EXPECT_TRUE(
6586 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6587
6588 // Should be able to use keys, since early boot has not ended
6589 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6590 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6591 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6592 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6593
6594 // End early boot
6595 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6596 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6597
6598 // Should not be able to use already-created keys.
6599 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6600 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6601 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6602 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6603
6604 CheckedDeleteKey(&aesKeyData.blob);
6605 CheckedDeleteKey(&hmacKeyData.blob);
6606 CheckedDeleteKey(&rsaKeyData.blob);
6607 CheckedDeleteKey(&ecdsaKeyData.blob);
6608
6609 // Should not be able to create new keys
6610 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6611 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6612
6613 CheckedDeleteKey(&aesKeyData.blob);
6614 CheckedDeleteKey(&hmacKeyData.blob);
6615 CheckedDeleteKey(&rsaKeyData.blob);
6616 CheckedDeleteKey(&ecdsaKeyData.blob);
6617}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006618
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006619INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6620
Shawn Willdend659c7c2021-02-19 14:51:51 -07006621using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006622
6623// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6624// between runs... and on most test devices there are no enrolled credentials so it can't be
6625// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6626// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6627// a manual test process, which includes unlocking between runs, which is why it's included here.
6628// Well, that and the fact that it's the only test we can do without also making calls into the
6629// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6630// implications might be, so that may or may not be a solution.
6631TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6632 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6633 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6634
6635 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6636 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6637 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6638 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6639
6640 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006641 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006642 ASSERT_EQ(ErrorCode::OK, rc);
6643 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6644 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6645 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6646 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6647
6648 CheckedDeleteKey(&aesKeyData.blob);
6649 CheckedDeleteKey(&hmacKeyData.blob);
6650 CheckedDeleteKey(&rsaKeyData.blob);
6651 CheckedDeleteKey(&ecdsaKeyData.blob);
6652}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006653
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006654INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6655
Janis Danisevskis24c04702020-12-16 18:28:39 -08006656} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006657
6658int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006659 std::cout << "Testing ";
6660 auto halInstances =
6661 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6662 std::cout << "HAL instances:\n";
6663 for (auto& entry : halInstances) {
6664 std::cout << " " << entry << '\n';
6665 }
6666
Selene Huang31ab4042020-04-29 04:22:39 -07006667 ::testing::InitGoogleTest(&argc, argv);
6668 for (int i = 1; i < argc; ++i) {
6669 if (argv[i][0] == '-') {
6670 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006671 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6672 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006673 }
6674 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006675 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6676 dump_Attestations = true;
6677 } else {
6678 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006679 }
David Drysdalebb3d85e2021-04-13 11:15:51 +01006680 // TODO(drysdale): Remove this flag when available KeyMint devices comply with spec
6681 if (std::string(argv[i]) == "--check_patchLevels") {
6682 aidl::android::hardware::security::keymint::test::check_patchLevels = true;
6683 }
Selene Huang31ab4042020-04-29 04:22:39 -07006684 }
6685 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006686 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006687}