blob: 2c0c459a2a57dc3f91ee46acff60d1d9f2832b83 [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>
21#include <iostream>
22
David Zeuthene0c40892021-01-08 12:54:11 -050023#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070024#include <openssl/evp.h>
25#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050026#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070027
28#include <cutils/properties.h>
29
David Drysdale4dc01072021-04-01 12:17:35 +010030#include <android/binder_manager.h>
31
32#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080033#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070034
Shawn Willden08a7e432020-12-11 13:05:27 +000035#include <keymint_support/key_param_output.h>
36#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070037
38#include "KeyMintAidlTestBase.h"
39
Janis Danisevskis24c04702020-12-16 18:28:39 -080040using aidl::android::hardware::security::keymint::AuthorizationSet;
41using aidl::android::hardware::security::keymint::KeyCharacteristics;
42using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070043
Selene Huang31ab4042020-04-29 04:22:39 -070044namespace std {
45
Janis Danisevskis24c04702020-12-16 18:28:39 -080046using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070047
48template <>
49struct std::equal_to<KeyCharacteristics> {
50 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070051 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070052
Shawn Willden7f424372021-01-10 18:06:50 -070053 // this isn't very efficient. Oh, well.
54 AuthorizationSet a_auths(a.authorizations);
55 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070056
Shawn Willden7f424372021-01-10 18:06:50 -070057 a_auths.Sort();
58 b_auths.Sort();
59
60 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070061 }
62};
63
64} // namespace std
65
Janis Danisevskis24c04702020-12-16 18:28:39 -080066namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000067
Selene Huang31ab4042020-04-29 04:22:39 -070068namespace {
69
David Drysdalebb3d85e2021-04-13 11:15:51 +010070bool check_patchLevels = false;
71
Selene Huang31ab4042020-04-29 04:22:39 -070072template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000073bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
74 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070075 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080076 if (auto p = authorizationValue(ttag, param)) {
77 return *p == expected_value;
78 }
79 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070080 });
81 return (it != set.end());
82}
83
84template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000085bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070086 auto it = std::find_if(set.begin(), set.end(),
87 [&](const KeyParameter& param) { return param.tag == tag; });
88 return (it != set.end());
89}
90
91constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
92 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
93 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
94 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
95 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
96 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
97 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
98 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
99 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
103 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
104 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
107
108string hex2str(string a) {
109 string b;
110 size_t num = a.size() / 2;
111 b.resize(num);
112 for (size_t i = 0; i < num; i++) {
113 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
114 }
115 return b;
116}
117
David Drysdaled2cc8c22021-04-15 13:29:45 +0100118string rsa_key = hex2str(
119 // RFC 5208 s5
120 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
121 "020100" // INTEGER length 1 value 0x00 (version)
122 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
123 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
124 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
125 "0500" // NULL (parameters)
126 // } end SEQUENCE (AlgorithmIdentifier)
127 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
128 // RFC 8017 A.1.2
129 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
130 "020100" // INTEGER length 1 value 0x00 (version)
131 "028181" // INTEGER length 0x81 value (modulus) ...
132 "00c6095409047d8634812d5a218176e4"
133 "5c41d60a75b13901f234226cffe77652"
134 "1c5a77b9e389417b71c0b6a44d13afe4"
135 "e4a2805d46c9da2935adb1ff0c1f24ea"
136 "06e62b20d776430a4d435157233c6f91"
137 "6783c30e310fcbd89b85c2d567711697"
138 "85ac12bca244abda72bfb19fc44d27c8"
139 "1e1d92de284f4061edfd99280745ea6d"
140 "25"
141 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
142 "028180" // INTEGER length 0x80 (privateExponent) value...
143 "1be0f04d9cae3718691f035338308e91"
144 "564b55899ffb5084d2460e6630257e05"
145 "b3ceab02972dfabcd6ce5f6ee2589eb6"
146 "7911ed0fac16e43a444b8c861e544a05"
147 "93365772f8baf6b22fc9e3c5f1024b06"
148 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
149 "ace7240290bef16c0b3f7f3cdd64ce3a"
150 "b5912cf6e32f39ab188358afcccd8081"
151 "0241" // INTEGER length 0x41 (prime1)
152 "00e4b49ef50f765d3b24dde01aceaaf1"
153 "30f2c76670a91a61ae08af497b4a82be"
154 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
155 "8c92bfab137fba2285227b83c342ff7c"
156 "55"
157 "0241" // INTEGER length 0x41 (prime2)
158 "00ddabb5839c4c7f6bf3d4183231f005"
159 "b31aa58affdda5c79e4cce217f6bc930"
160 "dbe563d480706c24e9ebfcab28a6cdef"
161 "d324b77e1bf7251b709092c24ff501fd"
162 "91"
163 "0240" // INTEGER length 0x40 (exponent1)
164 "23d4340eda3445d8cd26c14411da6fdc"
165 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
166 "842c1d280405bc2f6c1bea214a1d742a"
167 "b996b35b63a82a5e470fa88dbf823cdd"
168 "0240" // INTEGER length 0x40 (exponent2)
169 "1b7b57449ad30d1518249a5f56bb9829"
170 "4d4b6ac12ffc86940497a5a5837a6cf9"
171 "46262b494526d328c11e1126380fde04"
172 "c24f916dec250892db09a6d77cdba351"
173 "0240" // INTEGER length 0x40 (coefficient)
174 "7762cd8f4d050da56bd591adb515d24d"
175 "7ccd32cca0d05f866d583514bd7324d5"
176 "f33645e8ed8b4a1cb3cc4a1d67987399"
177 "f2a09f5b3fb68c88d5e5d90ac33492d6"
178 // } end SEQUENCE (PrivateKey)
179 // } end SEQUENCE (PrivateKeyInfo)
180);
Selene Huang31ab4042020-04-29 04:22:39 -0700181
Selene Huange5727e62021-04-13 22:41:20 -0700182/*
183 * DER-encoded PKCS#8 format RSA key. Generated using:
184 *
185 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
186 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100187string rsa_2048_key = hex2str(
188 // RFC 5208 s5
189 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
190 "020100" // INTEGER length 1 value 0x00 (version)
191 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
192 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
193 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
194 "0500" // NULL (parameters)
195 // } end SEQUENCE (AlgorithmIdentifier)
196 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
197 // RFC 8017 A.1.2
198 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
199 "020100" // INTEGER length 1 value 0x00 (version)
200 "02820101" // INTEGER length 0x101 value (modulus) ...
201 "00BEBC342B56D443B1299F9A6A7056E8"
202 "0A897E318476A5A18029E63B2ED739A6"
203 "1791D339F58DC763D9D14911F2EDEC38"
204 "3DEE11F6319B44510E7A3ECD9B79B973"
205 "82E49500ACF8117DC89CAF0E621F7775"
206 "6554A2FD4664BFE7AB8B59AB48340DBF"
207 "A27B93B5A81F6ECDEB02D0759307128D"
208 "F3E3BAD4055C8B840216DFAA5700670E"
209 "6C5126F0962FCB70FF308F25049164CC"
210 "F76CC2DA66A7DD9A81A714C2809D6918"
211 "6133D29D84568E892B6FFBF3199BDB14"
212 "383EE224407F190358F111A949552ABA"
213 "6714227D1BD7F6B20DD0CB88F9467B71"
214 "9339F33BFF35B3870B3F62204E4286B0"
215 "948EA348B524544B5F9838F29EE643B0"
216 "79EEF8A713B220D7806924CDF7295070"
217 "C5"
218 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
219 "02820100" // INTEGER length 0x100 (privateExponent) value...
220 "69F377F35F2F584EF075353CCD1CA997"
221 "38DB3DBC7C7FF35F9366CE176DFD1B13"
222 "5AB10030344ABF5FBECF1D4659FDEF1C"
223 "0FC430834BE1BE3911951377BB3D563A"
224 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
225 "2686C7B4B3C09A7B8354133E6F93F790"
226 "D59EAEB92E84C9A4339302CCE28FDF04"
227 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
228 "6AB706645BF074A4E4090D06FB163124"
229 "365FD5EE7A20D350E9958CC30D91326E"
230 "1B292E9EF5DB408EC42DAF737D201497"
231 "04D0A678A0FB5B5446863B099228A352"
232 "D604BA8091A164D01D5AB05397C71EAD"
233 "20BE2A08FC528FE442817809C787FEE4"
234 "AB97F97B9130D022153EDC6EB6CBE7B0"
235 "F8E3473F2E901209B5DB10F93604DB01"
236 "028181" // INTEGER length 0x81 (prime1)
237 "00E83C0998214941EA4F9293F1B77E2E"
238 "99E6CF305FAF358238E126124FEAF2EB"
239 "9724B2EA7B78E6032343821A80E55D1D"
240 "88FB12D220C3F41A56142FEC85796D19"
241 "17F1E8C774F142B67D3D6E7B7E6B4383"
242 "E94DB5929089DBB346D5BDAB40CC2D96"
243 "EE0409475E175C63BF78CFD744136740"
244 "838127EA723FF3FE7FA368C1311B4A4E"
245 "05"
246 "028181" // INTEGER length 0x81 (prime2)
247 "00D240FCC0F5D7715CDE21CB2DC86EA1"
248 "46132EA3B06F61FF2AF54BF38473F59D"
249 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
250 "B1B58C39F95E4798CCBB43E83D0119AC"
251 "F532F359CA743C85199F0286610E2009"
252 "97D7312917179AC9B67558773212EC96"
253 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
254 "94D94E066A0900B7B70E82A44FB30053"
255 "C1"
256 "028181" // INTEGER length 0x81 (exponent1)
257 "00AD15DA1CBD6A492B66851BA8C316D3"
258 "8AB700E2CFDDD926A658003513C54BAA"
259 "152B30021D667D20078F500F8AD3E7F3"
260 "945D74A891ED1A28EAD0FEEAEC8C14A8"
261 "E834CF46A13D1378C99D18940823CFDD"
262 "27EC5810D59339E0C34198AC638E09C8"
263 "7CBB1B634A9864AE9F4D5EB2D53514F6"
264 "7B4CAEC048C8AB849A02E397618F3271"
265 "35"
266 "028180" // INTEGER length 0x80 (exponent2)
267 "1FA2C1A5331880A92D8F3E281C617108"
268 "BF38244F16E352E69ED417C7153F9EC3"
269 "18F211839C643DCF8B4DD67CE2AC312E"
270 "95178D5D952F06B1BF779F4916924B70"
271 "F582A23F11304E02A5E7565AE22A35E7"
272 "4FECC8B6FDC93F92A1A37703E4CF0E63"
273 "783BD02EB716A7ECBBFA606B10B74D01"
274 "579522E7EF84D91FC522292108D902C1"
275 "028180" // INTEGER length 0x80 (coefficient)
276 "796FE3825F9DCC85DF22D58690065D93"
277 "898ACD65C087BEA8DA3A63BF4549B795"
278 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
279 "0D74F40DED8E1102C52152A31B6165F8"
280 "3A6722AECFCC35A493D7634664B888A0"
281 "8D3EB034F12EA28BFEE346E205D33482"
282 "7F778B16ED40872BD29FCB36536B6E93"
283 "FFB06778696B4A9D81BB0A9423E63DE5"
284 // } end SEQUENCE (PrivateKey)
285 // } end SEQUENCE (PrivateKeyInfo)
286);
Selene Huange5727e62021-04-13 22:41:20 -0700287
David Drysdaled2cc8c22021-04-15 13:29:45 +0100288string ec_256_key = hex2str(
289 // RFC 5208 s5
290 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
291 "020100" // INTEGER length 1 value 0 (version)
292 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
293 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
294 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
295 "0608" // OBJECT IDENTIFIER length 8 (param)
296 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
297 // } end SEQUENCE (AlgorithmIdentifier)
298 "046d" // OCTET STRING length 0x6d (privateKey) holding...
299 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
300 "020101" // INTEGER length 1 value 1 (version)
301 "0420" // OCTET STRING length 0x20 (privateKey)
302 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
303 "941eed09366bc03299986481f3a4d859"
304 "a144" // TAG [1] len 0x44 (publicKey) {
305 "03420004bf85d7720d07c25461683bc6"
306 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
307 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
308 "bcc41c6eb00083cf3376d11fd44949e0"
309 "b2183bfe"
310 // } end SEQUENCE (ECPrivateKey)
311 // } end SEQUENCE (PrivateKeyInfo)
312);
Selene Huang31ab4042020-04-29 04:22:39 -0700313
David Drysdaled2cc8c22021-04-15 13:29:45 +0100314string ec_521_key = hex2str(
315 // RFC 5208 s5
316 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
317 "020100" // INTEGER length 1 value 0 (version)
318 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
319 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
320 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
321 "0605" // OBJECT IDENTIFIER length 5 (param)
322 "2B81040023" // 1.3.132.0.35 (secp521r1)
323 // } end SEQUENCE (AlgorithmIdentifier)
324 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
325 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
326 "020101" // INTEGER length 1 value 1 (version)
327 "0442" // OCTET STRING length 0x42 (privateKey)
328 "0011458C586DB5DAA92AFAB03F4FE46A"
329 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
330 "9D18D7D08B5BCFA0E53C75B064AD51C4"
331 "49BAE0258D54B94B1E885DED08ED4FB2"
332 "5CE9"
333 "A18189" // TAG [1] len 0x89 (publicKey) {
334 "03818600040149EC11C6DF0FA122C6A9"
335 "AFD9754A4FA9513A627CA329E349535A"
336 "5629875A8ADFBE27DCB932C051986377"
337 "108D054C28C6F39B6F2C9AF81802F9F3"
338 "26B842FF2E5F3C00AB7635CFB36157FC"
339 "0882D574A10D839C1A0C049DC5E0D775"
340 "E2EE50671A208431BB45E78E70BEFE93"
341 "0DB34818EE4D5C26259F5C6B8E28A652"
342 "950F9F88D7B4B2C9D9"
343 // } end SEQUENCE (ECPrivateKey)
344 // } end SEQUENCE (PrivateKeyInfo)
345);
Selene Huang31ab4042020-04-29 04:22:39 -0700346
David Drysdaled2cc8c22021-04-15 13:29:45 +0100347string ec_256_key_rfc5915 = hex2str(
348 // RFC 5208 s5
349 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
350 "020100" // INTEGER length 1 value 0 (version)
351 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
352 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
353 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
354 "0608" // OBJECT IDENTIFIER length 8 (param)
355 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
356 // } end SEQUENCE (AlgorithmIdentifier)
357 "0479" // OCTET STRING length 0x79 (privateKey) holding...
358 // RFC 5915 s3
359 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
360 "020101" // INTEGER length 1 value 1 (version)
361 "0420" // OCTET STRING length 0x42 (privateKey)
362 "782370a8c8ce5537baadd04dcff079c8"
363 "158cfa9c67b818b38e8d21c9fa750c1d"
364 "a00a" // TAG [0] length 0xa (parameters)
365 "0608" // OBJECT IDENTIFIER length 8
366 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
367 // } end TAG [0]
368 "a144" // TAG [1] length 0x44 (publicKey) {
369 "0342" // BIT STRING length 0x42
370 "00" // no pad bits
371 "04e2cc561ee701da0ad0ef0d176bb0c9"
372 "19d42e79c393fdc1bd6c4010d85cf2cf"
373 "8e68c905464666f98dad4f01573ba810"
374 "78b3428570a439ba3229fbc026c55068"
375 "2f"
376 // } end SEQUENCE (ECPrivateKey)
377 // } end SEQUENCE (PrivateKeyInfo)
378);
Selene Huang31ab4042020-04-29 04:22:39 -0700379
David Drysdaled2cc8c22021-04-15 13:29:45 +0100380string ec_256_key_sec1 = hex2str(
381 // RFC 5208 s5
382 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
383 "020100" // INTEGER length 1 value 0 (version)
384 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
385 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
386 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
387 "0608" // OBJECT IDENTIFIER length 8 (param)
388 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
389 // } end SEQUENCE (AlgorithmIdentifier)
390 "046d" // OCTET STRING length 0x6d (privateKey) holding...
391 // SEC1-v2 C.4
392 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
393 "020101" // INTEGER length 1 value 0x01 (version)
394 "0420" // OCTET STRING length 0x20 (privateKey)
395 "782370a8c8ce5537baadd04dcff079c8"
396 "158cfa9c67b818b38e8d21c9fa750c1d"
397 "a144" // TAG [1] length 0x44 (publicKey) {
398 "0342" // BIT STRING length 0x42
399 "00" // no pad bits
400 "04e2cc561ee701da0ad0ef0d176bb0c9"
401 "19d42e79c393fdc1bd6c4010d85cf2cf"
402 "8e68c905464666f98dad4f01573ba810"
403 "78b3428570a439ba3229fbc026c55068"
404 "2f"
405 // } end TAG [1] (publicKey)
406 // } end SEQUENCE (PrivateKeyInfo)
407);
Selene Huang31ab4042020-04-29 04:22:39 -0700408
409struct RSA_Delete {
410 void operator()(RSA* p) { RSA_free(p); }
411};
412
Selene Huang31ab4042020-04-29 04:22:39 -0700413std::string make_string(const uint8_t* data, size_t length) {
414 return std::string(reinterpret_cast<const char*>(data), length);
415}
416
417template <size_t N>
418std::string make_string(const uint8_t (&a)[N]) {
419 return make_string(a, N);
420}
421
422class AidlBuf : public vector<uint8_t> {
423 typedef vector<uint8_t> super;
424
425 public:
426 AidlBuf() {}
427 AidlBuf(const super& other) : super(other) {}
428 AidlBuf(super&& other) : super(std::move(other)) {}
429 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
430
431 AidlBuf& operator=(const super& other) {
432 super::operator=(other);
433 return *this;
434 }
435
436 AidlBuf& operator=(super&& other) {
437 super::operator=(std::move(other));
438 return *this;
439 }
440
441 AidlBuf& operator=(const string& other) {
442 resize(other.size());
443 for (size_t i = 0; i < other.size(); ++i) {
444 (*this)[i] = static_cast<uint8_t>(other[i]);
445 }
446 return *this;
447 }
448
449 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
450};
451
David Drysdale4dc01072021-04-01 12:17:35 +0100452string device_suffix(const string& name) {
453 size_t pos = name.find('/');
454 if (pos == string::npos) {
455 return name;
456 }
457 return name.substr(pos + 1);
458}
459
460bool matching_rp_instance(const string& km_name,
461 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
462 string km_suffix = device_suffix(km_name);
463
464 vector<string> rp_names =
465 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
466 for (const string& rp_name : rp_names) {
467 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
468 // KeyMint instance, assume they match.
469 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
470 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
471 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
472 return true;
473 }
474 }
475 return false;
476}
477
Selene Huang31ab4042020-04-29 04:22:39 -0700478} // namespace
479
480class NewKeyGenerationTest : public KeyMintAidlTestBase {
481 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700482 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000483 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700484 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700485
Selene Huang31ab4042020-04-29 04:22:39 -0700486 // Check that some unexpected tags/values are NOT present.
487 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
488 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000489 }
490
491 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
492 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
493 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
494 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
495
496 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000497 }
498
499 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
500 // TODO(swillden): Distinguish which params should be in which auth list.
501 AuthorizationSet auths;
502 for (auto& entry : keyCharacteristics) {
503 auths.push_back(AuthorizationSet(entry.authorizations));
504 }
505 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
506
507 // Verify that App data, ROT and auth timeout are NOT included.
508 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
509 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700510 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
511
David Drysdaled2cc8c22021-04-15 13:29:45 +0100512 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
513 // never adds it.
514 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
515
David Drysdale7de9feb2021-03-05 14:56:19 +0000516 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700517 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000518 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700519 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700520 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000521 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700522 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000523
David Drysdalebb3d85e2021-04-13 11:15:51 +0100524 if (check_patchLevels) {
525 // Should include vendor and boot patchlevels.
526 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
527 EXPECT_TRUE(vendor_pl);
528 EXPECT_EQ(*vendor_pl, vendor_patch_level());
529 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
530 EXPECT_TRUE(boot_pl);
531 }
532
David Drysdale7de9feb2021-03-05 14:56:19 +0000533 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700534 }
535};
536
537/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000538 * NewKeyGenerationTest.Aes
539 *
540 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
541 * have correct characteristics.
542 */
543TEST_P(NewKeyGenerationTest, Aes) {
544 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
545 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
546 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
547 SCOPED_TRACE(testing::Message()
548 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
549 vector<uint8_t> key_blob;
550 vector<KeyCharacteristics> key_characteristics;
551 auto builder = AuthorizationSetBuilder()
552 .AesEncryptionKey(key_size)
553 .BlockMode(block_mode)
554 .Padding(padding_mode)
555 .SetDefaultValidity();
556 if (block_mode == BlockMode::GCM) {
557 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
558 }
559 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
560
561 EXPECT_GT(key_blob.size(), 0U);
562 CheckSymmetricParams(key_characteristics);
563
564 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
565
566 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
567 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
568 << "Key size " << key_size << "missing";
569
570 CheckedDeleteKey(&key_blob);
571 }
572 }
573 }
574}
575
576/*
577 * NewKeyGenerationTest.AesInvalidSize
578 *
579 * Verifies that specifying an invalid key size for AES key generation returns
580 * UNSUPPORTED_KEY_SIZE.
581 */
582TEST_P(NewKeyGenerationTest, AesInvalidSize) {
583 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
584 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
585 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
586 SCOPED_TRACE(testing::Message()
587 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
588 vector<uint8_t> key_blob;
589 vector<KeyCharacteristics> key_characteristics;
590 auto builder = AuthorizationSetBuilder()
591 .AesEncryptionKey(key_size)
592 .BlockMode(block_mode)
593 .Padding(padding_mode)
594 .SetDefaultValidity();
595 if (block_mode == BlockMode::GCM) {
596 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
597 }
598 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
599 GenerateKey(builder, &key_blob, &key_characteristics));
600 }
601 }
602 }
603
604 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
605 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
606 vector<uint8_t> key_blob;
607 vector<KeyCharacteristics> key_characteristics;
608 // No key size specified
609 auto builder = AuthorizationSetBuilder()
610 .Authorization(TAG_ALGORITHM, Algorithm::AES)
611 .BlockMode(block_mode)
612 .Padding(padding_mode)
613 .SetDefaultValidity();
614 if (block_mode == BlockMode::GCM) {
615 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
616 }
617 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
618 GenerateKey(builder, &key_blob, &key_characteristics));
619 }
620 }
621}
622
623/*
624 * NewKeyGenerationTest.AesInvalidPadding
625 *
626 * Verifies that specifying an invalid padding on AES keys gives a failure
627 * somewhere along the way.
628 */
629TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
630 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
631 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
632 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
633 SCOPED_TRACE(testing::Message()
634 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000635 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800636 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000637 .AesEncryptionKey(key_size)
638 .BlockMode(block_mode)
639 .Padding(padding_mode)
640 .SetDefaultValidity();
641 if (block_mode == BlockMode::GCM) {
642 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
643 }
644
Tommy Chiu3950b452021-05-03 22:01:46 +0800645 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000646 if (result == ErrorCode::OK) {
647 // Key creation was OK but has generated a key that cannot be used.
648 auto params =
649 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800650 if (block_mode == BlockMode::GCM) {
651 params.Authorization(TAG_MAC_LENGTH, 128);
652 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000653 auto result = Begin(KeyPurpose::ENCRYPT, params);
654 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100655 result == ErrorCode::INVALID_KEY_BLOB)
656 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000657 } else {
658 // The KeyMint implementation detected that the generated key
659 // is unusable.
660 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
661 }
662 }
663 }
664 }
665}
666
667/*
668 * NewKeyGenerationTest.AesGcmMissingMinMac
669 *
670 * Verifies that specifying an invalid key size for AES key generation returns
671 * UNSUPPORTED_KEY_SIZE.
672 */
673TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
674 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
675 BlockMode block_mode = BlockMode::GCM;
676 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
677 SCOPED_TRACE(testing::Message()
678 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
679 vector<uint8_t> key_blob;
680 vector<KeyCharacteristics> key_characteristics;
681 // No MIN_MAC_LENGTH provided.
682 auto builder = AuthorizationSetBuilder()
683 .AesEncryptionKey(key_size)
684 .BlockMode(block_mode)
685 .Padding(padding_mode)
686 .SetDefaultValidity();
687 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
688 GenerateKey(builder, &key_blob, &key_characteristics));
689 }
690 }
691}
692
693/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100694 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
695 *
696 * Verifies that specifying an invalid min MAC size for AES key generation returns
697 * UNSUPPORTED_MIN_MAC_LENGTH.
698 */
699TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
700 for (size_t min_mac_len : {88, 136}) {
701 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
702 BlockMode block_mode = BlockMode::GCM;
703 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
704 SCOPED_TRACE(testing::Message()
705 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
706 vector<uint8_t> key_blob;
707 vector<KeyCharacteristics> key_characteristics;
708 auto builder = AuthorizationSetBuilder()
709 .AesEncryptionKey(key_size)
710 .BlockMode(block_mode)
711 .Padding(padding_mode)
712 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
713 .SetDefaultValidity();
714 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
715 GenerateKey(builder, &key_blob, &key_characteristics));
716 }
717 }
718 }
719}
720
721/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000722 * NewKeyGenerationTest.TripleDes
723 *
724 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
725 * have correct characteristics.
726 */
727TEST_P(NewKeyGenerationTest, TripleDes) {
728 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
729 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
730 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
731 SCOPED_TRACE(testing::Message()
732 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
733 vector<uint8_t> key_blob;
734 vector<KeyCharacteristics> key_characteristics;
735 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
736 .TripleDesEncryptionKey(key_size)
737 .BlockMode(block_mode)
738 .Padding(padding_mode)
739 .Authorization(TAG_NO_AUTH_REQUIRED)
740 .SetDefaultValidity(),
741 &key_blob, &key_characteristics));
742
743 EXPECT_GT(key_blob.size(), 0U);
744 CheckSymmetricParams(key_characteristics);
745
746 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
747
748 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
749 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
750 << "Key size " << key_size << "missing";
751
752 CheckedDeleteKey(&key_blob);
753 }
754 }
755 }
756}
757
758/*
759 * NewKeyGenerationTest.TripleDesWithAttestation
760 *
761 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
762 * have correct characteristics.
763 *
764 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
765 * put in a certificate) but which isn't an error.
766 */
767TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
768 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
769 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
770 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
771 SCOPED_TRACE(testing::Message()
772 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
773
774 auto challenge = "hello";
775 auto app_id = "foo";
776
777 vector<uint8_t> key_blob;
778 vector<KeyCharacteristics> key_characteristics;
779 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
780 .TripleDesEncryptionKey(key_size)
781 .BlockMode(block_mode)
782 .Padding(padding_mode)
783 .Authorization(TAG_NO_AUTH_REQUIRED)
784 .AttestationChallenge(challenge)
785 .AttestationApplicationId(app_id)
786 .SetDefaultValidity(),
787 &key_blob, &key_characteristics));
788
789 EXPECT_GT(key_blob.size(), 0U);
790 CheckSymmetricParams(key_characteristics);
791
792 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
793
794 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
795 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
796 << "Key size " << key_size << "missing";
797
798 CheckedDeleteKey(&key_blob);
799 }
800 }
801 }
802}
803
804/*
805 * NewKeyGenerationTest.TripleDesInvalidSize
806 *
807 * Verifies that specifying an invalid key size for 3-DES key generation returns
808 * UNSUPPORTED_KEY_SIZE.
809 */
810TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
811 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
812 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
813 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
814 SCOPED_TRACE(testing::Message()
815 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
816 vector<uint8_t> key_blob;
817 vector<KeyCharacteristics> key_characteristics;
818 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
819 GenerateKey(AuthorizationSetBuilder()
820 .TripleDesEncryptionKey(key_size)
821 .BlockMode(block_mode)
822 .Padding(padding_mode)
823 .Authorization(TAG_NO_AUTH_REQUIRED)
824 .SetDefaultValidity(),
825 &key_blob, &key_characteristics));
826 }
827 }
828 }
829
830 // Omitting the key size fails.
831 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
832 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
833 SCOPED_TRACE(testing::Message()
834 << "3DES-default-" << block_mode << "-" << padding_mode);
835 vector<uint8_t> key_blob;
836 vector<KeyCharacteristics> key_characteristics;
837 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
838 GenerateKey(AuthorizationSetBuilder()
839 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
840 .BlockMode(block_mode)
841 .Padding(padding_mode)
842 .Authorization(TAG_NO_AUTH_REQUIRED)
843 .SetDefaultValidity(),
844 &key_blob, &key_characteristics));
845 }
846 }
847}
848
849/*
Selene Huang31ab4042020-04-29 04:22:39 -0700850 * NewKeyGenerationTest.Rsa
851 *
852 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
853 * have correct characteristics.
854 */
855TEST_P(NewKeyGenerationTest, Rsa) {
856 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
857 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700858 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700859 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
860 .RsaSigningKey(key_size, 65537)
861 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800862 .Padding(PaddingMode::NONE)
863 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700864 &key_blob, &key_characteristics));
865
866 ASSERT_GT(key_blob.size(), 0U);
867 CheckBaseParams(key_characteristics);
868
Shawn Willden7f424372021-01-10 18:06:50 -0700869 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700870
871 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
872 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
873 << "Key size " << key_size << "missing";
874 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
875
876 CheckedDeleteKey(&key_blob);
877 }
878}
879
880/*
Qi Wud22ec842020-11-26 13:27:53 +0800881 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700882 *
David Drysdaled2cc8c22021-04-15 13:29:45 +0100883 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
884 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700885 */
886TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700887 auto challenge = "hello";
888 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700889
Selene Huang6e46f142021-04-20 19:20:11 -0700890 auto subject = "cert subj 2";
891 vector<uint8_t> subject_der(make_name_from_str(subject));
892
893 uint64_t serial_int = 66;
894 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
895
Selene Huang4f64c222021-04-13 19:54:36 -0700896 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700897 vector<uint8_t> key_blob;
898 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700899 ASSERT_EQ(ErrorCode::OK,
900 GenerateKey(AuthorizationSetBuilder()
901 .RsaSigningKey(key_size, 65537)
902 .Digest(Digest::NONE)
903 .Padding(PaddingMode::NONE)
904 .AttestationChallenge(challenge)
905 .AttestationApplicationId(app_id)
906 .Authorization(TAG_NO_AUTH_REQUIRED)
907 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
908 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
909 .SetDefaultValidity(),
910 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700911
912 ASSERT_GT(key_blob.size(), 0U);
913 CheckBaseParams(key_characteristics);
914
915 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
916
917 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
918 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
919 << "Key size " << key_size << "missing";
920 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
921
Selene Huang6e46f142021-04-20 19:20:11 -0700922 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700923 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700924 ASSERT_GT(cert_chain_.size(), 0);
925
926 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
927 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
928 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
929 sw_enforced, hw_enforced, SecLevel(),
930 cert_chain_[0].encodedCertificate));
931
932 CheckedDeleteKey(&key_blob);
933 }
934}
935
936/*
David Drysdale4dc01072021-04-01 12:17:35 +0100937 * NewKeyGenerationTest.RsaWithRpkAttestation
938 *
939 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
940 * that has been generated using an associate IRemotelyProvisionedComponent.
941 */
942TEST_P(NewKeyGenerationTest, RsaWithRpkAttestation) {
943 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
944 // instance.
945 std::shared_ptr<IRemotelyProvisionedComponent> rp;
946 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
947 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
948
949 // Generate a P-256 keypair to use as an attestation key.
950 MacedPublicKey macedPubKey;
951 std::vector<uint8_t> privateKeyBlob;
952 auto status =
953 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
954 ASSERT_TRUE(status.isOk());
955 vector<uint8_t> coseKeyData;
956 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
957
958 AttestationKey attestation_key;
959 attestation_key.keyBlob = std::move(privateKeyBlob);
960 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
961
962 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
963 auto challenge = "hello";
964 auto app_id = "foo";
965
966 vector<uint8_t> key_blob;
967 vector<KeyCharacteristics> key_characteristics;
968 ASSERT_EQ(ErrorCode::OK,
969 GenerateKey(AuthorizationSetBuilder()
970 .RsaSigningKey(key_size, 65537)
971 .Digest(Digest::NONE)
972 .Padding(PaddingMode::NONE)
973 .AttestationChallenge(challenge)
974 .AttestationApplicationId(app_id)
975 .Authorization(TAG_NO_AUTH_REQUIRED)
976 .SetDefaultValidity(),
977 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
978
979 ASSERT_GT(key_blob.size(), 0U);
980 CheckBaseParams(key_characteristics);
981
982 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
983
984 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
985 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
986 << "Key size " << key_size << "missing";
987 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
988
989 // Attestation by itself is not valid (last entry is not self-signed).
990 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
991
992 // The signature over the attested key should correspond to the P256 public key.
993 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
994 ASSERT_TRUE(key_cert.get());
995 EVP_PKEY_Ptr signing_pubkey;
996 p256_pub_key(coseKeyData, &signing_pubkey);
997 ASSERT_TRUE(signing_pubkey.get());
998
999 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1000 << "Verification of attested certificate failed "
1001 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1002
1003 CheckedDeleteKey(&key_blob);
1004 }
1005}
1006
1007/*
Selene Huang4f64c222021-04-13 19:54:36 -07001008 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1009 *
1010 * Verifies that keymint attestation for RSA encryption keys with challenge and
1011 * app id is also successful.
1012 */
1013TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1014 auto key_size = 2048;
1015 auto challenge = "hello";
1016 auto app_id = "foo";
1017
Selene Huang6e46f142021-04-20 19:20:11 -07001018 auto subject = "subj 2";
1019 vector<uint8_t> subject_der(make_name_from_str(subject));
1020
1021 uint64_t serial_int = 111166;
1022 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1023
Selene Huang4f64c222021-04-13 19:54:36 -07001024 vector<uint8_t> key_blob;
1025 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001026 ASSERT_EQ(ErrorCode::OK,
1027 GenerateKey(AuthorizationSetBuilder()
1028 .RsaEncryptionKey(key_size, 65537)
1029 .Padding(PaddingMode::NONE)
1030 .AttestationChallenge(challenge)
1031 .AttestationApplicationId(app_id)
1032 .Authorization(TAG_NO_AUTH_REQUIRED)
1033 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1034 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1035 .SetDefaultValidity(),
1036 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001037
1038 ASSERT_GT(key_blob.size(), 0U);
1039 AuthorizationSet auths;
1040 for (auto& entry : key_characteristics) {
1041 auths.push_back(AuthorizationSet(entry.authorizations));
1042 }
1043
1044 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1045 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1046
1047 // Verify that App data and ROT are NOT included.
1048 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1049 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1050
1051 // Check that some unexpected tags/values are NOT present.
1052 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1053 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1054
1055 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1056
1057 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1058 ASSERT_TRUE(os_ver);
1059 EXPECT_EQ(*os_ver, os_version());
1060
1061 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1062
1063 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1064 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1065 << "Key size " << key_size << "missing";
1066 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1067
Selene Huang6e46f142021-04-20 19:20:11 -07001068 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001069 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1070 ASSERT_GT(cert_chain_.size(), 0);
1071
1072 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1073 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1074 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1075 sw_enforced, hw_enforced, SecLevel(),
1076 cert_chain_[0].encodedCertificate));
1077
1078 CheckedDeleteKey(&key_blob);
1079}
1080
1081/*
1082 * NewKeyGenerationTest.RsaWithSelfSign
1083 *
1084 * Verifies that attesting to RSA key generation is successful, and returns
1085 * self signed certificate if no challenge is provided. And signing etc
1086 * works as expected.
1087 */
1088TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001089 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1090 vector<uint8_t> subject_der(make_name_from_str(subject));
1091
1092 uint64_t serial_int = 0;
1093 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1094
Selene Huang4f64c222021-04-13 19:54:36 -07001095 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1096 vector<uint8_t> key_blob;
1097 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001098 ASSERT_EQ(ErrorCode::OK,
1099 GenerateKey(AuthorizationSetBuilder()
1100 .RsaSigningKey(key_size, 65537)
1101 .Digest(Digest::NONE)
1102 .Padding(PaddingMode::NONE)
1103 .Authorization(TAG_NO_AUTH_REQUIRED)
1104 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1105 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1106 .SetDefaultValidity(),
1107 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001108
1109 ASSERT_GT(key_blob.size(), 0U);
1110 CheckBaseParams(key_characteristics);
1111
1112 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1113
1114 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1115 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1116 << "Key size " << key_size << "missing";
1117 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1118
Selene Huang6e46f142021-04-20 19:20:11 -07001119 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001120 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1121 ASSERT_EQ(cert_chain_.size(), 1);
1122
1123 CheckedDeleteKey(&key_blob);
1124 }
1125}
1126
1127/*
1128 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1129 *
1130 * Verifies that attesting to RSA checks for missing app ID.
1131 */
1132TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1133 auto challenge = "hello";
1134 vector<uint8_t> key_blob;
1135 vector<KeyCharacteristics> key_characteristics;
1136
1137 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1138 GenerateKey(AuthorizationSetBuilder()
1139 .RsaSigningKey(2048, 65537)
1140 .Digest(Digest::NONE)
1141 .Padding(PaddingMode::NONE)
1142 .AttestationChallenge(challenge)
1143 .Authorization(TAG_NO_AUTH_REQUIRED)
1144 .SetDefaultValidity(),
1145 &key_blob, &key_characteristics));
1146}
1147
1148/*
1149 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1150 *
1151 * Verifies that attesting to RSA ignores app id if challenge is missing.
1152 */
1153TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1154 auto key_size = 2048;
1155 auto app_id = "foo";
1156
Selene Huang6e46f142021-04-20 19:20:11 -07001157 auto subject = "cert subj 2";
1158 vector<uint8_t> subject_der(make_name_from_str(subject));
1159
1160 uint64_t serial_int = 1;
1161 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1162
Selene Huang4f64c222021-04-13 19:54:36 -07001163 vector<uint8_t> key_blob;
1164 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001165 ASSERT_EQ(ErrorCode::OK,
1166 GenerateKey(AuthorizationSetBuilder()
1167 .RsaSigningKey(key_size, 65537)
1168 .Digest(Digest::NONE)
1169 .Padding(PaddingMode::NONE)
1170 .AttestationApplicationId(app_id)
1171 .Authorization(TAG_NO_AUTH_REQUIRED)
1172 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1173 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1174 .SetDefaultValidity(),
1175 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001176
1177 ASSERT_GT(key_blob.size(), 0U);
1178 CheckBaseParams(key_characteristics);
1179
1180 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1181
1182 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1183 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1184 << "Key size " << key_size << "missing";
1185 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1186
Selene Huang6e46f142021-04-20 19:20:11 -07001187 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001188 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1189 ASSERT_EQ(cert_chain_.size(), 1);
1190
1191 CheckedDeleteKey(&key_blob);
1192}
1193
1194/*
Qi Wud22ec842020-11-26 13:27:53 +08001195 * NewKeyGenerationTest.LimitedUsageRsa
1196 *
1197 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1198 * resulting keys have correct characteristics.
1199 */
1200TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1201 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1202 vector<uint8_t> key_blob;
1203 vector<KeyCharacteristics> key_characteristics;
1204 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1205 .RsaSigningKey(key_size, 65537)
1206 .Digest(Digest::NONE)
1207 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001208 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1209 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001210 &key_blob, &key_characteristics));
1211
1212 ASSERT_GT(key_blob.size(), 0U);
1213 CheckBaseParams(key_characteristics);
1214
1215 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1216
1217 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1218 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1219 << "Key size " << key_size << "missing";
1220 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1221
1222 // Check the usage count limit tag appears in the authorizations.
1223 AuthorizationSet auths;
1224 for (auto& entry : key_characteristics) {
1225 auths.push_back(AuthorizationSet(entry.authorizations));
1226 }
1227 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1228 << "key usage count limit " << 1U << " missing";
1229
1230 CheckedDeleteKey(&key_blob);
1231 }
1232}
1233
1234/*
Qi Wubeefae42021-01-28 23:16:37 +08001235 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1236 *
1237 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1238 * resulting keys have correct characteristics and attestation.
1239 */
1240TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001241 auto challenge = "hello";
1242 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001243
Selene Huang6e46f142021-04-20 19:20:11 -07001244 auto subject = "cert subj 2";
1245 vector<uint8_t> subject_der(make_name_from_str(subject));
1246
1247 uint64_t serial_int = 66;
1248 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1249
Selene Huang4f64c222021-04-13 19:54:36 -07001250 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001251 vector<uint8_t> key_blob;
1252 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001253 ASSERT_EQ(ErrorCode::OK,
1254 GenerateKey(AuthorizationSetBuilder()
1255 .RsaSigningKey(key_size, 65537)
1256 .Digest(Digest::NONE)
1257 .Padding(PaddingMode::NONE)
1258 .AttestationChallenge(challenge)
1259 .AttestationApplicationId(app_id)
1260 .Authorization(TAG_NO_AUTH_REQUIRED)
1261 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1262 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1263 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1264 .SetDefaultValidity(),
1265 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001266
1267 ASSERT_GT(key_blob.size(), 0U);
1268 CheckBaseParams(key_characteristics);
1269
1270 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1271
1272 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1273 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1274 << "Key size " << key_size << "missing";
1275 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1276
1277 // Check the usage count limit tag appears in the authorizations.
1278 AuthorizationSet auths;
1279 for (auto& entry : key_characteristics) {
1280 auths.push_back(AuthorizationSet(entry.authorizations));
1281 }
1282 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1283 << "key usage count limit " << 1U << " missing";
1284
1285 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001286 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001287 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001288 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001289
1290 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1291 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1292 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1293 sw_enforced, hw_enforced, SecLevel(),
1294 cert_chain_[0].encodedCertificate));
1295
1296 CheckedDeleteKey(&key_blob);
1297 }
1298}
1299
1300/*
Selene Huang31ab4042020-04-29 04:22:39 -07001301 * NewKeyGenerationTest.NoInvalidRsaSizes
1302 *
1303 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1304 */
1305TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1306 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1307 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001308 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001309 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1310 GenerateKey(AuthorizationSetBuilder()
1311 .RsaSigningKey(key_size, 65537)
1312 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001313 .Padding(PaddingMode::NONE)
1314 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001315 &key_blob, &key_characteristics));
1316 }
1317}
1318
1319/*
1320 * NewKeyGenerationTest.RsaNoDefaultSize
1321 *
1322 * Verifies that failing to specify a key size for RSA key generation returns
1323 * UNSUPPORTED_KEY_SIZE.
1324 */
1325TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1326 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1327 GenerateKey(AuthorizationSetBuilder()
1328 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1329 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001330 .SigningKey()
1331 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001332}
1333
1334/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001335 * NewKeyGenerationTest.RsaMissingParams
1336 *
1337 * Verifies that omitting optional tags works.
1338 */
1339TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1340 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1341 ASSERT_EQ(ErrorCode::OK,
1342 GenerateKey(
1343 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1344 CheckedDeleteKey();
1345 }
1346}
1347
1348/*
Selene Huang31ab4042020-04-29 04:22:39 -07001349 * NewKeyGenerationTest.Ecdsa
1350 *
1351 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1352 * have correct characteristics.
1353 */
1354TEST_P(NewKeyGenerationTest, Ecdsa) {
1355 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1356 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001357 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001358 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1359 .EcdsaSigningKey(key_size)
1360 .Digest(Digest::NONE)
1361 .SetDefaultValidity(),
1362 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001363 ASSERT_GT(key_blob.size(), 0U);
1364 CheckBaseParams(key_characteristics);
1365
Shawn Willden7f424372021-01-10 18:06:50 -07001366 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001367
1368 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1369 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1370 << "Key size " << key_size << "missing";
1371
1372 CheckedDeleteKey(&key_blob);
1373 }
1374}
1375
1376/*
Selene Huang4f64c222021-04-13 19:54:36 -07001377 * NewKeyGenerationTest.EcdsaAttestation
1378 *
1379 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1380 * an attestation will be generated.
1381 */
1382TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1383 auto challenge = "hello";
1384 auto app_id = "foo";
1385
Selene Huang6e46f142021-04-20 19:20:11 -07001386 auto subject = "cert subj 2";
1387 vector<uint8_t> subject_der(make_name_from_str(subject));
1388
1389 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1390 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1391
Selene Huang4f64c222021-04-13 19:54:36 -07001392 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1393 vector<uint8_t> key_blob;
1394 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001395 ASSERT_EQ(ErrorCode::OK,
1396 GenerateKey(AuthorizationSetBuilder()
1397 .Authorization(TAG_NO_AUTH_REQUIRED)
1398 .EcdsaSigningKey(key_size)
1399 .Digest(Digest::NONE)
1400 .AttestationChallenge(challenge)
1401 .AttestationApplicationId(app_id)
1402 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1403 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1404 .SetDefaultValidity(),
1405 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001406 ASSERT_GT(key_blob.size(), 0U);
1407 CheckBaseParams(key_characteristics);
1408
1409 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1410
1411 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1412 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1413 << "Key size " << key_size << "missing";
1414
1415 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1416 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001417 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001418
1419 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1420 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1421 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1422 sw_enforced, hw_enforced, SecLevel(),
1423 cert_chain_[0].encodedCertificate));
1424
1425 CheckedDeleteKey(&key_blob);
1426 }
1427}
1428
1429/*
1430 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1431 *
1432 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1433 * the key will generate a self signed attestation.
1434 */
1435TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001436 auto subject = "cert subj 2";
1437 vector<uint8_t> subject_der(make_name_from_str(subject));
1438
1439 uint64_t serial_int = 0x123456FFF1234;
1440 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1441
Selene Huang4f64c222021-04-13 19:54:36 -07001442 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1443 vector<uint8_t> key_blob;
1444 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001445 ASSERT_EQ(ErrorCode::OK,
1446 GenerateKey(AuthorizationSetBuilder()
1447 .EcdsaSigningKey(key_size)
1448 .Digest(Digest::NONE)
1449 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1450 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1451 .SetDefaultValidity(),
1452 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001453 ASSERT_GT(key_blob.size(), 0U);
1454 CheckBaseParams(key_characteristics);
1455
1456 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1457
1458 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1459 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1460 << "Key size " << key_size << "missing";
1461
1462 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001463 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001464 ASSERT_EQ(cert_chain_.size(), 1);
1465
1466 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1467 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1468
1469 CheckedDeleteKey(&key_blob);
1470 }
1471}
1472
1473/*
1474 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1475 *
1476 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1477 * app id must also be provided or else it will fail.
1478 */
1479TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1480 auto challenge = "hello";
1481 vector<uint8_t> key_blob;
1482 vector<KeyCharacteristics> key_characteristics;
1483
1484 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1485 GenerateKey(AuthorizationSetBuilder()
1486 .EcdsaSigningKey(EcCurve::P_256)
1487 .Digest(Digest::NONE)
1488 .AttestationChallenge(challenge)
1489 .SetDefaultValidity(),
1490 &key_blob, &key_characteristics));
1491}
1492
1493/*
1494 * NewKeyGenerationTest.EcdsaIgnoreAppId
1495 *
1496 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1497 * any appid will be ignored, and keymint will generate a self sign certificate.
1498 */
1499TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1500 auto app_id = "foo";
1501
1502 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1503 vector<uint8_t> key_blob;
1504 vector<KeyCharacteristics> key_characteristics;
1505 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1506 .EcdsaSigningKey(key_size)
1507 .Digest(Digest::NONE)
1508 .AttestationApplicationId(app_id)
1509 .SetDefaultValidity(),
1510 &key_blob, &key_characteristics));
1511
1512 ASSERT_GT(key_blob.size(), 0U);
1513 CheckBaseParams(key_characteristics);
1514
1515 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1516
1517 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1518 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1519 << "Key size " << key_size << "missing";
1520
1521 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1522 ASSERT_EQ(cert_chain_.size(), 1);
1523
1524 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1525 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1526
1527 CheckedDeleteKey(&key_blob);
1528 }
1529}
1530
1531/*
1532 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1533 *
1534 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1535 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1536 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1537 * to specify how many following bytes will be used to encode the length.
1538 */
1539TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1540 auto challenge = "hello";
1541 auto key_size = 256;
1542 std::vector<uint32_t> app_id_lengths{143, 258};
1543
1544 for (uint32_t length : app_id_lengths) {
1545 const string app_id(length, 'a');
1546 vector<uint8_t> key_blob;
1547 vector<KeyCharacteristics> key_characteristics;
1548 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1549 .Authorization(TAG_NO_AUTH_REQUIRED)
1550 .EcdsaSigningKey(key_size)
1551 .Digest(Digest::NONE)
1552 .AttestationChallenge(challenge)
1553 .AttestationApplicationId(app_id)
1554 .SetDefaultValidity(),
1555 &key_blob, &key_characteristics));
1556 ASSERT_GT(key_blob.size(), 0U);
1557 CheckBaseParams(key_characteristics);
1558
1559 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1560
1561 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1562 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1563 << "Key size " << key_size << "missing";
1564
1565 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1566 ASSERT_GT(cert_chain_.size(), 0);
1567
1568 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1569 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1570 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1571 sw_enforced, hw_enforced, SecLevel(),
1572 cert_chain_[0].encodedCertificate));
1573
1574 CheckedDeleteKey(&key_blob);
1575 }
1576}
1577
1578/*
Qi Wud22ec842020-11-26 13:27:53 +08001579 * NewKeyGenerationTest.LimitedUsageEcdsa
1580 *
1581 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1582 * resulting keys have correct characteristics.
1583 */
1584TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
1585 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1586 vector<uint8_t> key_blob;
1587 vector<KeyCharacteristics> key_characteristics;
1588 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1589 .EcdsaSigningKey(key_size)
1590 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001591 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1592 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001593 &key_blob, &key_characteristics));
1594
1595 ASSERT_GT(key_blob.size(), 0U);
1596 CheckBaseParams(key_characteristics);
1597
1598 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1599
1600 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1601 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1602 << "Key size " << key_size << "missing";
1603
1604 // Check the usage count limit tag appears in the authorizations.
1605 AuthorizationSet auths;
1606 for (auto& entry : key_characteristics) {
1607 auths.push_back(AuthorizationSet(entry.authorizations));
1608 }
1609 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1610 << "key usage count limit " << 1U << " missing";
1611
1612 CheckedDeleteKey(&key_blob);
1613 }
1614}
1615
1616/*
Selene Huang31ab4042020-04-29 04:22:39 -07001617 * NewKeyGenerationTest.EcdsaDefaultSize
1618 *
1619 * Verifies that failing to specify a key size for EC key generation returns
1620 * UNSUPPORTED_KEY_SIZE.
1621 */
1622TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1623 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1624 GenerateKey(AuthorizationSetBuilder()
1625 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1626 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001627 .Digest(Digest::NONE)
1628 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001629}
1630
1631/*
1632 * NewKeyGenerationTest.EcdsaInvalidSize
1633 *
1634 * Verifies that specifying an invalid key size for EC key generation returns
1635 * UNSUPPORTED_KEY_SIZE.
1636 */
1637TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
1638 for (auto key_size : InvalidKeySizes(Algorithm::EC)) {
1639 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001640 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001641 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1642 .EcdsaSigningKey(key_size)
1643 .Digest(Digest::NONE)
1644 .SetDefaultValidity(),
1645 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001646 }
1647
Janis Danisevskis164bb872021-02-09 11:30:25 -08001648 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1649 .EcdsaSigningKey(190)
1650 .Digest(Digest::NONE)
1651 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001652}
1653
1654/*
1655 * NewKeyGenerationTest.EcdsaMismatchKeySize
1656 *
1657 * Verifies that specifying mismatched key size and curve for EC key generation returns
1658 * INVALID_ARGUMENT.
1659 */
1660TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1661 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1662
1663 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT,
1664 GenerateKey(AuthorizationSetBuilder()
1665 .EcdsaSigningKey(224)
1666 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001667 .Digest(Digest::NONE)
1668 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001669}
1670
1671/*
1672 * NewKeyGenerationTest.EcdsaAllValidSizes
1673 *
1674 * Verifies that keymint supports all required EC key sizes.
1675 */
1676TEST_P(NewKeyGenerationTest, EcdsaAllValidSizes) {
1677 auto valid_sizes = ValidKeySizes(Algorithm::EC);
1678 for (size_t size : valid_sizes) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001679 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1680 .EcdsaSigningKey(size)
1681 .Digest(Digest::NONE)
1682 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001683 << "Failed to generate size: " << size;
1684 CheckedDeleteKey();
1685 }
1686}
1687
1688/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001689 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07001690 *
1691 * Verifies that keymint does not support any curve designated as unsupported.
1692 */
1693TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1694 Digest digest;
1695 if (SecLevel() == SecurityLevel::STRONGBOX) {
1696 digest = Digest::SHA_2_256;
1697 } else {
1698 digest = Digest::SHA_2_512;
1699 }
1700 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001701 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1702 .EcdsaSigningKey(curve)
1703 .Digest(digest)
1704 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001705 << "Failed to generate key on curve: " << curve;
1706 CheckedDeleteKey();
1707 }
1708}
1709
1710/*
1711 * NewKeyGenerationTest.Hmac
1712 *
1713 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1714 * characteristics.
1715 */
1716TEST_P(NewKeyGenerationTest, Hmac) {
1717 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1718 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001719 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001720 constexpr size_t key_size = 128;
1721 ASSERT_EQ(ErrorCode::OK,
1722 GenerateKey(
1723 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1724 TAG_MIN_MAC_LENGTH, 128),
1725 &key_blob, &key_characteristics));
1726
1727 ASSERT_GT(key_blob.size(), 0U);
1728 CheckBaseParams(key_characteristics);
1729
Shawn Willden7f424372021-01-10 18:06:50 -07001730 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1731 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1732 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1733 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001734
1735 CheckedDeleteKey(&key_blob);
1736 }
1737}
1738
1739/*
Selene Huang4f64c222021-04-13 19:54:36 -07001740 * NewKeyGenerationTest.HmacNoAttestation
1741 *
1742 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1743 * and app id are provided.
1744 */
1745TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1746 auto challenge = "hello";
1747 auto app_id = "foo";
1748
1749 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1750 vector<uint8_t> key_blob;
1751 vector<KeyCharacteristics> key_characteristics;
1752 constexpr size_t key_size = 128;
1753 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1754 .HmacKey(key_size)
1755 .Digest(digest)
1756 .AttestationChallenge(challenge)
1757 .AttestationApplicationId(app_id)
1758 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1759 &key_blob, &key_characteristics));
1760
1761 ASSERT_GT(key_blob.size(), 0U);
1762 ASSERT_EQ(cert_chain_.size(), 0);
1763 CheckBaseParams(key_characteristics);
1764
1765 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1766 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1767 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1768 << "Key size " << key_size << "missing";
1769
1770 CheckedDeleteKey(&key_blob);
1771 }
1772}
1773
1774/*
Qi Wud22ec842020-11-26 13:27:53 +08001775 * NewKeyGenerationTest.LimitedUsageHmac
1776 *
1777 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1778 * resulting keys have correct characteristics.
1779 */
1780TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1781 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1782 vector<uint8_t> key_blob;
1783 vector<KeyCharacteristics> key_characteristics;
1784 constexpr size_t key_size = 128;
1785 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1786 .HmacKey(key_size)
1787 .Digest(digest)
1788 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1789 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1790 &key_blob, &key_characteristics));
1791
1792 ASSERT_GT(key_blob.size(), 0U);
1793 CheckBaseParams(key_characteristics);
1794
1795 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1796 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1797 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1798 << "Key size " << key_size << "missing";
1799
1800 // Check the usage count limit tag appears in the authorizations.
1801 AuthorizationSet auths;
1802 for (auto& entry : key_characteristics) {
1803 auths.push_back(AuthorizationSet(entry.authorizations));
1804 }
1805 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1806 << "key usage count limit " << 1U << " missing";
1807
1808 CheckedDeleteKey(&key_blob);
1809 }
1810}
1811
1812/*
Selene Huang31ab4042020-04-29 04:22:39 -07001813 * NewKeyGenerationTest.HmacCheckKeySizes
1814 *
1815 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1816 */
1817TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1818 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1819 if (key_size < 64 || key_size % 8 != 0) {
1820 // To keep this test from being very slow, we only test a random fraction of
1821 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1822 // them, we expect to run ~40 of them in each run.
1823 if (key_size % 8 == 0 || random() % 10 == 0) {
1824 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1825 GenerateKey(AuthorizationSetBuilder()
1826 .HmacKey(key_size)
1827 .Digest(Digest::SHA_2_256)
1828 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1829 << "HMAC key size " << key_size << " invalid";
1830 }
1831 } else {
1832 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1833 .HmacKey(key_size)
1834 .Digest(Digest::SHA_2_256)
1835 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1836 << "Failed to generate HMAC key of size " << key_size;
1837 CheckedDeleteKey();
1838 }
1839 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01001840 if (SecLevel() == SecurityLevel::STRONGBOX) {
1841 // STRONGBOX devices must not support keys larger than 512 bits.
1842 size_t key_size = 520;
1843 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1844 GenerateKey(AuthorizationSetBuilder()
1845 .HmacKey(key_size)
1846 .Digest(Digest::SHA_2_256)
1847 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1848 << "HMAC key size " << key_size << " unexpectedly valid";
1849 }
Selene Huang31ab4042020-04-29 04:22:39 -07001850}
1851
1852/*
1853 * NewKeyGenerationTest.HmacCheckMinMacLengths
1854 *
1855 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
1856 * test is probabilistic in order to keep the runtime down, but any failure prints out the
1857 * specific MAC length that failed, so reproducing a failed run will be easy.
1858 */
1859TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
1860 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
1861 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
1862 // To keep this test from being very long, we only test a random fraction of
1863 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
1864 // we expect to run ~17 of them in each run.
1865 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
1866 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
1867 GenerateKey(AuthorizationSetBuilder()
1868 .HmacKey(128)
1869 .Digest(Digest::SHA_2_256)
1870 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1871 << "HMAC min mac length " << min_mac_length << " invalid.";
1872 }
1873 } else {
1874 EXPECT_EQ(ErrorCode::OK,
1875 GenerateKey(AuthorizationSetBuilder()
1876 .HmacKey(128)
1877 .Digest(Digest::SHA_2_256)
1878 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1879 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
1880 CheckedDeleteKey();
1881 }
1882 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01001883
1884 // Minimum MAC length must be no more than 512 bits.
1885 size_t min_mac_length = 520;
1886 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
1887 GenerateKey(AuthorizationSetBuilder()
1888 .HmacKey(128)
1889 .Digest(Digest::SHA_2_256)
1890 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1891 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07001892}
1893
1894/*
1895 * NewKeyGenerationTest.HmacMultipleDigests
1896 *
1897 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
1898 */
1899TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
1900 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1901
1902 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1903 GenerateKey(AuthorizationSetBuilder()
1904 .HmacKey(128)
1905 .Digest(Digest::SHA1)
1906 .Digest(Digest::SHA_2_256)
1907 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1908}
1909
1910/*
1911 * NewKeyGenerationTest.HmacDigestNone
1912 *
1913 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
1914 */
1915TEST_P(NewKeyGenerationTest, HmacDigestNone) {
1916 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1917 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
1918 128)));
1919
1920 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1921 GenerateKey(AuthorizationSetBuilder()
1922 .HmacKey(128)
1923 .Digest(Digest::NONE)
1924 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1925}
1926
Selene Huang4f64c222021-04-13 19:54:36 -07001927/*
1928 * NewKeyGenerationTest.AesNoAttestation
1929 *
1930 * Verifies that attestation parameters to AES keys are ignored and generateKey
1931 * will succeed.
1932 */
1933TEST_P(NewKeyGenerationTest, AesNoAttestation) {
1934 auto challenge = "hello";
1935 auto app_id = "foo";
1936
1937 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1938 .Authorization(TAG_NO_AUTH_REQUIRED)
1939 .AesEncryptionKey(128)
1940 .EcbMode()
1941 .Padding(PaddingMode::PKCS7)
1942 .AttestationChallenge(challenge)
1943 .AttestationApplicationId(app_id)));
1944
1945 ASSERT_EQ(cert_chain_.size(), 0);
1946}
1947
1948/*
1949 * NewKeyGenerationTest.TripleDesNoAttestation
1950 *
1951 * Verifies that attesting parameters to 3DES keys are ignored and generate key
1952 * will be successful. No attestation should be generated.
1953 */
1954TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
1955 auto challenge = "hello";
1956 auto app_id = "foo";
1957
1958 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1959 .TripleDesEncryptionKey(168)
1960 .BlockMode(BlockMode::ECB)
1961 .Authorization(TAG_NO_AUTH_REQUIRED)
1962 .Padding(PaddingMode::NONE)
1963 .AttestationChallenge(challenge)
1964 .AttestationApplicationId(app_id)));
1965 ASSERT_EQ(cert_chain_.size(), 0);
1966}
1967
Selene Huang31ab4042020-04-29 04:22:39 -07001968INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
1969
1970typedef KeyMintAidlTestBase SigningOperationsTest;
1971
1972/*
1973 * SigningOperationsTest.RsaSuccess
1974 *
1975 * Verifies that raw RSA signature operations succeed.
1976 */
1977TEST_P(SigningOperationsTest, RsaSuccess) {
1978 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1979 .RsaSigningKey(2048, 65537)
1980 .Digest(Digest::NONE)
1981 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001982 .Authorization(TAG_NO_AUTH_REQUIRED)
1983 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001984 string message = "12345678901234567890123456789012";
1985 string signature = SignMessage(
1986 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01001987 LocalVerifyMessage(message, signature,
1988 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1989}
1990
1991/*
1992 * SigningOperationsTest.RsaAllPaddingsAndDigests
1993 *
1994 * Verifies RSA signature/verification for all padding modes and digests.
1995 */
1996TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
1997 auto authorizations = AuthorizationSetBuilder()
1998 .Authorization(TAG_NO_AUTH_REQUIRED)
1999 .RsaSigningKey(2048, 65537)
2000 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2001 .Padding(PaddingMode::NONE)
2002 .Padding(PaddingMode::RSA_PSS)
2003 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2004 .SetDefaultValidity();
2005
2006 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2007
2008 string message(128, 'a');
2009 string corrupt_message(message);
2010 ++corrupt_message[corrupt_message.size() / 2];
2011
2012 for (auto padding :
2013 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2014 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2015 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2016 // Digesting only makes sense with padding.
2017 continue;
2018 }
2019
2020 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2021 // PSS requires digesting.
2022 continue;
2023 }
2024
2025 string signature =
2026 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2027 LocalVerifyMessage(message, signature,
2028 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2029 }
2030 }
Selene Huang31ab4042020-04-29 04:22:39 -07002031}
2032
2033/*
2034 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2035 *
Shawn Willden7f424372021-01-10 18:06:50 -07002036 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002037 */
2038TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2039 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2040 .Authorization(TAG_NO_AUTH_REQUIRED)
2041 .RsaSigningKey(2048, 65537)
2042 .Digest(Digest::NONE)
2043 .Padding(PaddingMode::NONE)
2044 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002045 .Authorization(TAG_APPLICATION_DATA, "appdata")
2046 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002047 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2048 Begin(KeyPurpose::SIGN,
2049 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2050 AbortIfNeeded();
2051 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2052 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2053 .Digest(Digest::NONE)
2054 .Padding(PaddingMode::NONE)
2055 .Authorization(TAG_APPLICATION_ID, "clientid")));
2056 AbortIfNeeded();
2057 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2058 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2059 .Digest(Digest::NONE)
2060 .Padding(PaddingMode::NONE)
2061 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2062 AbortIfNeeded();
2063 EXPECT_EQ(ErrorCode::OK,
2064 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2065 .Digest(Digest::NONE)
2066 .Padding(PaddingMode::NONE)
2067 .Authorization(TAG_APPLICATION_DATA, "appdata")
2068 .Authorization(TAG_APPLICATION_ID, "clientid")));
2069 AbortIfNeeded();
2070}
2071
2072/*
2073 * SigningOperationsTest.RsaPssSha256Success
2074 *
2075 * Verifies that RSA-PSS signature operations succeed.
2076 */
2077TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2078 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2079 .RsaSigningKey(2048, 65537)
2080 .Digest(Digest::SHA_2_256)
2081 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002082 .Authorization(TAG_NO_AUTH_REQUIRED)
2083 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002084 // Use large message, which won't work without digesting.
2085 string message(1024, 'a');
2086 string signature = SignMessage(
2087 message,
2088 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2089}
2090
2091/*
2092 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2093 *
2094 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2095 * supports only unpadded operations.
2096 */
2097TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2098 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2099 .RsaSigningKey(2048, 65537)
2100 .Digest(Digest::NONE)
2101 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002102 .Padding(PaddingMode::NONE)
2103 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002104 string message = "12345678901234567890123456789012";
2105 string signature;
2106
2107 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2108 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2109 .Digest(Digest::NONE)
2110 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2111}
2112
2113/*
2114 * SigningOperationsTest.NoUserConfirmation
2115 *
2116 * Verifies that keymint rejects signing operations for keys with
2117 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2118 * presented.
2119 */
2120TEST_P(SigningOperationsTest, NoUserConfirmation) {
2121 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08002122 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2123 .RsaSigningKey(1024, 65537)
2124 .Digest(Digest::NONE)
2125 .Padding(PaddingMode::NONE)
2126 .Authorization(TAG_NO_AUTH_REQUIRED)
2127 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2128 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002129
2130 const string message = "12345678901234567890123456789012";
2131 EXPECT_EQ(ErrorCode::OK,
2132 Begin(KeyPurpose::SIGN,
2133 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2134 string signature;
2135 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2136}
2137
2138/*
2139 * SigningOperationsTest.RsaPkcs1Sha256Success
2140 *
2141 * Verifies that digested RSA-PKCS1 signature operations succeed.
2142 */
2143TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2144 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2145 .RsaSigningKey(2048, 65537)
2146 .Digest(Digest::SHA_2_256)
2147 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002148 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2149 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002150 string message(1024, 'a');
2151 string signature = SignMessage(message, AuthorizationSetBuilder()
2152 .Digest(Digest::SHA_2_256)
2153 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2154}
2155
2156/*
2157 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2158 *
2159 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2160 */
2161TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2162 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2163 .RsaSigningKey(2048, 65537)
2164 .Digest(Digest::NONE)
2165 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002166 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2167 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002168 string message(53, 'a');
2169 string signature = SignMessage(message, AuthorizationSetBuilder()
2170 .Digest(Digest::NONE)
2171 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2172}
2173
2174/*
2175 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2176 *
2177 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2178 * given a too-long message.
2179 */
2180TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2181 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2182 .RsaSigningKey(2048, 65537)
2183 .Digest(Digest::NONE)
2184 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002185 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2186 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002187 string message(257, 'a');
2188
2189 EXPECT_EQ(ErrorCode::OK,
2190 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2191 .Digest(Digest::NONE)
2192 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2193 string signature;
2194 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2195}
2196
2197/*
2198 * SigningOperationsTest.RsaPssSha512TooSmallKey
2199 *
2200 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2201 * used with a key that is too small for the message.
2202 *
2203 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2204 * keymint specification requires that salt_size == digest_size, so the message will be
2205 * digest_size * 2 +
2206 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2207 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2208 * for a 1024-bit key.
2209 */
2210TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
2211 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2212 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2213 .RsaSigningKey(1024, 65537)
2214 .Digest(Digest::SHA_2_512)
2215 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002216 .Padding(PaddingMode::RSA_PSS)
2217 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002218 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2219 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2220 .Digest(Digest::SHA_2_512)
2221 .Padding(PaddingMode::RSA_PSS)));
2222}
2223
2224/*
2225 * SigningOperationsTest.RsaNoPaddingTooLong
2226 *
2227 * Verifies that raw RSA signature operations fail with the correct error code when
2228 * given a too-long message.
2229 */
2230TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2231 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2232 .RsaSigningKey(2048, 65537)
2233 .Digest(Digest::NONE)
2234 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002235 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2236 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002237 // One byte too long
2238 string message(2048 / 8 + 1, 'a');
2239 ASSERT_EQ(ErrorCode::OK,
2240 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2241 .Digest(Digest::NONE)
2242 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2243 string result;
2244 ErrorCode finish_error_code = Finish(message, &result);
2245 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2246 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2247
2248 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2249 message = string(128 * 1024, 'a');
2250 ASSERT_EQ(ErrorCode::OK,
2251 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2252 .Digest(Digest::NONE)
2253 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2254 finish_error_code = Finish(message, &result);
2255 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2256 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2257}
2258
2259/*
2260 * SigningOperationsTest.RsaAbort
2261 *
2262 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2263 * test, but the behavior should be algorithm and purpose-independent.
2264 */
2265TEST_P(SigningOperationsTest, RsaAbort) {
2266 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2267 .RsaSigningKey(2048, 65537)
2268 .Digest(Digest::NONE)
2269 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002270 .Padding(PaddingMode::NONE)
2271 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002272
2273 ASSERT_EQ(ErrorCode::OK,
2274 Begin(KeyPurpose::SIGN,
2275 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2276 EXPECT_EQ(ErrorCode::OK, Abort());
2277
2278 // Another abort should fail
2279 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2280
2281 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002282 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002283}
2284
2285/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002286 * SigningOperationsTest.RsaNonUniqueParams
2287 *
2288 * Verifies that an operation with multiple padding modes is rejected.
2289 */
2290TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2291 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2292 .RsaSigningKey(2048, 65537)
2293 .Digest(Digest::NONE)
2294 .Digest(Digest::SHA1)
2295 .Authorization(TAG_NO_AUTH_REQUIRED)
2296 .Padding(PaddingMode::NONE)
2297 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2298 .SetDefaultValidity()));
2299
2300 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2301 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2302 .Digest(Digest::NONE)
2303 .Padding(PaddingMode::NONE)
2304 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2305
2306 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2307 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2308 .Digest(Digest::NONE)
2309 .Digest(Digest::SHA1)
2310 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2311
2312 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2313 Begin(KeyPurpose::SIGN,
2314 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2315}
2316
2317/*
Selene Huang31ab4042020-04-29 04:22:39 -07002318 * SigningOperationsTest.RsaUnsupportedPadding
2319 *
2320 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2321 * with a padding mode inappropriate for RSA.
2322 */
2323TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2324 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2325 .RsaSigningKey(2048, 65537)
2326 .Authorization(TAG_NO_AUTH_REQUIRED)
2327 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002328 .Padding(PaddingMode::PKCS7)
2329 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002330 ASSERT_EQ(
2331 ErrorCode::UNSUPPORTED_PADDING_MODE,
2332 Begin(KeyPurpose::SIGN,
2333 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002334 CheckedDeleteKey();
2335
2336 ASSERT_EQ(ErrorCode::OK,
2337 GenerateKey(
2338 AuthorizationSetBuilder()
2339 .RsaSigningKey(2048, 65537)
2340 .Authorization(TAG_NO_AUTH_REQUIRED)
2341 .Digest(Digest::SHA_2_256 /* supported digest */)
2342 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2343 .SetDefaultValidity()));
2344 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2345 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2346 .Digest(Digest::SHA_2_256)
2347 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002348}
2349
2350/*
2351 * SigningOperationsTest.RsaPssNoDigest
2352 *
2353 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2354 */
2355TEST_P(SigningOperationsTest, RsaNoDigest) {
2356 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2357 .RsaSigningKey(2048, 65537)
2358 .Authorization(TAG_NO_AUTH_REQUIRED)
2359 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002360 .Padding(PaddingMode::RSA_PSS)
2361 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002362 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2363 Begin(KeyPurpose::SIGN,
2364 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2365
2366 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2367 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2368}
2369
2370/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002371 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002372 *
2373 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2374 * supported in some cases (as validated in other tests), but a mode must be specified.
2375 */
2376TEST_P(SigningOperationsTest, RsaNoPadding) {
2377 // Padding must be specified
2378 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2379 .RsaKey(2048, 65537)
2380 .Authorization(TAG_NO_AUTH_REQUIRED)
2381 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002382 .Digest(Digest::NONE)
2383 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002384 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2385 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2386}
2387
2388/*
2389 * SigningOperationsTest.RsaShortMessage
2390 *
2391 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2392 */
2393TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2394 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2395 .Authorization(TAG_NO_AUTH_REQUIRED)
2396 .RsaSigningKey(2048, 65537)
2397 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002398 .Padding(PaddingMode::NONE)
2399 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002400
2401 // Barely shorter
2402 string message(2048 / 8 - 1, 'a');
2403 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2404
2405 // Much shorter
2406 message = "a";
2407 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2408}
2409
2410/*
2411 * SigningOperationsTest.RsaSignWithEncryptionKey
2412 *
2413 * Verifies that RSA encryption keys cannot be used to sign.
2414 */
2415TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2416 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2417 .Authorization(TAG_NO_AUTH_REQUIRED)
2418 .RsaEncryptionKey(2048, 65537)
2419 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002420 .Padding(PaddingMode::NONE)
2421 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002422 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2423 Begin(KeyPurpose::SIGN,
2424 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2425}
2426
2427/*
2428 * SigningOperationsTest.RsaSignTooLargeMessage
2429 *
2430 * Verifies that attempting a raw signature of a message which is the same length as the key,
2431 * but numerically larger than the public modulus, fails with the correct error.
2432 */
2433TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2434 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2435 .Authorization(TAG_NO_AUTH_REQUIRED)
2436 .RsaSigningKey(2048, 65537)
2437 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002438 .Padding(PaddingMode::NONE)
2439 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002440
2441 // Largest possible message will always be larger than the public modulus.
2442 string message(2048 / 8, static_cast<char>(0xff));
2443 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2444 .Authorization(TAG_NO_AUTH_REQUIRED)
2445 .Digest(Digest::NONE)
2446 .Padding(PaddingMode::NONE)));
2447 string signature;
2448 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2449}
2450
2451/*
2452 * SigningOperationsTest.EcdsaAllSizesAndHashes
2453 *
2454 * Verifies that ECDSA operations succeed with all possible key sizes and hashes.
2455 */
2456TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
2457 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
2458 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2459 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2460 .Authorization(TAG_NO_AUTH_REQUIRED)
2461 .EcdsaSigningKey(key_size)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002462 .Digest(digest)
2463 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002464 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size
2465 << " and digest " << digest;
2466 if (error != ErrorCode::OK) continue;
2467
2468 string message(1024, 'a');
2469 if (digest == Digest::NONE) message.resize(key_size / 8);
2470 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2471 CheckedDeleteKey();
2472 }
2473 }
2474}
2475
2476/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01002477 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2478 *
2479 * Verifies ECDSA signature/verification for all digests and curves.
2480 */
2481TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2482 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2483
2484 string message = "1234567890";
2485 string corrupt_message = "2234567890";
2486 for (auto curve : ValidCurves()) {
2487 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2488 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2489 .Authorization(TAG_NO_AUTH_REQUIRED)
2490 .EcdsaSigningKey(curve)
2491 .Digest(digests)
2492 .SetDefaultValidity());
2493 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2494 if (error != ErrorCode::OK) {
2495 continue;
2496 }
2497
2498 for (auto digest : digests) {
2499 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2500 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2501 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2502 }
2503
2504 auto rc = DeleteKey();
2505 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2506 }
2507}
2508
2509/*
Selene Huang31ab4042020-04-29 04:22:39 -07002510 * SigningOperationsTest.EcdsaAllCurves
2511 *
2512 * Verifies that ECDSA operations succeed with all possible curves.
2513 */
2514TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2515 for (auto curve : ValidCurves()) {
2516 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2517 .Authorization(TAG_NO_AUTH_REQUIRED)
2518 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002519 .Digest(Digest::SHA_2_256)
2520 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002521 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2522 if (error != ErrorCode::OK) continue;
2523
2524 string message(1024, 'a');
2525 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2526 CheckedDeleteKey();
2527 }
2528}
2529
2530/*
2531 * SigningOperationsTest.EcdsaNoDigestHugeData
2532 *
2533 * Verifies that ECDSA operations support very large messages, even without digesting. This
2534 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2535 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2536 * the framework.
2537 */
2538TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2539 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2540 .Authorization(TAG_NO_AUTH_REQUIRED)
2541 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002542 .Digest(Digest::NONE)
2543 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002544 string message(1 * 1024, 'a');
2545 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2546}
2547
2548/*
2549 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2550 *
2551 * Verifies that using an EC key requires the correct app ID/data.
2552 */
2553TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2554 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2555 .Authorization(TAG_NO_AUTH_REQUIRED)
2556 .EcdsaSigningKey(256)
2557 .Digest(Digest::NONE)
2558 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002559 .Authorization(TAG_APPLICATION_DATA, "appdata")
2560 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002561 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2562 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2563 AbortIfNeeded();
2564 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2565 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2566 .Digest(Digest::NONE)
2567 .Authorization(TAG_APPLICATION_ID, "clientid")));
2568 AbortIfNeeded();
2569 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2570 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2571 .Digest(Digest::NONE)
2572 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2573 AbortIfNeeded();
2574 EXPECT_EQ(ErrorCode::OK,
2575 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2576 .Digest(Digest::NONE)
2577 .Authorization(TAG_APPLICATION_DATA, "appdata")
2578 .Authorization(TAG_APPLICATION_ID, "clientid")));
2579 AbortIfNeeded();
2580}
2581
2582/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002583 * SigningOperationsTest.EcdsaIncompatibleDigest
2584 *
2585 * Verifies that using an EC key requires compatible digest.
2586 */
2587TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2588 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2589 .Authorization(TAG_NO_AUTH_REQUIRED)
2590 .EcdsaSigningKey(256)
2591 .Digest(Digest::NONE)
2592 .Digest(Digest::SHA1)
2593 .SetDefaultValidity()));
2594 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2595 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2596 AbortIfNeeded();
2597}
2598
2599/*
Selene Huang31ab4042020-04-29 04:22:39 -07002600 * SigningOperationsTest.AesEcbSign
2601 *
2602 * Verifies that attempts to use AES keys to sign fail in the correct way.
2603 */
2604TEST_P(SigningOperationsTest, AesEcbSign) {
2605 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2606 .Authorization(TAG_NO_AUTH_REQUIRED)
2607 .SigningKey()
2608 .AesEncryptionKey(128)
2609 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2610
2611 AuthorizationSet out_params;
2612 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2613 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2614 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2615 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2616}
2617
2618/*
2619 * SigningOperationsTest.HmacAllDigests
2620 *
2621 * Verifies that HMAC works with all digests.
2622 */
2623TEST_P(SigningOperationsTest, HmacAllDigests) {
2624 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2625 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2626 .Authorization(TAG_NO_AUTH_REQUIRED)
2627 .HmacKey(128)
2628 .Digest(digest)
2629 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2630 << "Failed to create HMAC key with digest " << digest;
2631 string message = "12345678901234567890123456789012";
2632 string signature = MacMessage(message, digest, 160);
2633 EXPECT_EQ(160U / 8U, signature.size())
2634 << "Failed to sign with HMAC key with digest " << digest;
2635 CheckedDeleteKey();
2636 }
2637}
2638
2639/*
2640 * SigningOperationsTest.HmacSha256TooLargeMacLength
2641 *
2642 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2643 * digest size.
2644 */
2645TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2646 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2647 .Authorization(TAG_NO_AUTH_REQUIRED)
2648 .HmacKey(128)
2649 .Digest(Digest::SHA_2_256)
2650 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2651 AuthorizationSet output_params;
2652 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2653 AuthorizationSetBuilder()
2654 .Digest(Digest::SHA_2_256)
2655 .Authorization(TAG_MAC_LENGTH, 264),
2656 &output_params));
2657}
2658
2659/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002660 * SigningOperationsTest.HmacSha256InvalidMacLength
2661 *
2662 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2663 * not a multiple of 8.
2664 */
2665TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2666 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2667 .Authorization(TAG_NO_AUTH_REQUIRED)
2668 .HmacKey(128)
2669 .Digest(Digest::SHA_2_256)
2670 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2671 AuthorizationSet output_params;
2672 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2673 AuthorizationSetBuilder()
2674 .Digest(Digest::SHA_2_256)
2675 .Authorization(TAG_MAC_LENGTH, 161),
2676 &output_params));
2677}
2678
2679/*
Selene Huang31ab4042020-04-29 04:22:39 -07002680 * SigningOperationsTest.HmacSha256TooSmallMacLength
2681 *
2682 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2683 * specified minimum MAC length.
2684 */
2685TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2686 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2687 .Authorization(TAG_NO_AUTH_REQUIRED)
2688 .HmacKey(128)
2689 .Digest(Digest::SHA_2_256)
2690 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2691 AuthorizationSet output_params;
2692 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2693 AuthorizationSetBuilder()
2694 .Digest(Digest::SHA_2_256)
2695 .Authorization(TAG_MAC_LENGTH, 120),
2696 &output_params));
2697}
2698
2699/*
2700 * SigningOperationsTest.HmacRfc4231TestCase3
2701 *
2702 * Validates against the test vectors from RFC 4231 test case 3.
2703 */
2704TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2705 string key(20, 0xaa);
2706 string message(50, 0xdd);
2707 uint8_t sha_224_expected[] = {
2708 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2709 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2710 };
2711 uint8_t sha_256_expected[] = {
2712 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2713 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2714 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2715 };
2716 uint8_t sha_384_expected[] = {
2717 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2718 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2719 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2720 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2721 };
2722 uint8_t sha_512_expected[] = {
2723 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2724 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2725 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2726 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2727 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2728 };
2729
2730 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2731 if (SecLevel() != SecurityLevel::STRONGBOX) {
2732 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2733 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2734 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2735 }
2736}
2737
2738/*
2739 * SigningOperationsTest.HmacRfc4231TestCase5
2740 *
2741 * Validates against the test vectors from RFC 4231 test case 5.
2742 */
2743TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2744 string key(20, 0x0c);
2745 string message = "Test With Truncation";
2746
2747 uint8_t sha_224_expected[] = {
2748 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2749 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2750 };
2751 uint8_t sha_256_expected[] = {
2752 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2753 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2754 };
2755 uint8_t sha_384_expected[] = {
2756 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2757 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2758 };
2759 uint8_t sha_512_expected[] = {
2760 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2761 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2762 };
2763
2764 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2765 if (SecLevel() != SecurityLevel::STRONGBOX) {
2766 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2767 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2768 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2769 }
2770}
2771
2772INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2773
2774typedef KeyMintAidlTestBase VerificationOperationsTest;
2775
2776/*
Selene Huang31ab4042020-04-29 04:22:39 -07002777 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2778 *
2779 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2780 */
2781TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2782 string key_material = "HelloThisIsAKey";
2783
2784 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002785 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002786 EXPECT_EQ(ErrorCode::OK,
2787 ImportKey(AuthorizationSetBuilder()
2788 .Authorization(TAG_NO_AUTH_REQUIRED)
2789 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2790 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2791 .Digest(Digest::SHA_2_256)
2792 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2793 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2794 EXPECT_EQ(ErrorCode::OK,
2795 ImportKey(AuthorizationSetBuilder()
2796 .Authorization(TAG_NO_AUTH_REQUIRED)
2797 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2798 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2799 .Digest(Digest::SHA_2_256)
2800 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2801 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2802
2803 string message = "This is a message.";
2804 string signature = SignMessage(
2805 signing_key, message,
2806 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2807
2808 // Signing key should not work.
2809 AuthorizationSet out_params;
2810 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2811 Begin(KeyPurpose::VERIFY, signing_key,
2812 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2813
2814 // Verification key should work.
2815 VerifyMessage(verification_key, message, signature,
2816 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2817
2818 CheckedDeleteKey(&signing_key);
2819 CheckedDeleteKey(&verification_key);
2820}
2821
2822INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2823
2824typedef KeyMintAidlTestBase ExportKeyTest;
2825
2826/*
2827 * ExportKeyTest.RsaUnsupportedKeyFormat
2828 *
2829 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2830 */
2831// TODO(seleneh) add ExportKey to GenerateKey
2832// check result
2833
2834class ImportKeyTest : public KeyMintAidlTestBase {
2835 public:
2836 template <TagType tag_type, Tag tag, typename ValueT>
2837 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2838 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002839 for (auto& entry : key_characteristics_) {
2840 if (entry.securityLevel == SecLevel()) {
2841 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2842 << "Tag " << tag << " with value " << expected
2843 << " not found at security level" << entry.securityLevel;
2844 } else {
2845 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
2846 << "Tag " << tag << " found at security level " << entry.securityLevel;
2847 }
Selene Huang31ab4042020-04-29 04:22:39 -07002848 }
2849 }
2850
2851 void CheckOrigin() {
2852 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07002853 // Origin isn't a crypto param, but it always lives with them.
2854 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07002855 }
2856};
2857
2858/*
2859 * ImportKeyTest.RsaSuccess
2860 *
2861 * Verifies that importing and using an RSA key pair works correctly.
2862 */
2863TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07002864 uint32_t key_size;
2865 string key;
2866
2867 if (SecLevel() == SecurityLevel::STRONGBOX) {
2868 key_size = 2048;
2869 key = rsa_2048_key;
2870 } else {
2871 key_size = 1024;
2872 key = rsa_key;
2873 }
2874
Selene Huang31ab4042020-04-29 04:22:39 -07002875 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2876 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07002877 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07002878 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002879 .Padding(PaddingMode::RSA_PSS)
2880 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07002881 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07002882
2883 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07002884 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002885 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
2886 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2887 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
2888 CheckOrigin();
2889
2890 string message(1024 / 8, 'a');
2891 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
2892 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002893 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07002894}
2895
2896/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002897 * ImportKeyTest.RsaSuccessWithoutParams
2898 *
2899 * Verifies that importing and using an RSA key pair without specifying parameters
2900 * works correctly.
2901 */
2902TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
2903 uint32_t key_size;
2904 string key;
2905
2906 if (SecLevel() == SecurityLevel::STRONGBOX) {
2907 key_size = 2048;
2908 key = rsa_2048_key;
2909 } else {
2910 key_size = 1024;
2911 key = rsa_key;
2912 }
2913
2914 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2915 .Authorization(TAG_NO_AUTH_REQUIRED)
2916 .SigningKey()
2917 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
2918 .Digest(Digest::SHA_2_256)
2919 .Padding(PaddingMode::RSA_PSS)
2920 .SetDefaultValidity(),
2921 KeyFormat::PKCS8, key));
2922
2923 // Key size and public exponent are determined from the imported key material.
2924 CheckCryptoParam(TAG_KEY_SIZE, key_size);
2925 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
2926
2927 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
2928 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2929 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
2930 CheckOrigin();
2931
2932 string message(1024 / 8, 'a');
2933 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
2934 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002935 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002936}
2937
2938/*
Selene Huang31ab4042020-04-29 04:22:39 -07002939 * ImportKeyTest.RsaKeySizeMismatch
2940 *
2941 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
2942 * correct way.
2943 */
2944TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
2945 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2946 ImportKey(AuthorizationSetBuilder()
2947 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
2948 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002949 .Padding(PaddingMode::NONE)
2950 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002951 KeyFormat::PKCS8, rsa_key));
2952}
2953
2954/*
2955 * ImportKeyTest.RsaPublicExponentMismatch
2956 *
2957 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
2958 * fails in the correct way.
2959 */
2960TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
2961 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2962 ImportKey(AuthorizationSetBuilder()
2963 .RsaSigningKey(1024, 3 /* Doesn't match key */)
2964 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002965 .Padding(PaddingMode::NONE)
2966 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002967 KeyFormat::PKCS8, rsa_key));
2968}
2969
2970/*
2971 * ImportKeyTest.EcdsaSuccess
2972 *
2973 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
2974 */
2975TEST_P(ImportKeyTest, EcdsaSuccess) {
2976 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2977 .Authorization(TAG_NO_AUTH_REQUIRED)
2978 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002979 .Digest(Digest::SHA_2_256)
2980 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002981 KeyFormat::PKCS8, ec_256_key));
2982
2983 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2984 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2985 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2986 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2987
2988 CheckOrigin();
2989
2990 string message(32, 'a');
2991 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2992 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002993 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07002994}
2995
2996/*
2997 * ImportKeyTest.EcdsaP256RFC5915Success
2998 *
2999 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3000 * correctly.
3001 */
3002TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3003 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3004 .Authorization(TAG_NO_AUTH_REQUIRED)
3005 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003006 .Digest(Digest::SHA_2_256)
3007 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003008 KeyFormat::PKCS8, ec_256_key_rfc5915));
3009
3010 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3011 CheckCryptoParam(TAG_KEY_SIZE, 256U);
3012 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3013 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3014
3015 CheckOrigin();
3016
3017 string message(32, 'a');
3018 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3019 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003020 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003021}
3022
3023/*
3024 * ImportKeyTest.EcdsaP256SEC1Success
3025 *
3026 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3027 */
3028TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3029 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3030 .Authorization(TAG_NO_AUTH_REQUIRED)
3031 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003032 .Digest(Digest::SHA_2_256)
3033 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003034 KeyFormat::PKCS8, ec_256_key_sec1));
3035
3036 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3037 CheckCryptoParam(TAG_KEY_SIZE, 256U);
3038 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3039 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3040
3041 CheckOrigin();
3042
3043 string message(32, 'a');
3044 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3045 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003046 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003047}
3048
3049/*
3050 * ImportKeyTest.Ecdsa521Success
3051 *
3052 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3053 */
3054TEST_P(ImportKeyTest, Ecdsa521Success) {
3055 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3056 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3057 .Authorization(TAG_NO_AUTH_REQUIRED)
3058 .EcdsaSigningKey(521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003059 .Digest(Digest::SHA_2_256)
3060 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003061 KeyFormat::PKCS8, ec_521_key));
3062
3063 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3064 CheckCryptoParam(TAG_KEY_SIZE, 521U);
3065 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3066 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3067 CheckOrigin();
3068
3069 string message(32, 'a');
3070 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3071 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003072 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003073}
3074
3075/*
3076 * ImportKeyTest.EcdsaSizeMismatch
3077 *
3078 * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the
3079 * correct way.
3080 */
3081TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
3082 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3083 ImportKey(AuthorizationSetBuilder()
3084 .EcdsaSigningKey(224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003085 .Digest(Digest::NONE)
3086 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003087 KeyFormat::PKCS8, ec_256_key));
3088}
3089
3090/*
3091 * ImportKeyTest.EcdsaCurveMismatch
3092 *
3093 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3094 * the correct way.
3095 */
3096TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3097 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3098 ImportKey(AuthorizationSetBuilder()
3099 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003100 .Digest(Digest::NONE)
3101 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003102 KeyFormat::PKCS8, ec_256_key));
3103}
3104
3105/*
3106 * ImportKeyTest.AesSuccess
3107 *
3108 * Verifies that importing and using an AES key works.
3109 */
3110TEST_P(ImportKeyTest, AesSuccess) {
3111 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3112 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3113 .Authorization(TAG_NO_AUTH_REQUIRED)
3114 .AesEncryptionKey(key.size() * 8)
3115 .EcbMode()
3116 .Padding(PaddingMode::PKCS7),
3117 KeyFormat::RAW, key));
3118
3119 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3120 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3121 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3122 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3123 CheckOrigin();
3124
3125 string message = "Hello World!";
3126 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3127 string ciphertext = EncryptMessage(message, params);
3128 string plaintext = DecryptMessage(ciphertext, params);
3129 EXPECT_EQ(message, plaintext);
3130}
3131
3132/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003133 * ImportKeyTest.AesFailure
3134 *
3135 * Verifies that importing an invalid AES key fails.
3136 */
3137TEST_P(ImportKeyTest, AesFailure) {
3138 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3139 uint32_t bitlen = key.size() * 8;
3140 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003141 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003142 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003143 .Authorization(TAG_NO_AUTH_REQUIRED)
3144 .AesEncryptionKey(key_size)
3145 .EcbMode()
3146 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003147 KeyFormat::RAW, key);
3148 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003149 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3150 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003151 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003152
3153 // Explicit key size matches that of the provided key, but it's not a valid size.
3154 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3155 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3156 ImportKey(AuthorizationSetBuilder()
3157 .Authorization(TAG_NO_AUTH_REQUIRED)
3158 .AesEncryptionKey(long_key.size() * 8)
3159 .EcbMode()
3160 .Padding(PaddingMode::PKCS7),
3161 KeyFormat::RAW, long_key));
3162 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3163 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3164 ImportKey(AuthorizationSetBuilder()
3165 .Authorization(TAG_NO_AUTH_REQUIRED)
3166 .AesEncryptionKey(short_key.size() * 8)
3167 .EcbMode()
3168 .Padding(PaddingMode::PKCS7),
3169 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003170}
3171
3172/*
3173 * ImportKeyTest.TripleDesSuccess
3174 *
3175 * Verifies that importing and using a 3DES key works.
3176 */
3177TEST_P(ImportKeyTest, TripleDesSuccess) {
3178 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3179 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3180 .Authorization(TAG_NO_AUTH_REQUIRED)
3181 .TripleDesEncryptionKey(168)
3182 .EcbMode()
3183 .Padding(PaddingMode::PKCS7),
3184 KeyFormat::RAW, key));
3185
3186 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3187 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3188 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3189 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3190 CheckOrigin();
3191
3192 string message = "Hello World!";
3193 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3194 string ciphertext = EncryptMessage(message, params);
3195 string plaintext = DecryptMessage(ciphertext, params);
3196 EXPECT_EQ(message, plaintext);
3197}
3198
3199/*
3200 * ImportKeyTest.TripleDesFailure
3201 *
3202 * Verifies that importing an invalid 3DES key fails.
3203 */
3204TEST_P(ImportKeyTest, TripleDesFailure) {
3205 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3206 uint32_t bitlen = key.size() * 8;
3207 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003208 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003209 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003210 .Authorization(TAG_NO_AUTH_REQUIRED)
3211 .TripleDesEncryptionKey(key_size)
3212 .EcbMode()
3213 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003214 KeyFormat::RAW, key);
3215 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003216 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3217 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003218 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003219 // Explicit key size matches that of the provided key, but it's not a valid size.
3220 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3221 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3222 ImportKey(AuthorizationSetBuilder()
3223 .Authorization(TAG_NO_AUTH_REQUIRED)
3224 .TripleDesEncryptionKey(long_key.size() * 8)
3225 .EcbMode()
3226 .Padding(PaddingMode::PKCS7),
3227 KeyFormat::RAW, long_key));
3228 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3229 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3230 ImportKey(AuthorizationSetBuilder()
3231 .Authorization(TAG_NO_AUTH_REQUIRED)
3232 .TripleDesEncryptionKey(short_key.size() * 8)
3233 .EcbMode()
3234 .Padding(PaddingMode::PKCS7),
3235 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003236}
3237
3238/*
3239 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003240 *
3241 * Verifies that importing and using an HMAC key works.
3242 */
3243TEST_P(ImportKeyTest, HmacKeySuccess) {
3244 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3245 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3246 .Authorization(TAG_NO_AUTH_REQUIRED)
3247 .HmacKey(key.size() * 8)
3248 .Digest(Digest::SHA_2_256)
3249 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3250 KeyFormat::RAW, key));
3251
3252 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3253 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3254 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3255 CheckOrigin();
3256
3257 string message = "Hello World!";
3258 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3259 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3260}
3261
3262INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3263
3264auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003265 // IKeyMintDevice.aidl
3266 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3267 "020100" // INTEGER length 1 value 0x00 (version)
3268 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3269 "934bf94e2aa28a3f83c9f79297250262"
3270 "fbe3276b5a1c91159bbfa3ef8957aac8"
3271 "4b59b30b455a79c2973480823d8b3863"
3272 "c3deef4a8e243590268d80e18751a0e1"
3273 "30f67ce6a1ace9f79b95e097474febc9"
3274 "81195b1d13a69086c0863f66a7b7fdb4"
3275 "8792227b1ac5e2489febdf087ab54864"
3276 "83033a6f001ca5d1ec1e27f5c30f4cec"
3277 "2642074a39ae68aee552e196627a8e3d"
3278 "867e67a8c01b11e75f13cca0a97ab668"
3279 "b50cda07a8ecb7cd8e3dd7009c963653"
3280 "4f6f239cffe1fc8daa466f78b676c711"
3281 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3282 "99b801597d5220e307eaa5bee507fb94"
3283 "d1fa69f9e519b2de315bac92c36f2ea1"
3284 "fa1df4478c0ddedeae8c70e0233cd098"
3285 "040c" // OCTET STRING length 0x0c (initializationVector)
3286 "d796b02c370f1fa4cc0124f1"
3287 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3288 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3289 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3290 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3291 "3106" // SET length 0x06
3292 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3293 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3294 // } end SET
3295 // } end [1]
3296 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3297 "020120" // INTEGER length 1 value 0x20 (AES)
3298 // } end [2]
3299 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3300 "02020100" // INTEGER length 2 value 0x100
3301 // } end [3]
3302 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3303 "3103" // SET length 0x03 {
3304 "020101" // INTEGER length 1 value 0x01 (ECB)
3305 // } end SET
3306 // } end [4]
3307 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3308 "3103" // SET length 0x03 {
3309 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3310 // } end SET
3311 // } end [5]
3312 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3313 // (noAuthRequired)
3314 "0500" // NULL
3315 // } end [503]
3316 // } end SEQUENCE (AuthorizationList)
3317 // } end SEQUENCE (KeyDescription)
3318 "0420" // OCTET STRING length 0x20 (encryptedKey)
3319 "ccd540855f833a5e1480bfd2d36faf3a"
3320 "eee15df5beabe2691bc82dde2a7aa910"
3321 "0410" // OCTET STRING length 0x10 (tag)
3322 "64c9f689c60ff6223ab6e6999e0eb6e5"
3323 // } SEQUENCE (SecureKeyWrapper)
3324);
Selene Huang31ab4042020-04-29 04:22:39 -07003325
3326auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003327 // IKeyMintDevice.aidl
3328 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3329 "020100" // INTEGER length 1 value 0x00 (version)
3330 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3331 "aad93ed5924f283b4bb5526fbe7a1412"
3332 "f9d9749ec30db9062b29e574a8546f33"
3333 "c88732452f5b8e6a391ee76c39ed1712"
3334 "c61d8df6213dec1cffbc17a8c6d04c7b"
3335 "30893d8daa9b2015213e219468215532"
3336 "07f8f9931c4caba23ed3bee28b36947e"
3337 "47f10e0a5c3dc51c988a628daad3e5e1"
3338 "f4005e79c2d5a96c284b4b8d7e4948f3"
3339 "31e5b85dd5a236f85579f3ea1d1b8484"
3340 "87470bdb0ab4f81a12bee42c99fe0df4"
3341 "bee3759453e69ad1d68a809ce06b949f"
3342 "7694a990429b2fe81e066ff43e56a216"
3343 "02db70757922a4bcc23ab89f1e35da77"
3344 "586775f423e519c2ea394caf48a28d0c"
3345 "8020f1dcf6b3a68ec246f615ae96dae9"
3346 "a079b1f6eb959033c1af5c125fd94168"
3347 "040c" // OCTET STRING length 0x0c (initializationVector)
3348 "6d9721d08589581ab49204a3"
3349 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3350 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3351 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3352 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3353 "3106" // SET length 0x06
3354 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3355 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3356 // } end SET
3357 // } end [1]
3358 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3359 "020120" // INTEGER length 1 value 0x20 (AES)
3360 // } end [2]
3361 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3362 "02020100" // INTEGER length 2 value 0x100
3363 // } end [3]
3364 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3365 "3103" // SET length 0x03 {
3366 "020101" // INTEGER length 1 value 0x01 (ECB)
3367 // } end SET
3368 // } end [4]
3369 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3370 "3103" // SET length 0x03 {
3371 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3372 // } end SET
3373 // } end [5]
3374 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3375 // (noAuthRequired)
3376 "0500" // NULL
3377 // } end [503]
3378 // } end SEQUENCE (AuthorizationList)
3379 // } end SEQUENCE (KeyDescription)
3380 "0420" // OCTET STRING length 0x20 (encryptedKey)
3381 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3382 "c20d1f99a9a024a76f35c8e2cab9b68d"
3383 "0410" // OCTET STRING length 0x10 (tag)
3384 "2560c70109ae67c030f00b98b512a670"
3385 // } SEQUENCE (SecureKeyWrapper)
3386);
Selene Huang31ab4042020-04-29 04:22:39 -07003387
3388auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003389 // RFC 5208 s5
3390 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3391 "020100" // INTEGER length 1 value 0x00 (version)
3392 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3393 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3394 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3395 "0500" // NULL (parameters)
3396 // } SEQUENCE (AlgorithmIdentifier)
3397 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3398 // RFC 8017 A.1.2
3399 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3400 "020100" // INTEGER length 1 value 0x00 (version)
3401 "02820101" // INTEGER length 0x0101 (modulus) value...
3402 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3403 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3404 "7b06e673a837313d56b1c725150a3fef" // 0x30
3405 "86acbddc41bb759c2854eae32d35841e" // 0x40
3406 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3407 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3408 "312d7bd5921ffaea1347c157406fef71" // 0x70
3409 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3410 "f4645c11f5c1374c3886427411c44979" // 0x90
3411 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3412 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3413 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3414 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3415 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3416 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3417 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3418 "55" // 0x101
3419 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3420 "02820100" // INTEGER length 0x100 (privateExponent) value...
3421 "431447b6251908112b1ee76f99f3711a" // 0x10
3422 "52b6630960046c2de70de188d833f8b8" // 0x20
3423 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3424 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3425 "e710b630a03adc683b5d2c43080e52be" // 0x50
3426 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3427 "822bccff087d63c940ba8a45f670feb2" // 0x70
3428 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3429 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3430 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3431 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3432 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3433 "52659d5a5ba05b663737a8696281865b" // 0xd0
3434 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3435 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3436 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3437 "028181" // INTEGER length 0x81 (prime1) value...
3438 "00de392e18d682c829266cc3454e1d61" // 0x10
3439 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3440 "ff841be5bac82a164c5970007047b8c5" // 0x30
3441 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3442 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3443 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3444 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3445 "9e91346130748a6e3c124f9149d71c74" // 0x80
3446 "35"
3447 "028181" // INTEGER length 0x81 (prime2) value...
3448 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3449 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3450 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3451 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3452 "9ed39a2d934c880440aed8832f984316" // 0x50
3453 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3454 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3455 "b880677c068e1be936e81288815252a8" // 0x80
3456 "a1"
3457 "028180" // INTEGER length 0x80 (exponent1) value...
3458 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3459 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3460 "5a063212a4f105a3764743e53281988a" // 0x30
3461 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3462 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3463 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3464 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3465 "4719d6e2b9439823719cd08bcd031781" // 0x80
3466 "028181" // INTEGER length 0x81 (exponent2) value...
3467 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3468 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3469 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3470 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3471 "1254186af30b22c10582a8a43e34fe94" // 0x50
3472 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3473 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3474 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3475 "61"
3476 "028181" // INTEGER length 0x81 (coefficient) value...
3477 "00c931617c77829dfb1270502be9195c" // 0x10
3478 "8f2830885f57dba869536811e6864236" // 0x20
3479 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3480 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3481 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3482 "959356210723287b0affcc9f727044d4" // 0x60
3483 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3484 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3485 "22"
3486 // } SEQUENCE
3487 // } SEQUENCE ()
3488);
Selene Huang31ab4042020-04-29 04:22:39 -07003489
3490string zero_masking_key =
3491 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3492string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3493
3494class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3495
3496TEST_P(ImportWrappedKeyTest, Success) {
3497 auto wrapping_key_desc = AuthorizationSetBuilder()
3498 .RsaEncryptionKey(2048, 65537)
3499 .Digest(Digest::SHA_2_256)
3500 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003501 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3502 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003503
3504 ASSERT_EQ(ErrorCode::OK,
3505 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3506 AuthorizationSetBuilder()
3507 .Digest(Digest::SHA_2_256)
3508 .Padding(PaddingMode::RSA_OAEP)));
3509
3510 string message = "Hello World!";
3511 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3512 string ciphertext = EncryptMessage(message, params);
3513 string plaintext = DecryptMessage(ciphertext, params);
3514 EXPECT_EQ(message, plaintext);
3515}
3516
David Drysdaled2cc8c22021-04-15 13:29:45 +01003517/*
3518 * ImportWrappedKeyTest.SuccessSidsIgnored
3519 *
3520 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3521 * include Tag:USER_SECURE_ID.
3522 */
3523TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3524 auto wrapping_key_desc = AuthorizationSetBuilder()
3525 .RsaEncryptionKey(2048, 65537)
3526 .Digest(Digest::SHA_2_256)
3527 .Padding(PaddingMode::RSA_OAEP)
3528 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3529 .SetDefaultValidity();
3530
3531 int64_t password_sid = 42;
3532 int64_t biometric_sid = 24;
3533 ASSERT_EQ(ErrorCode::OK,
3534 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3535 AuthorizationSetBuilder()
3536 .Digest(Digest::SHA_2_256)
3537 .Padding(PaddingMode::RSA_OAEP),
3538 password_sid, biometric_sid));
3539
3540 string message = "Hello World!";
3541 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3542 string ciphertext = EncryptMessage(message, params);
3543 string plaintext = DecryptMessage(ciphertext, params);
3544 EXPECT_EQ(message, plaintext);
3545}
3546
Selene Huang31ab4042020-04-29 04:22:39 -07003547TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3548 auto wrapping_key_desc = AuthorizationSetBuilder()
3549 .RsaEncryptionKey(2048, 65537)
3550 .Digest(Digest::SHA_2_256)
3551 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003552 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3553 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003554
3555 ASSERT_EQ(ErrorCode::OK,
3556 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3557 AuthorizationSetBuilder()
3558 .Digest(Digest::SHA_2_256)
3559 .Padding(PaddingMode::RSA_OAEP)));
3560}
3561
3562TEST_P(ImportWrappedKeyTest, WrongMask) {
3563 auto wrapping_key_desc = AuthorizationSetBuilder()
3564 .RsaEncryptionKey(2048, 65537)
3565 .Digest(Digest::SHA_2_256)
3566 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003567 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3568 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003569
3570 ASSERT_EQ(
3571 ErrorCode::VERIFICATION_FAILED,
3572 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3573 AuthorizationSetBuilder()
3574 .Digest(Digest::SHA_2_256)
3575 .Padding(PaddingMode::RSA_OAEP)));
3576}
3577
3578TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3579 auto wrapping_key_desc = AuthorizationSetBuilder()
3580 .RsaEncryptionKey(2048, 65537)
3581 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003582 .Padding(PaddingMode::RSA_OAEP)
3583 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003584
3585 ASSERT_EQ(
3586 ErrorCode::INCOMPATIBLE_PURPOSE,
3587 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3588 AuthorizationSetBuilder()
3589 .Digest(Digest::SHA_2_256)
3590 .Padding(PaddingMode::RSA_OAEP)));
3591}
3592
David Drysdaled2cc8c22021-04-15 13:29:45 +01003593TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3594 auto wrapping_key_desc = AuthorizationSetBuilder()
3595 .RsaEncryptionKey(2048, 65537)
3596 .Digest(Digest::SHA_2_256)
3597 .Padding(PaddingMode::RSA_PSS)
3598 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3599 .SetDefaultValidity();
3600
3601 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3602 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3603 AuthorizationSetBuilder()
3604 .Digest(Digest::SHA_2_256)
3605 .Padding(PaddingMode::RSA_OAEP)));
3606}
3607
3608TEST_P(ImportWrappedKeyTest, WrongDigest) {
3609 auto wrapping_key_desc = AuthorizationSetBuilder()
3610 .RsaEncryptionKey(2048, 65537)
3611 .Digest(Digest::SHA_2_512)
3612 .Padding(PaddingMode::RSA_OAEP)
3613 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3614 .SetDefaultValidity();
3615
3616 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3617 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3618 AuthorizationSetBuilder()
3619 .Digest(Digest::SHA_2_256)
3620 .Padding(PaddingMode::RSA_OAEP)));
3621}
3622
Selene Huang31ab4042020-04-29 04:22:39 -07003623INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3624
3625typedef KeyMintAidlTestBase EncryptionOperationsTest;
3626
3627/*
3628 * EncryptionOperationsTest.RsaNoPaddingSuccess
3629 *
3630 * Verifies that raw RSA encryption works.
3631 */
3632TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003633 for (uint64_t exponent : {3, 65537}) {
3634 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3635 .Authorization(TAG_NO_AUTH_REQUIRED)
3636 .RsaEncryptionKey(2048, exponent)
3637 .Padding(PaddingMode::NONE)
3638 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003639
David Drysdaled2cc8c22021-04-15 13:29:45 +01003640 string message = string(2048 / 8, 'a');
3641 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3642 string ciphertext1 = EncryptMessage(message, params);
3643 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003644
David Drysdaled2cc8c22021-04-15 13:29:45 +01003645 string ciphertext2 = EncryptMessage(message, params);
3646 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003647
David Drysdaled2cc8c22021-04-15 13:29:45 +01003648 // Unpadded RSA is deterministic
3649 EXPECT_EQ(ciphertext1, ciphertext2);
3650
3651 CheckedDeleteKey();
3652 }
Selene Huang31ab4042020-04-29 04:22:39 -07003653}
3654
3655/*
3656 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3657 *
3658 * Verifies that raw RSA encryption of short messages works.
3659 */
3660TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3661 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3662 .Authorization(TAG_NO_AUTH_REQUIRED)
3663 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003664 .Padding(PaddingMode::NONE)
3665 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003666
3667 string message = "1";
3668 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3669
3670 string ciphertext = EncryptMessage(message, params);
3671 EXPECT_EQ(2048U / 8, ciphertext.size());
3672
3673 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3674 string plaintext = DecryptMessage(ciphertext, params);
3675
3676 EXPECT_EQ(expected_plaintext, plaintext);
3677
3678 // Degenerate case, encrypting a numeric 1 yields 0x00..01 as the ciphertext.
3679 message = static_cast<char>(1);
3680 ciphertext = EncryptMessage(message, params);
3681 EXPECT_EQ(2048U / 8, ciphertext.size());
3682 EXPECT_EQ(ciphertext, string(2048U / 8 - 1, 0) + message);
3683}
3684
3685/*
3686 * EncryptionOperationsTest.RsaNoPaddingTooLong
3687 *
3688 * Verifies that raw RSA encryption of too-long messages fails in the expected way.
3689 */
3690TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
3691 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3692 .Authorization(TAG_NO_AUTH_REQUIRED)
3693 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003694 .Padding(PaddingMode::NONE)
3695 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003696
3697 string message(2048 / 8 + 1, 'a');
3698
3699 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3700 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3701
3702 string result;
3703 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
3704}
3705
3706/*
3707 * EncryptionOperationsTest.RsaNoPaddingTooLarge
3708 *
3709 * Verifies that raw RSA encryption of too-large (numerically) messages fails in the expected
3710 * way.
3711 */
3712// TODO(seleneh) add RsaNoPaddingTooLarge test back after decided and implemented new
3713// version of ExportKey inside generateKey
3714
3715/*
3716 * EncryptionOperationsTest.RsaOaepSuccess
3717 *
3718 * Verifies that RSA-OAEP encryption operations work, with all digests.
3719 */
3720TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3721 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3722
3723 size_t key_size = 2048; // Need largish key for SHA-512 test.
3724 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3725 .Authorization(TAG_NO_AUTH_REQUIRED)
3726 .RsaEncryptionKey(key_size, 65537)
3727 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003728 .Digest(digests)
3729 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003730
3731 string message = "Hello";
3732
3733 for (auto digest : digests) {
3734 auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP);
3735 string ciphertext1 = EncryptMessage(message, params);
3736 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3737 EXPECT_EQ(key_size / 8, ciphertext1.size());
3738
3739 string ciphertext2 = EncryptMessage(message, params);
3740 EXPECT_EQ(key_size / 8, ciphertext2.size());
3741
3742 // OAEP randomizes padding so every result should be different (with astronomically high
3743 // probability).
3744 EXPECT_NE(ciphertext1, ciphertext2);
3745
3746 string plaintext1 = DecryptMessage(ciphertext1, params);
3747 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3748 string plaintext2 = DecryptMessage(ciphertext2, params);
3749 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3750
3751 // Decrypting corrupted ciphertext should fail.
3752 size_t offset_to_corrupt = random() % ciphertext1.size();
3753 char corrupt_byte;
3754 do {
3755 corrupt_byte = static_cast<char>(random() % 256);
3756 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3757 ciphertext1[offset_to_corrupt] = corrupt_byte;
3758
3759 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3760 string result;
3761 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3762 EXPECT_EQ(0U, result.size());
3763 }
3764}
3765
3766/*
3767 * EncryptionOperationsTest.RsaOaepInvalidDigest
3768 *
3769 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3770 * without a digest.
3771 */
3772TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3773 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3774 .Authorization(TAG_NO_AUTH_REQUIRED)
3775 .RsaEncryptionKey(2048, 65537)
3776 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003777 .Digest(Digest::NONE)
3778 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003779
3780 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
3781 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3782}
3783
3784/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003785 * EncryptionOperationsTest.RsaOaepInvalidPadding
3786 *
3787 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3788 * with a padding value that is only suitable for signing/verifying.
3789 */
3790TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3791 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3792 .Authorization(TAG_NO_AUTH_REQUIRED)
3793 .RsaEncryptionKey(2048, 65537)
3794 .Padding(PaddingMode::RSA_PSS)
3795 .Digest(Digest::NONE)
3796 .SetDefaultValidity()));
3797
3798 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
3799 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3800}
3801
3802/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003803 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003804 *
3805 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt
3806 * with a different digest than was used to encrypt.
3807 */
3808TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3809 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3810
3811 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3812 .Authorization(TAG_NO_AUTH_REQUIRED)
3813 .RsaEncryptionKey(1024, 65537)
3814 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003815 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3816 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003817 string message = "Hello World!";
3818 string ciphertext = EncryptMessage(
3819 message,
3820 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3821
3822 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3823 .Digest(Digest::SHA_2_256)
3824 .Padding(PaddingMode::RSA_OAEP)));
3825 string result;
3826 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3827 EXPECT_EQ(0U, result.size());
3828}
3829
3830/*
3831 * EncryptionOperationsTest.RsaOaepTooLarge
3832 *
3833 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a
3834 * too-large message.
3835 */
3836TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
3837 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3838 .Authorization(TAG_NO_AUTH_REQUIRED)
3839 .RsaEncryptionKey(2048, 65537)
3840 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003841 .Digest(Digest::SHA_2_256)
3842 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003843 constexpr size_t digest_size = 256 /* SHA_2_256 */ / 8;
3844 constexpr size_t oaep_overhead = 2 * digest_size + 2;
3845 string message(2048 / 8 - oaep_overhead + 1, 'a');
3846 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
3847 .Padding(PaddingMode::RSA_OAEP)
3848 .Digest(Digest::SHA_2_256)));
3849 string result;
3850 ErrorCode error = Finish(message, &result);
3851 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
3852 EXPECT_EQ(0U, result.size());
3853}
3854
3855/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003856 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3857 *
3858 * Verifies that RSA-OAEP encryption operations work, with all SHA 256 digests and all type of MGF1
3859 * digests.
3860 */
3861TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3862 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3863
3864 size_t key_size = 2048; // Need largish key for SHA-512 test.
3865 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3866 .OaepMGFDigest(digests)
3867 .Authorization(TAG_NO_AUTH_REQUIRED)
3868 .RsaEncryptionKey(key_size, 65537)
3869 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003870 .Digest(Digest::SHA_2_256)
3871 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003872
3873 string message = "Hello";
3874
3875 for (auto digest : digests) {
3876 auto params = AuthorizationSetBuilder()
3877 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
3878 .Digest(Digest::SHA_2_256)
3879 .Padding(PaddingMode::RSA_OAEP);
3880 string ciphertext1 = EncryptMessage(message, params);
3881 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3882 EXPECT_EQ(key_size / 8, ciphertext1.size());
3883
3884 string ciphertext2 = EncryptMessage(message, params);
3885 EXPECT_EQ(key_size / 8, ciphertext2.size());
3886
3887 // OAEP randomizes padding so every result should be different (with astronomically high
3888 // probability).
3889 EXPECT_NE(ciphertext1, ciphertext2);
3890
3891 string plaintext1 = DecryptMessage(ciphertext1, params);
3892 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3893 string plaintext2 = DecryptMessage(ciphertext2, params);
3894 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3895
3896 // Decrypting corrupted ciphertext should fail.
3897 size_t offset_to_corrupt = random() % ciphertext1.size();
3898 char corrupt_byte;
3899 do {
3900 corrupt_byte = static_cast<char>(random() % 256);
3901 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3902 ciphertext1[offset_to_corrupt] = corrupt_byte;
3903
3904 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3905 string result;
3906 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3907 EXPECT_EQ(0U, result.size());
3908 }
3909}
3910
3911/*
3912 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
3913 *
3914 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3915 * with incompatible MGF digest.
3916 */
3917TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
3918 ASSERT_EQ(ErrorCode::OK,
3919 GenerateKey(AuthorizationSetBuilder()
3920 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3921 .Authorization(TAG_NO_AUTH_REQUIRED)
3922 .RsaEncryptionKey(2048, 65537)
3923 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003924 .Digest(Digest::SHA_2_256)
3925 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003926 string message = "Hello World!";
3927
3928 auto params = AuthorizationSetBuilder()
3929 .Padding(PaddingMode::RSA_OAEP)
3930 .Digest(Digest::SHA_2_256)
3931 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
3932 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3933}
3934
3935/*
3936 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
3937 *
3938 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3939 * with unsupported MGF digest.
3940 */
3941TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
3942 ASSERT_EQ(ErrorCode::OK,
3943 GenerateKey(AuthorizationSetBuilder()
3944 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3945 .Authorization(TAG_NO_AUTH_REQUIRED)
3946 .RsaEncryptionKey(2048, 65537)
3947 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003948 .Digest(Digest::SHA_2_256)
3949 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003950 string message = "Hello World!";
3951
3952 auto params = AuthorizationSetBuilder()
3953 .Padding(PaddingMode::RSA_OAEP)
3954 .Digest(Digest::SHA_2_256)
3955 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
3956 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3957}
3958
3959/*
Selene Huang31ab4042020-04-29 04:22:39 -07003960 * EncryptionOperationsTest.RsaPkcs1Success
3961 *
3962 * Verifies that RSA PKCS encryption/decrypts works.
3963 */
3964TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
3965 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3966 .Authorization(TAG_NO_AUTH_REQUIRED)
3967 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003968 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
3969 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003970
3971 string message = "Hello World!";
3972 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
3973 string ciphertext1 = EncryptMessage(message, params);
3974 EXPECT_EQ(2048U / 8, ciphertext1.size());
3975
3976 string ciphertext2 = EncryptMessage(message, params);
3977 EXPECT_EQ(2048U / 8, ciphertext2.size());
3978
3979 // PKCS1 v1.5 randomizes padding so every result should be different.
3980 EXPECT_NE(ciphertext1, ciphertext2);
3981
3982 string plaintext = DecryptMessage(ciphertext1, params);
3983 EXPECT_EQ(message, plaintext);
3984
3985 // Decrypting corrupted ciphertext should fail.
3986 size_t offset_to_corrupt = random() % ciphertext1.size();
3987 char corrupt_byte;
3988 do {
3989 corrupt_byte = static_cast<char>(random() % 256);
3990 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3991 ciphertext1[offset_to_corrupt] = corrupt_byte;
3992
3993 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3994 string result;
3995 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3996 EXPECT_EQ(0U, result.size());
3997}
3998
3999/*
4000 * EncryptionOperationsTest.RsaPkcs1TooLarge
4001 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01004002 * Verifies that RSA PKCS encryption fails in the correct way when the message is too large.
Selene Huang31ab4042020-04-29 04:22:39 -07004003 */
4004TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
4005 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4006 .Authorization(TAG_NO_AUTH_REQUIRED)
4007 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004008 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4009 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004010 string message(2048 / 8 - 10, 'a');
4011
4012 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
4013 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
4014 string result;
4015 ErrorCode error = Finish(message, &result);
4016 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
4017 EXPECT_EQ(0U, result.size());
4018}
4019
4020/*
4021 * EncryptionOperationsTest.EcdsaEncrypt
4022 *
4023 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4024 */
4025TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4026 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4027 .Authorization(TAG_NO_AUTH_REQUIRED)
4028 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004029 .Digest(Digest::NONE)
4030 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004031 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4032 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4033 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4034}
4035
4036/*
4037 * EncryptionOperationsTest.HmacEncrypt
4038 *
4039 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4040 */
4041TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4042 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4043 .Authorization(TAG_NO_AUTH_REQUIRED)
4044 .HmacKey(128)
4045 .Digest(Digest::SHA_2_256)
4046 .Padding(PaddingMode::NONE)
4047 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4048 auto params = AuthorizationSetBuilder()
4049 .Digest(Digest::SHA_2_256)
4050 .Padding(PaddingMode::NONE)
4051 .Authorization(TAG_MAC_LENGTH, 128);
4052 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4053 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4054}
4055
4056/*
4057 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4058 *
4059 * Verifies that AES ECB mode works.
4060 */
4061TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4062 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4063 .Authorization(TAG_NO_AUTH_REQUIRED)
4064 .AesEncryptionKey(128)
4065 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4066 .Padding(PaddingMode::NONE)));
4067
4068 ASSERT_GT(key_blob_.size(), 0U);
4069 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4070
4071 // Two-block message.
4072 string message = "12345678901234567890123456789012";
4073 string ciphertext1 = EncryptMessage(message, params);
4074 EXPECT_EQ(message.size(), ciphertext1.size());
4075
4076 string ciphertext2 = EncryptMessage(string(message), params);
4077 EXPECT_EQ(message.size(), ciphertext2.size());
4078
4079 // ECB is deterministic.
4080 EXPECT_EQ(ciphertext1, ciphertext2);
4081
4082 string plaintext = DecryptMessage(ciphertext1, params);
4083 EXPECT_EQ(message, plaintext);
4084}
4085
4086/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004087 * EncryptionOperationsTest.AesEcbUnknownTag
4088 *
4089 * Verifies that AES ECB operations ignore unknown tags.
4090 */
4091TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4092 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4093 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4094 KeyParameter unknown_param;
4095 unknown_param.tag = unknown_tag;
4096
4097 vector<KeyCharacteristics> key_characteristics;
4098 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4099 .Authorization(TAG_NO_AUTH_REQUIRED)
4100 .AesEncryptionKey(128)
4101 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4102 .Padding(PaddingMode::NONE)
4103 .Authorization(unknown_param),
4104 &key_blob_, &key_characteristics));
4105 ASSERT_GT(key_blob_.size(), 0U);
4106
4107 // Unknown tags should not be returned in key characteristics.
4108 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4109 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4110 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4111 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4112
4113 // Encrypt without mentioning the unknown parameter.
4114 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4115 string message = "12345678901234567890123456789012";
4116 string ciphertext = EncryptMessage(message, params);
4117 EXPECT_EQ(message.size(), ciphertext.size());
4118
4119 // Decrypt including the unknown parameter.
4120 auto decrypt_params = AuthorizationSetBuilder()
4121 .BlockMode(BlockMode::ECB)
4122 .Padding(PaddingMode::NONE)
4123 .Authorization(unknown_param);
4124 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4125 EXPECT_EQ(message, plaintext);
4126}
4127
4128/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004129 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004130 *
4131 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4132 */
4133TEST_P(EncryptionOperationsTest, AesWrongMode) {
4134 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4135 .Authorization(TAG_NO_AUTH_REQUIRED)
4136 .AesEncryptionKey(128)
4137 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4138 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004139 ASSERT_GT(key_blob_.size(), 0U);
4140
Selene Huang31ab4042020-04-29 04:22:39 -07004141 EXPECT_EQ(
4142 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4143 Begin(KeyPurpose::ENCRYPT,
4144 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4145}
4146
4147/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004148 * EncryptionOperationsTest.AesWrongPadding
4149 *
4150 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4151 */
4152TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4153 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4154 .Authorization(TAG_NO_AUTH_REQUIRED)
4155 .AesEncryptionKey(128)
4156 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4157 .Padding(PaddingMode::NONE)));
4158 ASSERT_GT(key_blob_.size(), 0U);
4159
4160 EXPECT_EQ(
4161 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4162 Begin(KeyPurpose::ENCRYPT,
4163 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4164}
4165
4166/*
4167 * EncryptionOperationsTest.AesInvalidParams
4168 *
4169 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4170 */
4171TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4172 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4173 .Authorization(TAG_NO_AUTH_REQUIRED)
4174 .AesEncryptionKey(128)
4175 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4176 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4177 .Padding(PaddingMode::NONE)
4178 .Padding(PaddingMode::PKCS7)));
4179 ASSERT_GT(key_blob_.size(), 0U);
4180
4181 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4182 .BlockMode(BlockMode::CBC)
4183 .BlockMode(BlockMode::ECB)
4184 .Padding(PaddingMode::NONE));
4185 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4186 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4187
4188 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4189 .BlockMode(BlockMode::ECB)
4190 .Padding(PaddingMode::NONE)
4191 .Padding(PaddingMode::PKCS7));
4192 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4193 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4194}
4195
4196/*
Selene Huang31ab4042020-04-29 04:22:39 -07004197 * EncryptionOperationsTest.AesWrongPurpose
4198 *
4199 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4200 * specified.
4201 */
4202TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4203 auto err = GenerateKey(AuthorizationSetBuilder()
4204 .Authorization(TAG_NO_AUTH_REQUIRED)
4205 .AesKey(128)
4206 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4207 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4208 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4209 .Padding(PaddingMode::NONE));
4210 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4211 ASSERT_GT(key_blob_.size(), 0U);
4212
4213 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4214 .BlockMode(BlockMode::GCM)
4215 .Padding(PaddingMode::NONE)
4216 .Authorization(TAG_MAC_LENGTH, 128));
4217 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4218
4219 CheckedDeleteKey();
4220
4221 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4222 .Authorization(TAG_NO_AUTH_REQUIRED)
4223 .AesKey(128)
4224 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4225 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4226 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4227 .Padding(PaddingMode::NONE)));
4228
4229 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4230 .BlockMode(BlockMode::GCM)
4231 .Padding(PaddingMode::NONE)
4232 .Authorization(TAG_MAC_LENGTH, 128));
4233 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4234}
4235
4236/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004237 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004238 *
4239 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4240 * multiple of the block size and no padding is specified.
4241 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004242TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4243 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4244 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4245 .Authorization(TAG_NO_AUTH_REQUIRED)
4246 .AesEncryptionKey(128)
4247 .Authorization(TAG_BLOCK_MODE, blockMode)
4248 .Padding(PaddingMode::NONE)));
4249 // Message is slightly shorter than two blocks.
4250 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004251
David Drysdaled2cc8c22021-04-15 13:29:45 +01004252 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4253 AuthorizationSet out_params;
4254 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4255 string ciphertext;
4256 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4257 EXPECT_EQ(0U, ciphertext.size());
4258
4259 CheckedDeleteKey();
4260 }
Selene Huang31ab4042020-04-29 04:22:39 -07004261}
4262
4263/*
4264 * EncryptionOperationsTest.AesEcbPkcs7Padding
4265 *
4266 * Verifies that AES PKCS7 padding works for any message length.
4267 */
4268TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4269 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4270 .Authorization(TAG_NO_AUTH_REQUIRED)
4271 .AesEncryptionKey(128)
4272 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4273 .Padding(PaddingMode::PKCS7)));
4274
4275 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4276
4277 // Try various message lengths; all should work.
4278 for (size_t i = 0; i < 32; ++i) {
4279 string message(i, 'a');
4280 string ciphertext = EncryptMessage(message, params);
4281 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4282 string plaintext = DecryptMessage(ciphertext, params);
4283 EXPECT_EQ(message, plaintext);
4284 }
4285}
4286
4287/*
4288 * EncryptionOperationsTest.AesEcbWrongPadding
4289 *
4290 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4291 * specified.
4292 */
4293TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4294 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4295 .Authorization(TAG_NO_AUTH_REQUIRED)
4296 .AesEncryptionKey(128)
4297 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4298 .Padding(PaddingMode::NONE)));
4299
4300 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4301
4302 // Try various message lengths; all should fail
4303 for (size_t i = 0; i < 32; ++i) {
4304 string message(i, 'a');
4305 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4306 }
4307}
4308
4309/*
4310 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4311 *
4312 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4313 */
4314TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4315 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4316 .Authorization(TAG_NO_AUTH_REQUIRED)
4317 .AesEncryptionKey(128)
4318 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4319 .Padding(PaddingMode::PKCS7)));
4320
4321 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4322
4323 string message = "a";
4324 string ciphertext = EncryptMessage(message, params);
4325 EXPECT_EQ(16U, ciphertext.size());
4326 EXPECT_NE(ciphertext, message);
4327 ++ciphertext[ciphertext.size() / 2];
4328
4329 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4330 string plaintext;
4331 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
4332}
4333
4334vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4335 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004336 EXPECT_TRUE(iv);
4337 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004338}
4339
4340/*
4341 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4342 *
4343 * Verifies that AES CTR mode works.
4344 */
4345TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4346 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4347 .Authorization(TAG_NO_AUTH_REQUIRED)
4348 .AesEncryptionKey(128)
4349 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4350 .Padding(PaddingMode::NONE)));
4351
4352 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4353
4354 string message = "123";
4355 AuthorizationSet out_params;
4356 string ciphertext1 = EncryptMessage(message, params, &out_params);
4357 vector<uint8_t> iv1 = CopyIv(out_params);
4358 EXPECT_EQ(16U, iv1.size());
4359
4360 EXPECT_EQ(message.size(), ciphertext1.size());
4361
4362 out_params.Clear();
4363 string ciphertext2 = EncryptMessage(message, params, &out_params);
4364 vector<uint8_t> iv2 = CopyIv(out_params);
4365 EXPECT_EQ(16U, iv2.size());
4366
4367 // IVs should be random, so ciphertexts should differ.
4368 EXPECT_NE(ciphertext1, ciphertext2);
4369
4370 auto params_iv1 =
4371 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4372 auto params_iv2 =
4373 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4374
4375 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4376 EXPECT_EQ(message, plaintext);
4377 plaintext = DecryptMessage(ciphertext2, params_iv2);
4378 EXPECT_EQ(message, plaintext);
4379
4380 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4381 plaintext = DecryptMessage(ciphertext1, params_iv2);
4382 EXPECT_NE(message, plaintext);
4383 plaintext = DecryptMessage(ciphertext2, params_iv1);
4384 EXPECT_NE(message, plaintext);
4385}
4386
4387/*
4388 * EncryptionOperationsTest.AesIncremental
4389 *
4390 * Verifies that AES works, all modes, when provided data in various size increments.
4391 */
4392TEST_P(EncryptionOperationsTest, AesIncremental) {
4393 auto block_modes = {
4394 BlockMode::ECB,
4395 BlockMode::CBC,
4396 BlockMode::CTR,
4397 BlockMode::GCM,
4398 };
4399
4400 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4401 .Authorization(TAG_NO_AUTH_REQUIRED)
4402 .AesEncryptionKey(128)
4403 .BlockMode(block_modes)
4404 .Padding(PaddingMode::NONE)
4405 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4406
4407 for (int increment = 1; increment <= 240; ++increment) {
4408 for (auto block_mode : block_modes) {
4409 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004410 auto params =
4411 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4412 if (block_mode == BlockMode::GCM) {
4413 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4414 }
Selene Huang31ab4042020-04-29 04:22:39 -07004415
4416 AuthorizationSet output_params;
4417 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4418
4419 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004420 string to_send;
4421 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004422 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004423 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004424 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4425 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004426
4427 switch (block_mode) {
4428 case BlockMode::GCM:
4429 EXPECT_EQ(message.size() + 16, ciphertext.size());
4430 break;
4431 case BlockMode::CTR:
4432 EXPECT_EQ(message.size(), ciphertext.size());
4433 break;
4434 case BlockMode::CBC:
4435 case BlockMode::ECB:
4436 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4437 break;
4438 }
4439
4440 auto iv = output_params.GetTagValue(TAG_NONCE);
4441 switch (block_mode) {
4442 case BlockMode::CBC:
4443 case BlockMode::GCM:
4444 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004445 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4446 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4447 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004448 break;
4449
4450 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004451 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004452 break;
4453 }
4454
4455 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4456 << "Decrypt begin() failed for block mode " << block_mode;
4457
4458 string plaintext;
4459 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004460 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004461 }
4462 ErrorCode error = Finish(to_send, &plaintext);
4463 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4464 << " and increment " << increment;
4465 if (error == ErrorCode::OK) {
4466 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4467 << block_mode << " and increment " << increment;
4468 }
4469 }
4470 }
4471}
4472
4473struct AesCtrSp80038aTestVector {
4474 const char* key;
4475 const char* nonce;
4476 const char* plaintext;
4477 const char* ciphertext;
4478};
4479
4480// These test vectors are taken from
4481// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4482static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4483 // AES-128
4484 {
4485 "2b7e151628aed2a6abf7158809cf4f3c",
4486 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4487 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4488 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4489 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4490 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4491 },
4492 // AES-192
4493 {
4494 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4495 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4496 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4497 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4498 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4499 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4500 },
4501 // AES-256
4502 {
4503 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4504 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4505 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4506 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4507 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4508 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4509 },
4510};
4511
4512/*
4513 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4514 *
4515 * Verifies AES CTR implementation against SP800-38A test vectors.
4516 */
4517TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4518 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4519 for (size_t i = 0; i < 3; i++) {
4520 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4521 const string key = hex2str(test.key);
4522 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4523 InvalidSizes.end())
4524 continue;
4525 const string nonce = hex2str(test.nonce);
4526 const string plaintext = hex2str(test.plaintext);
4527 const string ciphertext = hex2str(test.ciphertext);
4528 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4529 }
4530}
4531
4532/*
4533 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4534 *
4535 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4536 */
4537TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4538 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4539 .Authorization(TAG_NO_AUTH_REQUIRED)
4540 .AesEncryptionKey(128)
4541 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4542 .Padding(PaddingMode::PKCS7)));
4543 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4544 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4545}
4546
4547/*
4548 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4549 *
4550 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4551 */
4552TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4553 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4554 .Authorization(TAG_NO_AUTH_REQUIRED)
4555 .AesEncryptionKey(128)
4556 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4557 .Authorization(TAG_CALLER_NONCE)
4558 .Padding(PaddingMode::NONE)));
4559
4560 auto params = AuthorizationSetBuilder()
4561 .BlockMode(BlockMode::CTR)
4562 .Padding(PaddingMode::NONE)
4563 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4564 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4565
4566 params = AuthorizationSetBuilder()
4567 .BlockMode(BlockMode::CTR)
4568 .Padding(PaddingMode::NONE)
4569 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4570 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4571
4572 params = AuthorizationSetBuilder()
4573 .BlockMode(BlockMode::CTR)
4574 .Padding(PaddingMode::NONE)
4575 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4576 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4577}
4578
4579/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004580 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004581 *
4582 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4583 */
4584TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4585 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4586 .Authorization(TAG_NO_AUTH_REQUIRED)
4587 .AesEncryptionKey(128)
4588 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4589 .Padding(PaddingMode::NONE)));
4590 // Two-block message.
4591 string message = "12345678901234567890123456789012";
4592 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4593 AuthorizationSet out_params;
4594 string ciphertext1 = EncryptMessage(message, params, &out_params);
4595 vector<uint8_t> iv1 = CopyIv(out_params);
4596 EXPECT_EQ(message.size(), ciphertext1.size());
4597
4598 out_params.Clear();
4599
4600 string ciphertext2 = EncryptMessage(message, params, &out_params);
4601 vector<uint8_t> iv2 = CopyIv(out_params);
4602 EXPECT_EQ(message.size(), ciphertext2.size());
4603
4604 // IVs should be random, so ciphertexts should differ.
4605 EXPECT_NE(ciphertext1, ciphertext2);
4606
4607 params.push_back(TAG_NONCE, iv1);
4608 string plaintext = DecryptMessage(ciphertext1, params);
4609 EXPECT_EQ(message, plaintext);
4610}
4611
4612/*
4613 * EncryptionOperationsTest.AesCallerNonce
4614 *
4615 * Verifies that AES caller-provided nonces work correctly.
4616 */
4617TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4618 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4619 .Authorization(TAG_NO_AUTH_REQUIRED)
4620 .AesEncryptionKey(128)
4621 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4622 .Authorization(TAG_CALLER_NONCE)
4623 .Padding(PaddingMode::NONE)));
4624
4625 string message = "12345678901234567890123456789012";
4626
4627 // Don't specify nonce, should get a random one.
4628 AuthorizationSetBuilder params =
4629 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4630 AuthorizationSet out_params;
4631 string ciphertext = EncryptMessage(message, params, &out_params);
4632 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004633 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004634
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004635 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004636 string plaintext = DecryptMessage(ciphertext, params);
4637 EXPECT_EQ(message, plaintext);
4638
4639 // Now specify a nonce, should also work.
4640 params = AuthorizationSetBuilder()
4641 .BlockMode(BlockMode::CBC)
4642 .Padding(PaddingMode::NONE)
4643 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4644 out_params.Clear();
4645 ciphertext = EncryptMessage(message, params, &out_params);
4646
4647 // Decrypt with correct nonce.
4648 plaintext = DecryptMessage(ciphertext, params);
4649 EXPECT_EQ(message, plaintext);
4650
4651 // Try with wrong nonce.
4652 params = AuthorizationSetBuilder()
4653 .BlockMode(BlockMode::CBC)
4654 .Padding(PaddingMode::NONE)
4655 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4656 plaintext = DecryptMessage(ciphertext, params);
4657 EXPECT_NE(message, plaintext);
4658}
4659
4660/*
4661 * EncryptionOperationsTest.AesCallerNonceProhibited
4662 *
4663 * Verifies that caller-provided nonces are not permitted when not specified in the key
4664 * authorizations.
4665 */
4666TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4667 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4668 .Authorization(TAG_NO_AUTH_REQUIRED)
4669 .AesEncryptionKey(128)
4670 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4671 .Padding(PaddingMode::NONE)));
4672
4673 string message = "12345678901234567890123456789012";
4674
4675 // Don't specify nonce, should get a random one.
4676 AuthorizationSetBuilder params =
4677 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4678 AuthorizationSet out_params;
4679 string ciphertext = EncryptMessage(message, params, &out_params);
4680 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004681 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004682
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004683 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004684 string plaintext = DecryptMessage(ciphertext, params);
4685 EXPECT_EQ(message, plaintext);
4686
4687 // Now specify a nonce, should fail
4688 params = AuthorizationSetBuilder()
4689 .BlockMode(BlockMode::CBC)
4690 .Padding(PaddingMode::NONE)
4691 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4692 out_params.Clear();
4693 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4694}
4695
4696/*
4697 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4698 *
4699 * Verifies that AES GCM mode works.
4700 */
4701TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4702 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4703 .Authorization(TAG_NO_AUTH_REQUIRED)
4704 .AesEncryptionKey(128)
4705 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4706 .Padding(PaddingMode::NONE)
4707 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4708
4709 string aad = "foobar";
4710 string message = "123456789012345678901234567890123456";
4711
4712 auto begin_params = AuthorizationSetBuilder()
4713 .BlockMode(BlockMode::GCM)
4714 .Padding(PaddingMode::NONE)
4715 .Authorization(TAG_MAC_LENGTH, 128);
4716
Selene Huang31ab4042020-04-29 04:22:39 -07004717 // Encrypt
4718 AuthorizationSet begin_out_params;
4719 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4720 << "Begin encrypt";
4721 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004722 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4723 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004724 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4725
4726 // Grab nonce
4727 begin_params.push_back(begin_out_params);
4728
4729 // Decrypt.
4730 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004731 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004732 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004733 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004734 EXPECT_EQ(message.length(), plaintext.length());
4735 EXPECT_EQ(message, plaintext);
4736}
4737
4738/*
4739 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4740 *
4741 * Verifies that AES GCM mode works, even when there's a long delay
4742 * between operations.
4743 */
4744TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4745 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4746 .Authorization(TAG_NO_AUTH_REQUIRED)
4747 .AesEncryptionKey(128)
4748 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4749 .Padding(PaddingMode::NONE)
4750 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4751
4752 string aad = "foobar";
4753 string message = "123456789012345678901234567890123456";
4754
4755 auto begin_params = AuthorizationSetBuilder()
4756 .BlockMode(BlockMode::GCM)
4757 .Padding(PaddingMode::NONE)
4758 .Authorization(TAG_MAC_LENGTH, 128);
4759
Selene Huang31ab4042020-04-29 04:22:39 -07004760 // Encrypt
4761 AuthorizationSet begin_out_params;
4762 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4763 << "Begin encrypt";
4764 string ciphertext;
4765 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004766 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004767 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004768 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004769
4770 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4771
4772 // Grab nonce
4773 begin_params.push_back(begin_out_params);
4774
4775 // Decrypt.
4776 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4777 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004778 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004779 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004780 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004781 sleep(5);
4782 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4783 EXPECT_EQ(message.length(), plaintext.length());
4784 EXPECT_EQ(message, plaintext);
4785}
4786
4787/*
4788 * EncryptionOperationsTest.AesGcmDifferentNonces
4789 *
4790 * Verifies that encrypting the same data with different nonces produces different outputs.
4791 */
4792TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4793 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4794 .Authorization(TAG_NO_AUTH_REQUIRED)
4795 .AesEncryptionKey(128)
4796 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4797 .Padding(PaddingMode::NONE)
4798 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4799 .Authorization(TAG_CALLER_NONCE)));
4800
4801 string aad = "foobar";
4802 string message = "123456789012345678901234567890123456";
4803 string nonce1 = "000000000000";
4804 string nonce2 = "111111111111";
4805 string nonce3 = "222222222222";
4806
4807 string ciphertext1 =
4808 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4809 string ciphertext2 =
4810 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4811 string ciphertext3 =
4812 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4813
4814 ASSERT_NE(ciphertext1, ciphertext2);
4815 ASSERT_NE(ciphertext1, ciphertext3);
4816 ASSERT_NE(ciphertext2, ciphertext3);
4817}
4818
4819/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004820 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4821 *
4822 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4823 */
4824TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4825 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4826 .Authorization(TAG_NO_AUTH_REQUIRED)
4827 .AesEncryptionKey(128)
4828 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4829 .Padding(PaddingMode::NONE)
4830 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4831
4832 string aad = "foobar";
4833 string message = "123456789012345678901234567890123456";
4834
4835 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4836 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4837 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4838
4839 ASSERT_NE(ciphertext1, ciphertext2);
4840 ASSERT_NE(ciphertext1, ciphertext3);
4841 ASSERT_NE(ciphertext2, ciphertext3);
4842}
4843
4844/*
Selene Huang31ab4042020-04-29 04:22:39 -07004845 * EncryptionOperationsTest.AesGcmTooShortTag
4846 *
4847 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4848 */
4849TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4850 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4851 .Authorization(TAG_NO_AUTH_REQUIRED)
4852 .AesEncryptionKey(128)
4853 .BlockMode(BlockMode::GCM)
4854 .Padding(PaddingMode::NONE)
4855 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4856 string message = "123456789012345678901234567890123456";
4857 auto params = AuthorizationSetBuilder()
4858 .BlockMode(BlockMode::GCM)
4859 .Padding(PaddingMode::NONE)
4860 .Authorization(TAG_MAC_LENGTH, 96);
4861
4862 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4863}
4864
4865/*
4866 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4867 *
4868 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4869 */
4870TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4871 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4872 .Authorization(TAG_NO_AUTH_REQUIRED)
4873 .AesEncryptionKey(128)
4874 .BlockMode(BlockMode::GCM)
4875 .Padding(PaddingMode::NONE)
4876 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4877 string aad = "foobar";
4878 string message = "123456789012345678901234567890123456";
4879 auto params = AuthorizationSetBuilder()
4880 .BlockMode(BlockMode::GCM)
4881 .Padding(PaddingMode::NONE)
4882 .Authorization(TAG_MAC_LENGTH, 128);
4883
Selene Huang31ab4042020-04-29 04:22:39 -07004884 // Encrypt
4885 AuthorizationSet begin_out_params;
4886 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4887 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004888 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004889
4890 AuthorizationSet finish_out_params;
4891 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004892 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4893 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004894
4895 params = AuthorizationSetBuilder()
4896 .Authorizations(begin_out_params)
4897 .BlockMode(BlockMode::GCM)
4898 .Padding(PaddingMode::NONE)
4899 .Authorization(TAG_MAC_LENGTH, 96);
4900
4901 // Decrypt.
4902 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
4903}
4904
4905/*
4906 * EncryptionOperationsTest.AesGcmCorruptKey
4907 *
4908 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
4909 */
4910TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
4911 const uint8_t nonce_bytes[] = {
4912 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
4913 };
4914 string nonce = make_string(nonce_bytes);
4915 const uint8_t ciphertext_bytes[] = {
4916 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
4917 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
4918 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
4919 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
4920 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
4921 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
4922 };
4923 string ciphertext = make_string(ciphertext_bytes);
4924
4925 auto params = AuthorizationSetBuilder()
4926 .BlockMode(BlockMode::GCM)
4927 .Padding(PaddingMode::NONE)
4928 .Authorization(TAG_MAC_LENGTH, 128)
4929 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
4930
4931 auto import_params = AuthorizationSetBuilder()
4932 .Authorization(TAG_NO_AUTH_REQUIRED)
4933 .AesEncryptionKey(128)
4934 .BlockMode(BlockMode::GCM)
4935 .Padding(PaddingMode::NONE)
4936 .Authorization(TAG_CALLER_NONCE)
4937 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4938
4939 // Import correct key and decrypt
4940 const uint8_t key_bytes[] = {
4941 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
4942 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
4943 };
4944 string key = make_string(key_bytes);
4945 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
4946 string plaintext = DecryptMessage(ciphertext, params);
4947 CheckedDeleteKey();
4948
4949 // Corrupt key and attempt to decrypt
4950 key[0] = 0;
4951 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
4952 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4953 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
4954 CheckedDeleteKey();
4955}
4956
4957/*
4958 * EncryptionOperationsTest.AesGcmAadNoData
4959 *
4960 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
4961 * encrypt.
4962 */
4963TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
4964 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4965 .Authorization(TAG_NO_AUTH_REQUIRED)
4966 .AesEncryptionKey(128)
4967 .BlockMode(BlockMode::GCM)
4968 .Padding(PaddingMode::NONE)
4969 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4970
4971 string aad = "1234567890123456";
4972 auto params = AuthorizationSetBuilder()
4973 .BlockMode(BlockMode::GCM)
4974 .Padding(PaddingMode::NONE)
4975 .Authorization(TAG_MAC_LENGTH, 128);
4976
Selene Huang31ab4042020-04-29 04:22:39 -07004977 // Encrypt
4978 AuthorizationSet begin_out_params;
4979 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4980 string ciphertext;
4981 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004982 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4983 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004984 EXPECT_TRUE(finish_out_params.empty());
4985
4986 // Grab nonce
4987 params.push_back(begin_out_params);
4988
4989 // Decrypt.
4990 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004991 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004992 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004993 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004994
4995 EXPECT_TRUE(finish_out_params.empty());
4996
4997 EXPECT_EQ("", plaintext);
4998}
4999
5000/*
5001 * EncryptionOperationsTest.AesGcmMultiPartAad
5002 *
5003 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5004 * chunks.
5005 */
5006TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5007 const size_t tag_bits = 128;
5008 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5009 .Authorization(TAG_NO_AUTH_REQUIRED)
5010 .AesEncryptionKey(128)
5011 .BlockMode(BlockMode::GCM)
5012 .Padding(PaddingMode::NONE)
5013 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5014
5015 string message = "123456789012345678901234567890123456";
5016 auto begin_params = AuthorizationSetBuilder()
5017 .BlockMode(BlockMode::GCM)
5018 .Padding(PaddingMode::NONE)
5019 .Authorization(TAG_MAC_LENGTH, tag_bits);
5020 AuthorizationSet begin_out_params;
5021
Selene Huang31ab4042020-04-29 04:22:39 -07005022 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5023
5024 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005025 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5026 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005027 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005028 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5029 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005030
Selene Huang31ab4042020-04-29 04:22:39 -07005031 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005032 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005033
5034 // Grab nonce.
5035 begin_params.push_back(begin_out_params);
5036
5037 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005038 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005039 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005040 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005041 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005042 EXPECT_EQ(message, plaintext);
5043}
5044
5045/*
5046 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5047 *
5048 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5049 */
5050TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5051 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5052 .Authorization(TAG_NO_AUTH_REQUIRED)
5053 .AesEncryptionKey(128)
5054 .BlockMode(BlockMode::GCM)
5055 .Padding(PaddingMode::NONE)
5056 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5057
5058 string message = "123456789012345678901234567890123456";
5059 auto begin_params = AuthorizationSetBuilder()
5060 .BlockMode(BlockMode::GCM)
5061 .Padding(PaddingMode::NONE)
5062 .Authorization(TAG_MAC_LENGTH, 128);
5063 AuthorizationSet begin_out_params;
5064
Selene Huang31ab4042020-04-29 04:22:39 -07005065 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5066
Shawn Willden92d79c02021-02-19 07:31:55 -07005067 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005068 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005069 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5070 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005071
David Drysdaled2cc8c22021-04-15 13:29:45 +01005072 // The failure should have already cancelled the operation.
5073 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5074
Shawn Willden92d79c02021-02-19 07:31:55 -07005075 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005076}
5077
5078/*
5079 * EncryptionOperationsTest.AesGcmBadAad
5080 *
5081 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5082 */
5083TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5084 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5085 .Authorization(TAG_NO_AUTH_REQUIRED)
5086 .AesEncryptionKey(128)
5087 .BlockMode(BlockMode::GCM)
5088 .Padding(PaddingMode::NONE)
5089 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5090
5091 string message = "12345678901234567890123456789012";
5092 auto begin_params = AuthorizationSetBuilder()
5093 .BlockMode(BlockMode::GCM)
5094 .Padding(PaddingMode::NONE)
5095 .Authorization(TAG_MAC_LENGTH, 128);
5096
Selene Huang31ab4042020-04-29 04:22:39 -07005097 // Encrypt
5098 AuthorizationSet begin_out_params;
5099 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005100 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005101 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005102 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005103
5104 // Grab nonce
5105 begin_params.push_back(begin_out_params);
5106
Selene Huang31ab4042020-04-29 04:22:39 -07005107 // Decrypt.
5108 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005109 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005110 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005111 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005112}
5113
5114/*
5115 * EncryptionOperationsTest.AesGcmWrongNonce
5116 *
5117 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5118 */
5119TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5120 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5121 .Authorization(TAG_NO_AUTH_REQUIRED)
5122 .AesEncryptionKey(128)
5123 .BlockMode(BlockMode::GCM)
5124 .Padding(PaddingMode::NONE)
5125 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5126
5127 string message = "12345678901234567890123456789012";
5128 auto begin_params = AuthorizationSetBuilder()
5129 .BlockMode(BlockMode::GCM)
5130 .Padding(PaddingMode::NONE)
5131 .Authorization(TAG_MAC_LENGTH, 128);
5132
Selene Huang31ab4042020-04-29 04:22:39 -07005133 // Encrypt
5134 AuthorizationSet begin_out_params;
5135 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005136 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005137 string ciphertext;
5138 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005139 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005140
5141 // Wrong nonce
5142 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5143
5144 // Decrypt.
5145 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005146 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005147 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005148 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005149
5150 // With wrong nonce, should have gotten garbage plaintext (or none).
5151 EXPECT_NE(message, plaintext);
5152}
5153
5154/*
5155 * EncryptionOperationsTest.AesGcmCorruptTag
5156 *
5157 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5158 */
5159TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5160 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5161 .Authorization(TAG_NO_AUTH_REQUIRED)
5162 .AesEncryptionKey(128)
5163 .BlockMode(BlockMode::GCM)
5164 .Padding(PaddingMode::NONE)
5165 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5166
5167 string aad = "1234567890123456";
5168 string message = "123456789012345678901234567890123456";
5169
5170 auto params = AuthorizationSetBuilder()
5171 .BlockMode(BlockMode::GCM)
5172 .Padding(PaddingMode::NONE)
5173 .Authorization(TAG_MAC_LENGTH, 128);
5174
Selene Huang31ab4042020-04-29 04:22:39 -07005175 // Encrypt
5176 AuthorizationSet begin_out_params;
5177 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005178 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005179 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005180 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005181
5182 // Corrupt tag
5183 ++(*ciphertext.rbegin());
5184
5185 // Grab nonce
5186 params.push_back(begin_out_params);
5187
5188 // Decrypt.
5189 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005190 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005191 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005192 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005193}
5194
5195/*
5196 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5197 *
5198 * Verifies that 3DES is basically functional.
5199 */
5200TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5201 auto auths = AuthorizationSetBuilder()
5202 .TripleDesEncryptionKey(168)
5203 .BlockMode(BlockMode::ECB)
5204 .Authorization(TAG_NO_AUTH_REQUIRED)
5205 .Padding(PaddingMode::NONE);
5206
5207 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5208 // Two-block message.
5209 string message = "1234567890123456";
5210 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5211 string ciphertext1 = EncryptMessage(message, inParams);
5212 EXPECT_EQ(message.size(), ciphertext1.size());
5213
5214 string ciphertext2 = EncryptMessage(string(message), inParams);
5215 EXPECT_EQ(message.size(), ciphertext2.size());
5216
5217 // ECB is deterministic.
5218 EXPECT_EQ(ciphertext1, ciphertext2);
5219
5220 string plaintext = DecryptMessage(ciphertext1, inParams);
5221 EXPECT_EQ(message, plaintext);
5222}
5223
5224/*
5225 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5226 *
5227 * Verifies that CBC keys reject ECB usage.
5228 */
5229TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5230 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5231 .TripleDesEncryptionKey(168)
5232 .BlockMode(BlockMode::CBC)
5233 .Authorization(TAG_NO_AUTH_REQUIRED)
5234 .Padding(PaddingMode::NONE)));
5235
5236 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5237 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5238}
5239
5240/*
5241 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5242 *
5243 * Tests ECB mode with PKCS#7 padding, various message sizes.
5244 */
5245TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5246 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5247 .TripleDesEncryptionKey(168)
5248 .BlockMode(BlockMode::ECB)
5249 .Authorization(TAG_NO_AUTH_REQUIRED)
5250 .Padding(PaddingMode::PKCS7)));
5251
5252 for (size_t i = 0; i < 32; ++i) {
5253 string message(i, 'a');
5254 auto inParams =
5255 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5256 string ciphertext = EncryptMessage(message, inParams);
5257 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5258 string plaintext = DecryptMessage(ciphertext, inParams);
5259 EXPECT_EQ(message, plaintext);
5260 }
5261}
5262
5263/*
5264 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5265 *
5266 * Verifies that keys configured for no padding reject PKCS7 padding
5267 */
5268TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5269 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5270 .TripleDesEncryptionKey(168)
5271 .BlockMode(BlockMode::ECB)
5272 .Authorization(TAG_NO_AUTH_REQUIRED)
5273 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005274 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5275 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005276}
5277
5278/*
5279 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5280 *
5281 * Verifies that corrupted padding is detected.
5282 */
5283TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5284 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5285 .TripleDesEncryptionKey(168)
5286 .BlockMode(BlockMode::ECB)
5287 .Authorization(TAG_NO_AUTH_REQUIRED)
5288 .Padding(PaddingMode::PKCS7)));
5289
5290 string message = "a";
5291 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5292 EXPECT_EQ(8U, ciphertext.size());
5293 EXPECT_NE(ciphertext, message);
5294 ++ciphertext[ciphertext.size() / 2];
5295
5296 AuthorizationSetBuilder begin_params;
5297 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5298 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
5299 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5300 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005301 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005302 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5303}
5304
5305struct TripleDesTestVector {
5306 const char* name;
5307 const KeyPurpose purpose;
5308 const BlockMode block_mode;
5309 const PaddingMode padding_mode;
5310 const char* key;
5311 const char* iv;
5312 const char* input;
5313 const char* output;
5314};
5315
5316// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5317// of the NIST vectors are multiples of the block size.
5318static const TripleDesTestVector kTripleDesTestVectors[] = {
5319 {
5320 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5321 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5322 "", // IV
5323 "329d86bdf1bc5af4", // input
5324 "d946c2756d78633f", // output
5325 },
5326 {
5327 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5328 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5329 "", // IV
5330 "6b1540781b01ce1997adae102dbf3c5b", // input
5331 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5332 },
5333 {
5334 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5335 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5336 "", // IV
5337 "6daad94ce08acfe7", // input
5338 "660e7d32dcc90e79", // output
5339 },
5340 {
5341 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5342 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5343 "", // IV
5344 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5345 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5346 },
5347 {
5348 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5349 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5350 "43f791134c5647ba", // IV
5351 "dcc153cef81d6f24", // input
5352 "92538bd8af18d3ba", // output
5353 },
5354 {
5355 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5356 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5357 "c2e999cb6249023c", // IV
5358 "c689aee38a301bb316da75db36f110b5", // input
5359 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5360 },
5361 {
5362 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5363 PaddingMode::PKCS7,
5364 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5365 "c2e999cb6249023c", // IV
5366 "c689aee38a301bb316da75db36f110b500", // input
5367 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5368 },
5369 {
5370 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5371 PaddingMode::PKCS7,
5372 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5373 "c2e999cb6249023c", // IV
5374 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5375 "c689aee38a301bb316da75db36f110b500", // output
5376 },
5377 {
5378 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5379 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5380 "41746c7e442d3681", // IV
5381 "c53a7b0ec40600fe", // input
5382 "d4f00eb455de1034", // output
5383 },
5384 {
5385 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5386 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5387 "3982bc02c3727d45", // IV
5388 "6006f10adef52991fcc777a1238bbb65", // input
5389 "edae09288e9e3bc05746d872b48e3b29", // output
5390 },
5391};
5392
5393/*
5394 * EncryptionOperationsTest.TripleDesTestVector
5395 *
5396 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5397 */
5398TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5399 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5400 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5401 SCOPED_TRACE(test->name);
5402 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5403 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5404 hex2str(test->output));
5405 }
5406}
5407
5408/*
5409 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5410 *
5411 * Validates CBC mode functionality.
5412 */
5413TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5414 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5415 .TripleDesEncryptionKey(168)
5416 .BlockMode(BlockMode::CBC)
5417 .Authorization(TAG_NO_AUTH_REQUIRED)
5418 .Padding(PaddingMode::NONE)));
5419
5420 ASSERT_GT(key_blob_.size(), 0U);
5421
5422 // Two-block message.
5423 string message = "1234567890123456";
5424 vector<uint8_t> iv1;
5425 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5426 EXPECT_EQ(message.size(), ciphertext1.size());
5427
5428 vector<uint8_t> iv2;
5429 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5430 EXPECT_EQ(message.size(), ciphertext2.size());
5431
5432 // IVs should be random, so ciphertexts should differ.
5433 EXPECT_NE(iv1, iv2);
5434 EXPECT_NE(ciphertext1, ciphertext2);
5435
5436 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5437 EXPECT_EQ(message, plaintext);
5438}
5439
5440/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005441 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5442 *
5443 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5444 */
5445TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5446 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5447 .TripleDesEncryptionKey(168)
5448 .BlockMode(BlockMode::CBC)
5449 .Authorization(TAG_NO_AUTH_REQUIRED)
5450 .Authorization(TAG_CALLER_NONCE)
5451 .Padding(PaddingMode::NONE)));
5452 auto params = AuthorizationSetBuilder()
5453 .BlockMode(BlockMode::CBC)
5454 .Padding(PaddingMode::NONE)
5455 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5456 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5457}
5458
5459/*
Selene Huang31ab4042020-04-29 04:22:39 -07005460 * EncryptionOperationsTest.TripleDesCallerIv
5461 *
5462 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5463 */
5464TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5465 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5466 .TripleDesEncryptionKey(168)
5467 .BlockMode(BlockMode::CBC)
5468 .Authorization(TAG_NO_AUTH_REQUIRED)
5469 .Authorization(TAG_CALLER_NONCE)
5470 .Padding(PaddingMode::NONE)));
5471 string message = "1234567890123456";
5472 vector<uint8_t> iv;
5473 // Don't specify IV, should get a random one.
5474 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5475 EXPECT_EQ(message.size(), ciphertext1.size());
5476 EXPECT_EQ(8U, iv.size());
5477
5478 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5479 EXPECT_EQ(message, plaintext);
5480
5481 // Now specify an IV, should also work.
5482 iv = AidlBuf("abcdefgh");
5483 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5484
5485 // Decrypt with correct IV.
5486 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5487 EXPECT_EQ(message, plaintext);
5488
5489 // Now try with wrong IV.
5490 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5491 EXPECT_NE(message, plaintext);
5492}
5493
5494/*
5495 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5496 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005497 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005498 */
5499TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5500 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5501 .TripleDesEncryptionKey(168)
5502 .BlockMode(BlockMode::CBC)
5503 .Authorization(TAG_NO_AUTH_REQUIRED)
5504 .Padding(PaddingMode::NONE)));
5505
5506 string message = "12345678901234567890123456789012";
5507 vector<uint8_t> iv;
5508 // Don't specify nonce, should get a random one.
5509 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5510 EXPECT_EQ(message.size(), ciphertext1.size());
5511 EXPECT_EQ(8U, iv.size());
5512
5513 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5514 EXPECT_EQ(message, plaintext);
5515
5516 // Now specify a nonce, should fail.
5517 auto input_params = AuthorizationSetBuilder()
5518 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5519 .BlockMode(BlockMode::CBC)
5520 .Padding(PaddingMode::NONE);
5521 AuthorizationSet output_params;
5522 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5523 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5524}
5525
5526/*
5527 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5528 *
5529 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5530 */
5531TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5532 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5533 .TripleDesEncryptionKey(168)
5534 .BlockMode(BlockMode::ECB)
5535 .Authorization(TAG_NO_AUTH_REQUIRED)
5536 .Padding(PaddingMode::NONE)));
5537 // Two-block message.
5538 string message = "1234567890123456";
5539 auto begin_params =
5540 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5541 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5542}
5543
5544/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005545 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005546 *
5547 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5548 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005549TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5550 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5551 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5552 .TripleDesEncryptionKey(168)
5553 .BlockMode(blockMode)
5554 .Authorization(TAG_NO_AUTH_REQUIRED)
5555 .Padding(PaddingMode::NONE)));
5556 // Message is slightly shorter than two blocks.
5557 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005558
David Drysdaled2cc8c22021-04-15 13:29:45 +01005559 auto begin_params =
5560 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5561 AuthorizationSet output_params;
5562 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5563 string ciphertext;
5564 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5565
5566 CheckedDeleteKey();
5567 }
Selene Huang31ab4042020-04-29 04:22:39 -07005568}
5569
5570/*
5571 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5572 *
5573 * Verifies that PKCS7 padding works correctly in CBC mode.
5574 */
5575TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5576 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5577 .TripleDesEncryptionKey(168)
5578 .BlockMode(BlockMode::CBC)
5579 .Authorization(TAG_NO_AUTH_REQUIRED)
5580 .Padding(PaddingMode::PKCS7)));
5581
5582 // Try various message lengths; all should work.
5583 for (size_t i = 0; i < 32; ++i) {
5584 string message(i, 'a');
5585 vector<uint8_t> iv;
5586 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5587 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5588 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5589 EXPECT_EQ(message, plaintext);
5590 }
5591}
5592
5593/*
5594 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5595 *
5596 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5597 */
5598TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5599 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5600 .TripleDesEncryptionKey(168)
5601 .BlockMode(BlockMode::CBC)
5602 .Authorization(TAG_NO_AUTH_REQUIRED)
5603 .Padding(PaddingMode::NONE)));
5604
5605 // Try various message lengths; all should fail.
5606 for (size_t i = 0; i < 32; ++i) {
5607 auto begin_params =
5608 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5609 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5610 }
5611}
5612
5613/*
5614 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5615 *
5616 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5617 */
5618TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5619 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5620 .TripleDesEncryptionKey(168)
5621 .BlockMode(BlockMode::CBC)
5622 .Authorization(TAG_NO_AUTH_REQUIRED)
5623 .Padding(PaddingMode::PKCS7)));
5624
5625 string message = "a";
5626 vector<uint8_t> iv;
5627 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5628 EXPECT_EQ(8U, ciphertext.size());
5629 EXPECT_NE(ciphertext, message);
5630 ++ciphertext[ciphertext.size() / 2];
5631
5632 auto begin_params = AuthorizationSetBuilder()
5633 .BlockMode(BlockMode::CBC)
5634 .Padding(PaddingMode::PKCS7)
5635 .Authorization(TAG_NONCE, iv);
5636 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5637 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005638 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005639 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5640}
5641
5642/*
5643 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5644 *
5645 * Verifies that 3DES CBC works with many different input sizes.
5646 */
5647TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5648 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5649 .TripleDesEncryptionKey(168)
5650 .BlockMode(BlockMode::CBC)
5651 .Authorization(TAG_NO_AUTH_REQUIRED)
5652 .Padding(PaddingMode::NONE)));
5653
5654 int increment = 7;
5655 string message(240, 'a');
5656 AuthorizationSet input_params =
5657 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5658 AuthorizationSet output_params;
5659 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5660
5661 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005662 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005663 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005664 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5665 EXPECT_EQ(message.size(), ciphertext.size());
5666
5667 // Move TAG_NONCE into input_params
5668 input_params = output_params;
5669 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5670 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5671 output_params.Clear();
5672
5673 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5674 string plaintext;
5675 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005676 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005677 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5678 EXPECT_EQ(ciphertext.size(), plaintext.size());
5679 EXPECT_EQ(message, plaintext);
5680}
5681
5682INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5683
5684typedef KeyMintAidlTestBase MaxOperationsTest;
5685
5686/*
5687 * MaxOperationsTest.TestLimitAes
5688 *
5689 * Verifies that the max uses per boot tag works correctly with AES keys.
5690 */
5691TEST_P(MaxOperationsTest, TestLimitAes) {
5692 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5693
5694 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5695 .Authorization(TAG_NO_AUTH_REQUIRED)
5696 .AesEncryptionKey(128)
5697 .EcbMode()
5698 .Padding(PaddingMode::NONE)
5699 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5700
5701 string message = "1234567890123456";
5702
5703 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5704
5705 EncryptMessage(message, params);
5706 EncryptMessage(message, params);
5707 EncryptMessage(message, params);
5708
5709 // Fourth time should fail.
5710 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5711}
5712
5713/*
Qi Wud22ec842020-11-26 13:27:53 +08005714 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005715 *
5716 * Verifies that the max uses per boot tag works correctly with RSA keys.
5717 */
5718TEST_P(MaxOperationsTest, TestLimitRsa) {
5719 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5720
5721 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5722 .Authorization(TAG_NO_AUTH_REQUIRED)
5723 .RsaSigningKey(1024, 65537)
5724 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005725 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5726 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005727
5728 string message = "1234567890123456";
5729
5730 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5731
5732 SignMessage(message, params);
5733 SignMessage(message, params);
5734 SignMessage(message, params);
5735
5736 // Fourth time should fail.
5737 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5738}
5739
5740INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5741
Qi Wud22ec842020-11-26 13:27:53 +08005742typedef KeyMintAidlTestBase UsageCountLimitTest;
5743
5744/*
Qi Wubeefae42021-01-28 23:16:37 +08005745 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005746 *
Qi Wubeefae42021-01-28 23:16:37 +08005747 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005748 */
Qi Wubeefae42021-01-28 23:16:37 +08005749TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005750 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5751
5752 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5753 .Authorization(TAG_NO_AUTH_REQUIRED)
5754 .AesEncryptionKey(128)
5755 .EcbMode()
5756 .Padding(PaddingMode::NONE)
5757 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5758
5759 // Check the usage count limit tag appears in the authorizations.
5760 AuthorizationSet auths;
5761 for (auto& entry : key_characteristics_) {
5762 auths.push_back(AuthorizationSet(entry.authorizations));
5763 }
5764 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5765 << "key usage count limit " << 1U << " missing";
5766
5767 string message = "1234567890123456";
5768 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5769
Qi Wubeefae42021-01-28 23:16:37 +08005770 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5771 AuthorizationSet keystore_auths =
5772 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5773
Qi Wud22ec842020-11-26 13:27:53 +08005774 // First usage of AES key should work.
5775 EncryptMessage(message, params);
5776
Qi Wud22ec842020-11-26 13:27:53 +08005777 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5778 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5779 // must be invalidated from secure storage (such as RPMB partition).
5780 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5781 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005782 // Usage count limit tag is enforced by keystore, keymint does nothing.
5783 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005784 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5785 }
5786}
5787
5788/*
Qi Wubeefae42021-01-28 23:16:37 +08005789 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005790 *
Qi Wubeefae42021-01-28 23:16:37 +08005791 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005792 */
Qi Wubeefae42021-01-28 23:16:37 +08005793TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5794 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5795
5796 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5797 .Authorization(TAG_NO_AUTH_REQUIRED)
5798 .AesEncryptionKey(128)
5799 .EcbMode()
5800 .Padding(PaddingMode::NONE)
5801 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5802
5803 // Check the usage count limit tag appears in the authorizations.
5804 AuthorizationSet auths;
5805 for (auto& entry : key_characteristics_) {
5806 auths.push_back(AuthorizationSet(entry.authorizations));
5807 }
5808 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5809 << "key usage count limit " << 3U << " missing";
5810
5811 string message = "1234567890123456";
5812 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5813
5814 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5815 AuthorizationSet keystore_auths =
5816 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5817
5818 EncryptMessage(message, params);
5819 EncryptMessage(message, params);
5820 EncryptMessage(message, params);
5821
5822 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5823 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5824 // must be invalidated from secure storage (such as RPMB partition).
5825 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5826 } else {
5827 // Usage count limit tag is enforced by keystore, keymint does nothing.
5828 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5829 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5830 }
5831}
5832
5833/*
5834 * UsageCountLimitTest.TestSingleUseRsa
5835 *
5836 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5837 */
5838TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005839 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5840
5841 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5842 .Authorization(TAG_NO_AUTH_REQUIRED)
5843 .RsaSigningKey(1024, 65537)
5844 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005845 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5846 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005847
5848 // Check the usage count limit tag appears in the authorizations.
5849 AuthorizationSet auths;
5850 for (auto& entry : key_characteristics_) {
5851 auths.push_back(AuthorizationSet(entry.authorizations));
5852 }
5853 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5854 << "key usage count limit " << 1U << " missing";
5855
5856 string message = "1234567890123456";
5857 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5858
Qi Wubeefae42021-01-28 23:16:37 +08005859 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5860 AuthorizationSet keystore_auths =
5861 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5862
Qi Wud22ec842020-11-26 13:27:53 +08005863 // First usage of RSA key should work.
5864 SignMessage(message, params);
5865
Qi Wud22ec842020-11-26 13:27:53 +08005866 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5867 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5868 // must be invalidated from secure storage (such as RPMB partition).
5869 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5870 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005871 // Usage count limit tag is enforced by keystore, keymint does nothing.
5872 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5873 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5874 }
5875}
5876
5877/*
5878 * UsageCountLimitTest.TestLimitUseRsa
5879 *
5880 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5881 */
5882TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
5883 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5884
5885 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5886 .Authorization(TAG_NO_AUTH_REQUIRED)
5887 .RsaSigningKey(1024, 65537)
5888 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005889 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
5890 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08005891
5892 // Check the usage count limit tag appears in the authorizations.
5893 AuthorizationSet auths;
5894 for (auto& entry : key_characteristics_) {
5895 auths.push_back(AuthorizationSet(entry.authorizations));
5896 }
5897 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5898 << "key usage count limit " << 3U << " missing";
5899
5900 string message = "1234567890123456";
5901 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5902
5903 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5904 AuthorizationSet keystore_auths =
5905 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5906
5907 SignMessage(message, params);
5908 SignMessage(message, params);
5909 SignMessage(message, params);
5910
5911 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5912 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5913 // must be invalidated from secure storage (such as RPMB partition).
5914 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5915 } else {
5916 // Usage count limit tag is enforced by keystore, keymint does nothing.
5917 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08005918 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5919 }
5920}
5921
Qi Wu8e727f72021-02-11 02:49:33 +08005922/*
5923 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
5924 *
5925 * Verifies that when rollback resistance is supported by the KeyMint implementation with
5926 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
5927 * in hardware.
5928 */
5929TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
5930 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5931
5932 auto error = GenerateKey(AuthorizationSetBuilder()
5933 .RsaSigningKey(2048, 65537)
5934 .Digest(Digest::NONE)
5935 .Padding(PaddingMode::NONE)
5936 .Authorization(TAG_NO_AUTH_REQUIRED)
5937 .Authorization(TAG_ROLLBACK_RESISTANCE)
5938 .SetDefaultValidity());
5939 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5940
5941 if (error == ErrorCode::OK) {
5942 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
5943 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
5944 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5945 ASSERT_EQ(ErrorCode::OK, DeleteKey());
5946
5947 // The KeyMint should also enforce single use key in hardware when it supports rollback
5948 // resistance.
5949 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5950 .Authorization(TAG_NO_AUTH_REQUIRED)
5951 .RsaSigningKey(1024, 65537)
5952 .NoDigestOrPadding()
5953 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5954 .SetDefaultValidity()));
5955
5956 // Check the usage count limit tag appears in the hardware authorizations.
5957 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5958 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5959 << "key usage count limit " << 1U << " missing";
5960
5961 string message = "1234567890123456";
5962 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5963
5964 // First usage of RSA key should work.
5965 SignMessage(message, params);
5966
5967 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5968 // must be invalidated from secure storage (such as RPMB partition).
5969 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5970 }
5971}
5972
Qi Wud22ec842020-11-26 13:27:53 +08005973INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
5974
David Drysdale7de9feb2021-03-05 14:56:19 +00005975typedef KeyMintAidlTestBase GetHardwareInfoTest;
5976
5977TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
5978 // Retrieving hardware info should give the same result each time.
5979 KeyMintHardwareInfo info;
5980 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
5981 KeyMintHardwareInfo info2;
5982 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
5983 EXPECT_EQ(info, info2);
5984}
5985
5986INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
5987
Selene Huang31ab4042020-04-29 04:22:39 -07005988typedef KeyMintAidlTestBase AddEntropyTest;
5989
5990/*
5991 * AddEntropyTest.AddEntropy
5992 *
5993 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
5994 * is actually added.
5995 */
5996TEST_P(AddEntropyTest, AddEntropy) {
5997 string data = "foo";
5998 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
5999}
6000
6001/*
6002 * AddEntropyTest.AddEmptyEntropy
6003 *
6004 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6005 */
6006TEST_P(AddEntropyTest, AddEmptyEntropy) {
6007 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6008}
6009
6010/*
6011 * AddEntropyTest.AddLargeEntropy
6012 *
6013 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6014 */
6015TEST_P(AddEntropyTest, AddLargeEntropy) {
6016 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6017}
6018
David Drysdalebb3d85e2021-04-13 11:15:51 +01006019/*
6020 * AddEntropyTest.AddTooLargeEntropy
6021 *
6022 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6023 */
6024TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6025 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6026 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6027}
6028
Selene Huang31ab4042020-04-29 04:22:39 -07006029INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6030
Selene Huang31ab4042020-04-29 04:22:39 -07006031typedef KeyMintAidlTestBase KeyDeletionTest;
6032
6033/**
6034 * KeyDeletionTest.DeleteKey
6035 *
6036 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6037 * valid key blob.
6038 */
6039TEST_P(KeyDeletionTest, DeleteKey) {
6040 auto error = GenerateKey(AuthorizationSetBuilder()
6041 .RsaSigningKey(2048, 65537)
6042 .Digest(Digest::NONE)
6043 .Padding(PaddingMode::NONE)
6044 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006045 .Authorization(TAG_ROLLBACK_RESISTANCE)
6046 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006047 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6048
6049 // Delete must work if rollback protection is implemented
6050 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006051 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006052 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6053
6054 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
6055
6056 string message = "12345678901234567890123456789012";
6057 AuthorizationSet begin_out_params;
6058 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6059 Begin(KeyPurpose::SIGN, key_blob_,
6060 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6061 &begin_out_params));
6062 AbortIfNeeded();
6063 key_blob_ = AidlBuf();
6064 }
6065}
6066
6067/**
6068 * KeyDeletionTest.DeleteInvalidKey
6069 *
6070 * This test checks that the HAL excepts invalid key blobs..
6071 */
6072TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6073 // Generate key just to check if rollback protection is implemented
6074 auto error = GenerateKey(AuthorizationSetBuilder()
6075 .RsaSigningKey(2048, 65537)
6076 .Digest(Digest::NONE)
6077 .Padding(PaddingMode::NONE)
6078 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006079 .Authorization(TAG_ROLLBACK_RESISTANCE)
6080 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006081 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6082
6083 // Delete must work if rollback protection is implemented
6084 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006085 AuthorizationSet enforced(SecLevelAuthorizations());
6086 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006087
6088 // Delete the key we don't care about the result at this point.
6089 DeleteKey();
6090
6091 // Now create an invalid key blob and delete it.
6092 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
6093
6094 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6095 }
6096}
6097
6098/**
6099 * KeyDeletionTest.DeleteAllKeys
6100 *
6101 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6102 *
6103 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6104 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6105 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6106 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6107 * credentials stored in Keystore/Keymint.
6108 */
6109TEST_P(KeyDeletionTest, DeleteAllKeys) {
6110 if (!arm_deleteAllKeys) return;
6111 auto error = GenerateKey(AuthorizationSetBuilder()
6112 .RsaSigningKey(2048, 65537)
6113 .Digest(Digest::NONE)
6114 .Padding(PaddingMode::NONE)
6115 .Authorization(TAG_NO_AUTH_REQUIRED)
6116 .Authorization(TAG_ROLLBACK_RESISTANCE));
6117 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6118
6119 // Delete must work if rollback protection is implemented
6120 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006121 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006122 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6123
6124 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
6125
6126 string message = "12345678901234567890123456789012";
6127 AuthorizationSet begin_out_params;
6128
6129 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6130 Begin(KeyPurpose::SIGN, key_blob_,
6131 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6132 &begin_out_params));
6133 AbortIfNeeded();
6134 key_blob_ = AidlBuf();
6135 }
6136}
6137
6138INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6139
David Drysdaled2cc8c22021-04-15 13:29:45 +01006140typedef KeyMintAidlTestBase KeyUpgradeTest;
6141
6142/**
6143 * KeyUpgradeTest.UpgradeInvalidKey
6144 *
6145 * This test checks that the HAL excepts invalid key blobs..
6146 */
6147TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6148 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6149
6150 std::vector<uint8_t> new_blob;
6151 Status result = keymint_->upgradeKey(key_blob,
6152 AuthorizationSetBuilder()
6153 .Authorization(TAG_APPLICATION_ID, "clientid")
6154 .Authorization(TAG_APPLICATION_DATA, "appdata")
6155 .vector_data(),
6156 &new_blob);
6157 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6158}
6159
6160INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6161
Selene Huang31ab4042020-04-29 04:22:39 -07006162using UpgradeKeyTest = KeyMintAidlTestBase;
6163
6164/*
6165 * UpgradeKeyTest.UpgradeKey
6166 *
6167 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6168 */
6169TEST_P(UpgradeKeyTest, UpgradeKey) {
6170 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6171 .AesEncryptionKey(128)
6172 .Padding(PaddingMode::NONE)
6173 .Authorization(TAG_NO_AUTH_REQUIRED)));
6174
6175 auto result = UpgradeKey(key_blob_);
6176
6177 // Key doesn't need upgrading. Should get okay, but no new key blob.
6178 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6179}
6180
6181INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6182
6183using ClearOperationsTest = KeyMintAidlTestBase;
6184
6185/*
6186 * ClearSlotsTest.TooManyOperations
6187 *
6188 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6189 * operations are started without being finished or aborted. Also verifies
6190 * that aborting the operations clears the operations.
6191 *
6192 */
6193TEST_P(ClearOperationsTest, TooManyOperations) {
6194 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6195 .Authorization(TAG_NO_AUTH_REQUIRED)
6196 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006197 .Padding(PaddingMode::NONE)
6198 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006199
6200 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6201 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006202 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006203 AuthorizationSet out_params;
6204 ErrorCode result;
6205 size_t i;
6206
6207 for (i = 0; i < max_operations; i++) {
6208 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6209 if (ErrorCode::OK != result) {
6210 break;
6211 }
6212 }
6213 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6214 // Try again just in case there's a weird overflow bug
6215 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6216 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6217 for (size_t j = 0; j < i; j++) {
6218 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6219 << "Aboort failed for i = " << j << std::endl;
6220 }
6221 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6222 AbortIfNeeded();
6223}
6224
6225INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6226
6227typedef KeyMintAidlTestBase TransportLimitTest;
6228
6229/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006230 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006231 *
6232 * Verifies that passing input data to finish succeeds as expected.
6233 */
6234TEST_P(TransportLimitTest, LargeFinishInput) {
6235 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6236 .Authorization(TAG_NO_AUTH_REQUIRED)
6237 .AesEncryptionKey(128)
6238 .BlockMode(BlockMode::ECB)
6239 .Padding(PaddingMode::NONE)));
6240
6241 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6242 auto cipher_params =
6243 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6244
6245 AuthorizationSet out_params;
6246 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6247
6248 string plain_message = std::string(1 << msg_size, 'x');
6249 string encrypted_message;
6250 auto rc = Finish(plain_message, &encrypted_message);
6251
6252 EXPECT_EQ(ErrorCode::OK, rc);
6253 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6254 << "Encrypt finish returned OK, but did not consume all of the given input";
6255 cipher_params.push_back(out_params);
6256
6257 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6258
6259 string decrypted_message;
6260 rc = Finish(encrypted_message, &decrypted_message);
6261 EXPECT_EQ(ErrorCode::OK, rc);
6262 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6263 << "Decrypt finish returned OK, did not consume all of the given input";
6264 }
6265}
6266
6267INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6268
David Zeuthene0c40892021-01-08 12:54:11 -05006269typedef KeyMintAidlTestBase KeyAgreementTest;
6270
6271int CurveToOpenSslCurveName(EcCurve curve) {
6272 switch (curve) {
6273 case EcCurve::P_224:
6274 return NID_secp224r1;
6275 case EcCurve::P_256:
6276 return NID_X9_62_prime256v1;
6277 case EcCurve::P_384:
6278 return NID_secp384r1;
6279 case EcCurve::P_521:
6280 return NID_secp521r1;
6281 }
6282}
6283
6284/*
6285 * KeyAgreementTest.Ecdh
6286 *
6287 * Verifies that ECDH works for all curves
6288 */
6289TEST_P(KeyAgreementTest, Ecdh) {
6290 // Because it's possible to use this API with keys on different curves, we
6291 // check all N^2 combinations where N is the number of supported
6292 // curves.
6293 //
6294 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6295 // lot more curves we can be smart about things and just pick |otherCurve| so
6296 // it's not |curve| and that way we end up with only 2*N runs
6297 //
6298 for (auto curve : ValidCurves()) {
6299 for (auto localCurve : ValidCurves()) {
6300 // Generate EC key locally (with access to private key material)
6301 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6302 int curveName = CurveToOpenSslCurveName(localCurve);
6303 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6304 ASSERT_NE(group, nullptr);
6305 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6306 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6307 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6308 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6309
6310 // Get encoded form of the public part of the locally generated key...
6311 unsigned char* p = nullptr;
6312 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6313 ASSERT_GT(encodedPublicKeySize, 0);
6314 vector<uint8_t> encodedPublicKey(
6315 reinterpret_cast<const uint8_t*>(p),
6316 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6317 OPENSSL_free(p);
6318
6319 // Generate EC key in KeyMint (only access to public key material)
6320 vector<uint8_t> challenge = {0x41, 0x42};
6321 EXPECT_EQ(
6322 ErrorCode::OK,
6323 GenerateKey(AuthorizationSetBuilder()
6324 .Authorization(TAG_NO_AUTH_REQUIRED)
6325 .Authorization(TAG_EC_CURVE, curve)
6326 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6327 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6328 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006329 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6330 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006331 << "Failed to generate key";
6332 ASSERT_GT(cert_chain_.size(), 0);
6333 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6334 ASSERT_NE(kmKeyCert, nullptr);
6335 // Check that keyAgreement (bit 4) is set in KeyUsage
6336 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6337 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6338 ASSERT_NE(kmPkey, nullptr);
6339 if (dump_Attestations) {
6340 for (size_t n = 0; n < cert_chain_.size(); n++) {
6341 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6342 }
6343 }
6344
6345 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6346 if (curve != localCurve) {
6347 // If the keys are using different curves KeyMint should fail with
6348 // ErrorCode:INVALID_ARGUMENT. Check that.
6349 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6350 string ZabFromKeyMintStr;
6351 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6352 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6353 &ZabFromKeyMintStr));
6354
6355 } else {
6356 // Otherwise if the keys are using the same curve, it should work.
6357 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6358 string ZabFromKeyMintStr;
6359 EXPECT_EQ(ErrorCode::OK,
6360 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6361 &ZabFromKeyMintStr));
6362 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6363
6364 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6365 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6366 ASSERT_NE(ctx, nullptr);
6367 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6368 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6369 size_t ZabFromTestLen = 0;
6370 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6371 vector<uint8_t> ZabFromTest;
6372 ZabFromTest.resize(ZabFromTestLen);
6373 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6374
6375 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6376 }
6377
6378 CheckedDeleteKey();
6379 }
6380 }
6381}
6382
6383INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6384
David Drysdaled2cc8c22021-04-15 13:29:45 +01006385using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6386
6387// This is a problematic test, as it can render the device under test permanently unusable.
6388// Re-enable and run at your own risk.
6389TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6390 auto result = DestroyAttestationIds();
6391 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6392}
6393
6394INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6395
Shawn Willdend659c7c2021-02-19 14:51:51 -07006396using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006397
6398TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
6399 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6400 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6401
6402 CheckedDeleteKey(&aesKeyData.blob);
6403 CheckedDeleteKey(&hmacKeyData.blob);
6404 CheckedDeleteKey(&rsaKeyData.blob);
6405 CheckedDeleteKey(&ecdsaKeyData.blob);
6406}
6407
David Drysdaled2cc8c22021-04-15 13:29:45 +01006408// 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 +00006409// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6410// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6411// early boot, so you'll have to reboot between runs.
6412TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6413 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6414 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6415 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6416 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6417 EXPECT_TRUE(
6418 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6419 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6420 EXPECT_TRUE(
6421 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6422
6423 // Should be able to use keys, since early boot has not ended
6424 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6425 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6426 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6427 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6428
6429 // End early boot
6430 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6431 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6432
6433 // Should not be able to use already-created keys.
6434 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6435 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6436 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6437 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6438
6439 CheckedDeleteKey(&aesKeyData.blob);
6440 CheckedDeleteKey(&hmacKeyData.blob);
6441 CheckedDeleteKey(&rsaKeyData.blob);
6442 CheckedDeleteKey(&ecdsaKeyData.blob);
6443
6444 // Should not be able to create new keys
6445 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6446 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6447
6448 CheckedDeleteKey(&aesKeyData.blob);
6449 CheckedDeleteKey(&hmacKeyData.blob);
6450 CheckedDeleteKey(&rsaKeyData.blob);
6451 CheckedDeleteKey(&ecdsaKeyData.blob);
6452}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006453
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006454INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6455
Shawn Willdend659c7c2021-02-19 14:51:51 -07006456using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006457
6458// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6459// between runs... and on most test devices there are no enrolled credentials so it can't be
6460// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6461// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6462// a manual test process, which includes unlocking between runs, which is why it's included here.
6463// Well, that and the fact that it's the only test we can do without also making calls into the
6464// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6465// implications might be, so that may or may not be a solution.
6466TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6467 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6468 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6469
6470 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6471 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6472 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6473 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6474
6475 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006476 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006477 ASSERT_EQ(ErrorCode::OK, rc);
6478 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6479 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6480 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6481 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6482
6483 CheckedDeleteKey(&aesKeyData.blob);
6484 CheckedDeleteKey(&hmacKeyData.blob);
6485 CheckedDeleteKey(&rsaKeyData.blob);
6486 CheckedDeleteKey(&ecdsaKeyData.blob);
6487}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006488
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006489INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6490
Janis Danisevskis24c04702020-12-16 18:28:39 -08006491} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006492
6493int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006494 std::cout << "Testing ";
6495 auto halInstances =
6496 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6497 std::cout << "HAL instances:\n";
6498 for (auto& entry : halInstances) {
6499 std::cout << " " << entry << '\n';
6500 }
6501
Selene Huang31ab4042020-04-29 04:22:39 -07006502 ::testing::InitGoogleTest(&argc, argv);
6503 for (int i = 1; i < argc; ++i) {
6504 if (argv[i][0] == '-') {
6505 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006506 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6507 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006508 }
6509 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006510 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6511 dump_Attestations = true;
6512 } else {
6513 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006514 }
David Drysdalebb3d85e2021-04-13 11:15:51 +01006515 // TODO(drysdale): Remove this flag when available KeyMint devices comply with spec
6516 if (std::string(argv[i]) == "--check_patchLevels") {
6517 aidl::android::hardware::security::keymint::test::check_patchLevels = true;
6518 }
Selene Huang31ab4042020-04-29 04:22:39 -07006519 }
6520 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006521 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006522}