blob: 7d366f11f2861d17447dfbb11547bcf739a74253 [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 *
David Drysdale59cae642021-05-12 13:52:03 +01003630 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003631 */
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);
David Drysdale59cae642021-05-12 13:52:03 +01003642 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003643 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003644
David Drysdale59cae642021-05-12 13:52:03 +01003645 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003646 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 *
David Drysdale59cae642021-05-12 13:52:03 +01003658 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003659 */
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
David Drysdale59cae642021-05-12 13:52:03 +01003670 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003671 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);
Selene Huang31ab4042020-04-29 04:22:39 -07003677}
3678
3679/*
Selene Huang31ab4042020-04-29 04:22:39 -07003680 * EncryptionOperationsTest.RsaOaepSuccess
3681 *
David Drysdale59cae642021-05-12 13:52:03 +01003682 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07003683 */
3684TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3685 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3686
3687 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01003688 ASSERT_EQ(ErrorCode::OK,
3689 GenerateKey(AuthorizationSetBuilder()
3690 .Authorization(TAG_NO_AUTH_REQUIRED)
3691 .RsaEncryptionKey(key_size, 65537)
3692 .Padding(PaddingMode::RSA_OAEP)
3693 .Digest(digests)
3694 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
3695 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003696
3697 string message = "Hello";
3698
3699 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01003700 SCOPED_TRACE(testing::Message() << "digest-" << digest);
3701
3702 auto params = AuthorizationSetBuilder()
3703 .Digest(digest)
3704 .Padding(PaddingMode::RSA_OAEP)
3705 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
3706 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003707 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3708 EXPECT_EQ(key_size / 8, ciphertext1.size());
3709
David Drysdale59cae642021-05-12 13:52:03 +01003710 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003711 EXPECT_EQ(key_size / 8, ciphertext2.size());
3712
3713 // OAEP randomizes padding so every result should be different (with astronomically high
3714 // probability).
3715 EXPECT_NE(ciphertext1, ciphertext2);
3716
3717 string plaintext1 = DecryptMessage(ciphertext1, params);
3718 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3719 string plaintext2 = DecryptMessage(ciphertext2, params);
3720 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3721
3722 // Decrypting corrupted ciphertext should fail.
3723 size_t offset_to_corrupt = random() % ciphertext1.size();
3724 char corrupt_byte;
3725 do {
3726 corrupt_byte = static_cast<char>(random() % 256);
3727 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3728 ciphertext1[offset_to_corrupt] = corrupt_byte;
3729
3730 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3731 string result;
3732 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3733 EXPECT_EQ(0U, result.size());
3734 }
3735}
3736
3737/*
3738 * EncryptionOperationsTest.RsaOaepInvalidDigest
3739 *
David Drysdale59cae642021-05-12 13:52:03 +01003740 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07003741 * without a digest.
3742 */
3743TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3744 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3745 .Authorization(TAG_NO_AUTH_REQUIRED)
3746 .RsaEncryptionKey(2048, 65537)
3747 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003748 .Digest(Digest::NONE)
3749 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003750
3751 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003752 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07003753}
3754
3755/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003756 * EncryptionOperationsTest.RsaOaepInvalidPadding
3757 *
David Drysdale59cae642021-05-12 13:52:03 +01003758 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01003759 * with a padding value that is only suitable for signing/verifying.
3760 */
3761TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3762 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3763 .Authorization(TAG_NO_AUTH_REQUIRED)
3764 .RsaEncryptionKey(2048, 65537)
3765 .Padding(PaddingMode::RSA_PSS)
3766 .Digest(Digest::NONE)
3767 .SetDefaultValidity()));
3768
3769 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003770 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003771}
3772
3773/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003774 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003775 *
David Drysdale59cae642021-05-12 13:52:03 +01003776 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07003777 * with a different digest than was used to encrypt.
3778 */
3779TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3780 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3781
3782 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3783 .Authorization(TAG_NO_AUTH_REQUIRED)
3784 .RsaEncryptionKey(1024, 65537)
3785 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003786 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3787 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003788 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01003789 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07003790 message,
3791 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3792
3793 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3794 .Digest(Digest::SHA_2_256)
3795 .Padding(PaddingMode::RSA_OAEP)));
3796 string result;
3797 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3798 EXPECT_EQ(0U, result.size());
3799}
3800
3801/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003802 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3803 *
David Drysdale59cae642021-05-12 13:52:03 +01003804 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003805 * digests.
3806 */
3807TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3808 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3809
3810 size_t key_size = 2048; // Need largish key for SHA-512 test.
3811 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3812 .OaepMGFDigest(digests)
3813 .Authorization(TAG_NO_AUTH_REQUIRED)
3814 .RsaEncryptionKey(key_size, 65537)
3815 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003816 .Digest(Digest::SHA_2_256)
3817 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003818
3819 string message = "Hello";
3820
3821 for (auto digest : digests) {
3822 auto params = AuthorizationSetBuilder()
3823 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
3824 .Digest(Digest::SHA_2_256)
3825 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01003826 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003827 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3828 EXPECT_EQ(key_size / 8, ciphertext1.size());
3829
David Drysdale59cae642021-05-12 13:52:03 +01003830 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003831 EXPECT_EQ(key_size / 8, ciphertext2.size());
3832
3833 // OAEP randomizes padding so every result should be different (with astronomically high
3834 // probability).
3835 EXPECT_NE(ciphertext1, ciphertext2);
3836
3837 string plaintext1 = DecryptMessage(ciphertext1, params);
3838 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3839 string plaintext2 = DecryptMessage(ciphertext2, params);
3840 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3841
3842 // Decrypting corrupted ciphertext should fail.
3843 size_t offset_to_corrupt = random() % ciphertext1.size();
3844 char corrupt_byte;
3845 do {
3846 corrupt_byte = static_cast<char>(random() % 256);
3847 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3848 ciphertext1[offset_to_corrupt] = corrupt_byte;
3849
3850 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3851 string result;
3852 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3853 EXPECT_EQ(0U, result.size());
3854 }
3855}
3856
3857/*
3858 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
3859 *
David Drysdale59cae642021-05-12 13:52:03 +01003860 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003861 * with incompatible MGF digest.
3862 */
3863TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
3864 ASSERT_EQ(ErrorCode::OK,
3865 GenerateKey(AuthorizationSetBuilder()
3866 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3867 .Authorization(TAG_NO_AUTH_REQUIRED)
3868 .RsaEncryptionKey(2048, 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 string message = "Hello World!";
3873
3874 auto params = AuthorizationSetBuilder()
3875 .Padding(PaddingMode::RSA_OAEP)
3876 .Digest(Digest::SHA_2_256)
3877 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01003878 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003879}
3880
3881/*
3882 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
3883 *
3884 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3885 * with unsupported MGF digest.
3886 */
3887TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
3888 ASSERT_EQ(ErrorCode::OK,
3889 GenerateKey(AuthorizationSetBuilder()
3890 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3891 .Authorization(TAG_NO_AUTH_REQUIRED)
3892 .RsaEncryptionKey(2048, 65537)
3893 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003894 .Digest(Digest::SHA_2_256)
3895 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003896 string message = "Hello World!";
3897
3898 auto params = AuthorizationSetBuilder()
3899 .Padding(PaddingMode::RSA_OAEP)
3900 .Digest(Digest::SHA_2_256)
3901 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003902 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003903}
3904
3905/*
Selene Huang31ab4042020-04-29 04:22:39 -07003906 * EncryptionOperationsTest.RsaPkcs1Success
3907 *
3908 * Verifies that RSA PKCS encryption/decrypts works.
3909 */
3910TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
3911 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3912 .Authorization(TAG_NO_AUTH_REQUIRED)
3913 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003914 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
3915 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003916
3917 string message = "Hello World!";
3918 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01003919 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003920 EXPECT_EQ(2048U / 8, ciphertext1.size());
3921
David Drysdale59cae642021-05-12 13:52:03 +01003922 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003923 EXPECT_EQ(2048U / 8, ciphertext2.size());
3924
3925 // PKCS1 v1.5 randomizes padding so every result should be different.
3926 EXPECT_NE(ciphertext1, ciphertext2);
3927
3928 string plaintext = DecryptMessage(ciphertext1, params);
3929 EXPECT_EQ(message, plaintext);
3930
3931 // Decrypting corrupted ciphertext should fail.
3932 size_t offset_to_corrupt = random() % ciphertext1.size();
3933 char corrupt_byte;
3934 do {
3935 corrupt_byte = static_cast<char>(random() % 256);
3936 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3937 ciphertext1[offset_to_corrupt] = corrupt_byte;
3938
3939 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3940 string result;
3941 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3942 EXPECT_EQ(0U, result.size());
3943}
3944
3945/*
Selene Huang31ab4042020-04-29 04:22:39 -07003946 * EncryptionOperationsTest.EcdsaEncrypt
3947 *
3948 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
3949 */
3950TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
3951 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3952 .Authorization(TAG_NO_AUTH_REQUIRED)
3953 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003954 .Digest(Digest::NONE)
3955 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003956 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3957 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
3958 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
3959}
3960
3961/*
3962 * EncryptionOperationsTest.HmacEncrypt
3963 *
3964 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
3965 */
3966TEST_P(EncryptionOperationsTest, HmacEncrypt) {
3967 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3968 .Authorization(TAG_NO_AUTH_REQUIRED)
3969 .HmacKey(128)
3970 .Digest(Digest::SHA_2_256)
3971 .Padding(PaddingMode::NONE)
3972 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3973 auto params = AuthorizationSetBuilder()
3974 .Digest(Digest::SHA_2_256)
3975 .Padding(PaddingMode::NONE)
3976 .Authorization(TAG_MAC_LENGTH, 128);
3977 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
3978 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
3979}
3980
3981/*
3982 * EncryptionOperationsTest.AesEcbRoundTripSuccess
3983 *
3984 * Verifies that AES ECB mode works.
3985 */
3986TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
3987 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3988 .Authorization(TAG_NO_AUTH_REQUIRED)
3989 .AesEncryptionKey(128)
3990 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3991 .Padding(PaddingMode::NONE)));
3992
3993 ASSERT_GT(key_blob_.size(), 0U);
3994 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3995
3996 // Two-block message.
3997 string message = "12345678901234567890123456789012";
3998 string ciphertext1 = EncryptMessage(message, params);
3999 EXPECT_EQ(message.size(), ciphertext1.size());
4000
4001 string ciphertext2 = EncryptMessage(string(message), params);
4002 EXPECT_EQ(message.size(), ciphertext2.size());
4003
4004 // ECB is deterministic.
4005 EXPECT_EQ(ciphertext1, ciphertext2);
4006
4007 string plaintext = DecryptMessage(ciphertext1, params);
4008 EXPECT_EQ(message, plaintext);
4009}
4010
4011/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004012 * EncryptionOperationsTest.AesEcbUnknownTag
4013 *
4014 * Verifies that AES ECB operations ignore unknown tags.
4015 */
4016TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4017 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4018 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4019 KeyParameter unknown_param;
4020 unknown_param.tag = unknown_tag;
4021
4022 vector<KeyCharacteristics> key_characteristics;
4023 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4024 .Authorization(TAG_NO_AUTH_REQUIRED)
4025 .AesEncryptionKey(128)
4026 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4027 .Padding(PaddingMode::NONE)
4028 .Authorization(unknown_param),
4029 &key_blob_, &key_characteristics));
4030 ASSERT_GT(key_blob_.size(), 0U);
4031
4032 // Unknown tags should not be returned in key characteristics.
4033 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4034 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4035 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4036 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4037
4038 // Encrypt without mentioning the unknown parameter.
4039 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4040 string message = "12345678901234567890123456789012";
4041 string ciphertext = EncryptMessage(message, params);
4042 EXPECT_EQ(message.size(), ciphertext.size());
4043
4044 // Decrypt including the unknown parameter.
4045 auto decrypt_params = AuthorizationSetBuilder()
4046 .BlockMode(BlockMode::ECB)
4047 .Padding(PaddingMode::NONE)
4048 .Authorization(unknown_param);
4049 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4050 EXPECT_EQ(message, plaintext);
4051}
4052
4053/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004054 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004055 *
4056 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4057 */
4058TEST_P(EncryptionOperationsTest, AesWrongMode) {
4059 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4060 .Authorization(TAG_NO_AUTH_REQUIRED)
4061 .AesEncryptionKey(128)
4062 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4063 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004064 ASSERT_GT(key_blob_.size(), 0U);
4065
Selene Huang31ab4042020-04-29 04:22:39 -07004066 EXPECT_EQ(
4067 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4068 Begin(KeyPurpose::ENCRYPT,
4069 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4070}
4071
4072/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004073 * EncryptionOperationsTest.AesWrongPadding
4074 *
4075 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4076 */
4077TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4078 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4079 .Authorization(TAG_NO_AUTH_REQUIRED)
4080 .AesEncryptionKey(128)
4081 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4082 .Padding(PaddingMode::NONE)));
4083 ASSERT_GT(key_blob_.size(), 0U);
4084
4085 EXPECT_EQ(
4086 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4087 Begin(KeyPurpose::ENCRYPT,
4088 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4089}
4090
4091/*
4092 * EncryptionOperationsTest.AesInvalidParams
4093 *
4094 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4095 */
4096TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4097 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4098 .Authorization(TAG_NO_AUTH_REQUIRED)
4099 .AesEncryptionKey(128)
4100 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4101 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4102 .Padding(PaddingMode::NONE)
4103 .Padding(PaddingMode::PKCS7)));
4104 ASSERT_GT(key_blob_.size(), 0U);
4105
4106 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4107 .BlockMode(BlockMode::CBC)
4108 .BlockMode(BlockMode::ECB)
4109 .Padding(PaddingMode::NONE));
4110 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4111 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4112
4113 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4114 .BlockMode(BlockMode::ECB)
4115 .Padding(PaddingMode::NONE)
4116 .Padding(PaddingMode::PKCS7));
4117 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4118 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4119}
4120
4121/*
Selene Huang31ab4042020-04-29 04:22:39 -07004122 * EncryptionOperationsTest.AesWrongPurpose
4123 *
4124 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4125 * specified.
4126 */
4127TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4128 auto err = GenerateKey(AuthorizationSetBuilder()
4129 .Authorization(TAG_NO_AUTH_REQUIRED)
4130 .AesKey(128)
4131 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4132 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4133 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4134 .Padding(PaddingMode::NONE));
4135 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4136 ASSERT_GT(key_blob_.size(), 0U);
4137
4138 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4139 .BlockMode(BlockMode::GCM)
4140 .Padding(PaddingMode::NONE)
4141 .Authorization(TAG_MAC_LENGTH, 128));
4142 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4143
4144 CheckedDeleteKey();
4145
4146 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4147 .Authorization(TAG_NO_AUTH_REQUIRED)
4148 .AesKey(128)
4149 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4150 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4151 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4152 .Padding(PaddingMode::NONE)));
4153
4154 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4155 .BlockMode(BlockMode::GCM)
4156 .Padding(PaddingMode::NONE)
4157 .Authorization(TAG_MAC_LENGTH, 128));
4158 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4159}
4160
4161/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004162 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004163 *
4164 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4165 * multiple of the block size and no padding is specified.
4166 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004167TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4168 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4169 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4170 .Authorization(TAG_NO_AUTH_REQUIRED)
4171 .AesEncryptionKey(128)
4172 .Authorization(TAG_BLOCK_MODE, blockMode)
4173 .Padding(PaddingMode::NONE)));
4174 // Message is slightly shorter than two blocks.
4175 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004176
David Drysdaled2cc8c22021-04-15 13:29:45 +01004177 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4178 AuthorizationSet out_params;
4179 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4180 string ciphertext;
4181 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4182 EXPECT_EQ(0U, ciphertext.size());
4183
4184 CheckedDeleteKey();
4185 }
Selene Huang31ab4042020-04-29 04:22:39 -07004186}
4187
4188/*
4189 * EncryptionOperationsTest.AesEcbPkcs7Padding
4190 *
4191 * Verifies that AES PKCS7 padding works for any message length.
4192 */
4193TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4194 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4195 .Authorization(TAG_NO_AUTH_REQUIRED)
4196 .AesEncryptionKey(128)
4197 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4198 .Padding(PaddingMode::PKCS7)));
4199
4200 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4201
4202 // Try various message lengths; all should work.
4203 for (size_t i = 0; i < 32; ++i) {
4204 string message(i, 'a');
4205 string ciphertext = EncryptMessage(message, params);
4206 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4207 string plaintext = DecryptMessage(ciphertext, params);
4208 EXPECT_EQ(message, plaintext);
4209 }
4210}
4211
4212/*
4213 * EncryptionOperationsTest.AesEcbWrongPadding
4214 *
4215 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4216 * specified.
4217 */
4218TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4219 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4220 .Authorization(TAG_NO_AUTH_REQUIRED)
4221 .AesEncryptionKey(128)
4222 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4223 .Padding(PaddingMode::NONE)));
4224
4225 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4226
4227 // Try various message lengths; all should fail
4228 for (size_t i = 0; i < 32; ++i) {
4229 string message(i, 'a');
4230 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4231 }
4232}
4233
4234/*
4235 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4236 *
4237 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4238 */
4239TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4240 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4241 .Authorization(TAG_NO_AUTH_REQUIRED)
4242 .AesEncryptionKey(128)
4243 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4244 .Padding(PaddingMode::PKCS7)));
4245
4246 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4247
4248 string message = "a";
4249 string ciphertext = EncryptMessage(message, params);
4250 EXPECT_EQ(16U, ciphertext.size());
4251 EXPECT_NE(ciphertext, message);
4252 ++ciphertext[ciphertext.size() / 2];
4253
4254 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4255 string plaintext;
4256 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
4257}
4258
4259vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4260 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004261 EXPECT_TRUE(iv);
4262 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004263}
4264
4265/*
4266 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4267 *
4268 * Verifies that AES CTR mode works.
4269 */
4270TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4271 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4272 .Authorization(TAG_NO_AUTH_REQUIRED)
4273 .AesEncryptionKey(128)
4274 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4275 .Padding(PaddingMode::NONE)));
4276
4277 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4278
4279 string message = "123";
4280 AuthorizationSet out_params;
4281 string ciphertext1 = EncryptMessage(message, params, &out_params);
4282 vector<uint8_t> iv1 = CopyIv(out_params);
4283 EXPECT_EQ(16U, iv1.size());
4284
4285 EXPECT_EQ(message.size(), ciphertext1.size());
4286
4287 out_params.Clear();
4288 string ciphertext2 = EncryptMessage(message, params, &out_params);
4289 vector<uint8_t> iv2 = CopyIv(out_params);
4290 EXPECT_EQ(16U, iv2.size());
4291
4292 // IVs should be random, so ciphertexts should differ.
4293 EXPECT_NE(ciphertext1, ciphertext2);
4294
4295 auto params_iv1 =
4296 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4297 auto params_iv2 =
4298 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4299
4300 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4301 EXPECT_EQ(message, plaintext);
4302 plaintext = DecryptMessage(ciphertext2, params_iv2);
4303 EXPECT_EQ(message, plaintext);
4304
4305 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4306 plaintext = DecryptMessage(ciphertext1, params_iv2);
4307 EXPECT_NE(message, plaintext);
4308 plaintext = DecryptMessage(ciphertext2, params_iv1);
4309 EXPECT_NE(message, plaintext);
4310}
4311
4312/*
4313 * EncryptionOperationsTest.AesIncremental
4314 *
4315 * Verifies that AES works, all modes, when provided data in various size increments.
4316 */
4317TEST_P(EncryptionOperationsTest, AesIncremental) {
4318 auto block_modes = {
4319 BlockMode::ECB,
4320 BlockMode::CBC,
4321 BlockMode::CTR,
4322 BlockMode::GCM,
4323 };
4324
4325 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4326 .Authorization(TAG_NO_AUTH_REQUIRED)
4327 .AesEncryptionKey(128)
4328 .BlockMode(block_modes)
4329 .Padding(PaddingMode::NONE)
4330 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4331
4332 for (int increment = 1; increment <= 240; ++increment) {
4333 for (auto block_mode : block_modes) {
4334 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004335 auto params =
4336 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4337 if (block_mode == BlockMode::GCM) {
4338 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4339 }
Selene Huang31ab4042020-04-29 04:22:39 -07004340
4341 AuthorizationSet output_params;
4342 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4343
4344 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004345 string to_send;
4346 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004347 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004348 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004349 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4350 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004351
4352 switch (block_mode) {
4353 case BlockMode::GCM:
4354 EXPECT_EQ(message.size() + 16, ciphertext.size());
4355 break;
4356 case BlockMode::CTR:
4357 EXPECT_EQ(message.size(), ciphertext.size());
4358 break;
4359 case BlockMode::CBC:
4360 case BlockMode::ECB:
4361 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4362 break;
4363 }
4364
4365 auto iv = output_params.GetTagValue(TAG_NONCE);
4366 switch (block_mode) {
4367 case BlockMode::CBC:
4368 case BlockMode::GCM:
4369 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004370 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4371 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4372 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004373 break;
4374
4375 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004376 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004377 break;
4378 }
4379
4380 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4381 << "Decrypt begin() failed for block mode " << block_mode;
4382
4383 string plaintext;
4384 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004385 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004386 }
4387 ErrorCode error = Finish(to_send, &plaintext);
4388 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4389 << " and increment " << increment;
4390 if (error == ErrorCode::OK) {
4391 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4392 << block_mode << " and increment " << increment;
4393 }
4394 }
4395 }
4396}
4397
4398struct AesCtrSp80038aTestVector {
4399 const char* key;
4400 const char* nonce;
4401 const char* plaintext;
4402 const char* ciphertext;
4403};
4404
4405// These test vectors are taken from
4406// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4407static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4408 // AES-128
4409 {
4410 "2b7e151628aed2a6abf7158809cf4f3c",
4411 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4412 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4413 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4414 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4415 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4416 },
4417 // AES-192
4418 {
4419 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4420 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4421 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4422 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4423 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4424 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4425 },
4426 // AES-256
4427 {
4428 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4429 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4430 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4431 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4432 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4433 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4434 },
4435};
4436
4437/*
4438 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4439 *
4440 * Verifies AES CTR implementation against SP800-38A test vectors.
4441 */
4442TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4443 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4444 for (size_t i = 0; i < 3; i++) {
4445 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4446 const string key = hex2str(test.key);
4447 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4448 InvalidSizes.end())
4449 continue;
4450 const string nonce = hex2str(test.nonce);
4451 const string plaintext = hex2str(test.plaintext);
4452 const string ciphertext = hex2str(test.ciphertext);
4453 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4454 }
4455}
4456
4457/*
4458 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4459 *
4460 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4461 */
4462TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4463 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4464 .Authorization(TAG_NO_AUTH_REQUIRED)
4465 .AesEncryptionKey(128)
4466 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4467 .Padding(PaddingMode::PKCS7)));
4468 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4469 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4470}
4471
4472/*
4473 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4474 *
4475 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4476 */
4477TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4478 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4479 .Authorization(TAG_NO_AUTH_REQUIRED)
4480 .AesEncryptionKey(128)
4481 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4482 .Authorization(TAG_CALLER_NONCE)
4483 .Padding(PaddingMode::NONE)));
4484
4485 auto params = AuthorizationSetBuilder()
4486 .BlockMode(BlockMode::CTR)
4487 .Padding(PaddingMode::NONE)
4488 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4489 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4490
4491 params = AuthorizationSetBuilder()
4492 .BlockMode(BlockMode::CTR)
4493 .Padding(PaddingMode::NONE)
4494 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4495 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4496
4497 params = AuthorizationSetBuilder()
4498 .BlockMode(BlockMode::CTR)
4499 .Padding(PaddingMode::NONE)
4500 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4501 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4502}
4503
4504/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004505 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004506 *
4507 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4508 */
4509TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4510 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4511 .Authorization(TAG_NO_AUTH_REQUIRED)
4512 .AesEncryptionKey(128)
4513 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4514 .Padding(PaddingMode::NONE)));
4515 // Two-block message.
4516 string message = "12345678901234567890123456789012";
4517 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4518 AuthorizationSet out_params;
4519 string ciphertext1 = EncryptMessage(message, params, &out_params);
4520 vector<uint8_t> iv1 = CopyIv(out_params);
4521 EXPECT_EQ(message.size(), ciphertext1.size());
4522
4523 out_params.Clear();
4524
4525 string ciphertext2 = EncryptMessage(message, params, &out_params);
4526 vector<uint8_t> iv2 = CopyIv(out_params);
4527 EXPECT_EQ(message.size(), ciphertext2.size());
4528
4529 // IVs should be random, so ciphertexts should differ.
4530 EXPECT_NE(ciphertext1, ciphertext2);
4531
4532 params.push_back(TAG_NONCE, iv1);
4533 string plaintext = DecryptMessage(ciphertext1, params);
4534 EXPECT_EQ(message, plaintext);
4535}
4536
4537/*
4538 * EncryptionOperationsTest.AesCallerNonce
4539 *
4540 * Verifies that AES caller-provided nonces work correctly.
4541 */
4542TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4543 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4544 .Authorization(TAG_NO_AUTH_REQUIRED)
4545 .AesEncryptionKey(128)
4546 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4547 .Authorization(TAG_CALLER_NONCE)
4548 .Padding(PaddingMode::NONE)));
4549
4550 string message = "12345678901234567890123456789012";
4551
4552 // Don't specify nonce, should get a random one.
4553 AuthorizationSetBuilder params =
4554 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4555 AuthorizationSet out_params;
4556 string ciphertext = EncryptMessage(message, params, &out_params);
4557 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004558 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004559
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004560 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004561 string plaintext = DecryptMessage(ciphertext, params);
4562 EXPECT_EQ(message, plaintext);
4563
4564 // Now specify a nonce, should also work.
4565 params = AuthorizationSetBuilder()
4566 .BlockMode(BlockMode::CBC)
4567 .Padding(PaddingMode::NONE)
4568 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4569 out_params.Clear();
4570 ciphertext = EncryptMessage(message, params, &out_params);
4571
4572 // Decrypt with correct nonce.
4573 plaintext = DecryptMessage(ciphertext, params);
4574 EXPECT_EQ(message, plaintext);
4575
4576 // Try with wrong nonce.
4577 params = AuthorizationSetBuilder()
4578 .BlockMode(BlockMode::CBC)
4579 .Padding(PaddingMode::NONE)
4580 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4581 plaintext = DecryptMessage(ciphertext, params);
4582 EXPECT_NE(message, plaintext);
4583}
4584
4585/*
4586 * EncryptionOperationsTest.AesCallerNonceProhibited
4587 *
4588 * Verifies that caller-provided nonces are not permitted when not specified in the key
4589 * authorizations.
4590 */
4591TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4592 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4593 .Authorization(TAG_NO_AUTH_REQUIRED)
4594 .AesEncryptionKey(128)
4595 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4596 .Padding(PaddingMode::NONE)));
4597
4598 string message = "12345678901234567890123456789012";
4599
4600 // Don't specify nonce, should get a random one.
4601 AuthorizationSetBuilder params =
4602 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4603 AuthorizationSet out_params;
4604 string ciphertext = EncryptMessage(message, params, &out_params);
4605 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004606 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004607
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004608 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004609 string plaintext = DecryptMessage(ciphertext, params);
4610 EXPECT_EQ(message, plaintext);
4611
4612 // Now specify a nonce, should fail
4613 params = AuthorizationSetBuilder()
4614 .BlockMode(BlockMode::CBC)
4615 .Padding(PaddingMode::NONE)
4616 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4617 out_params.Clear();
4618 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4619}
4620
4621/*
4622 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4623 *
4624 * Verifies that AES GCM mode works.
4625 */
4626TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4627 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4628 .Authorization(TAG_NO_AUTH_REQUIRED)
4629 .AesEncryptionKey(128)
4630 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4631 .Padding(PaddingMode::NONE)
4632 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4633
4634 string aad = "foobar";
4635 string message = "123456789012345678901234567890123456";
4636
4637 auto begin_params = AuthorizationSetBuilder()
4638 .BlockMode(BlockMode::GCM)
4639 .Padding(PaddingMode::NONE)
4640 .Authorization(TAG_MAC_LENGTH, 128);
4641
Selene Huang31ab4042020-04-29 04:22:39 -07004642 // Encrypt
4643 AuthorizationSet begin_out_params;
4644 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4645 << "Begin encrypt";
4646 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004647 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4648 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004649 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4650
4651 // Grab nonce
4652 begin_params.push_back(begin_out_params);
4653
4654 // Decrypt.
4655 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004656 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004657 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004658 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004659 EXPECT_EQ(message.length(), plaintext.length());
4660 EXPECT_EQ(message, plaintext);
4661}
4662
4663/*
4664 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4665 *
4666 * Verifies that AES GCM mode works, even when there's a long delay
4667 * between operations.
4668 */
4669TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4670 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4671 .Authorization(TAG_NO_AUTH_REQUIRED)
4672 .AesEncryptionKey(128)
4673 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4674 .Padding(PaddingMode::NONE)
4675 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4676
4677 string aad = "foobar";
4678 string message = "123456789012345678901234567890123456";
4679
4680 auto begin_params = AuthorizationSetBuilder()
4681 .BlockMode(BlockMode::GCM)
4682 .Padding(PaddingMode::NONE)
4683 .Authorization(TAG_MAC_LENGTH, 128);
4684
Selene Huang31ab4042020-04-29 04:22:39 -07004685 // Encrypt
4686 AuthorizationSet begin_out_params;
4687 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4688 << "Begin encrypt";
4689 string ciphertext;
4690 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004691 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004692 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004693 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004694
4695 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4696
4697 // Grab nonce
4698 begin_params.push_back(begin_out_params);
4699
4700 // Decrypt.
4701 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4702 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004703 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004704 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004705 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004706 sleep(5);
4707 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4708 EXPECT_EQ(message.length(), plaintext.length());
4709 EXPECT_EQ(message, plaintext);
4710}
4711
4712/*
4713 * EncryptionOperationsTest.AesGcmDifferentNonces
4714 *
4715 * Verifies that encrypting the same data with different nonces produces different outputs.
4716 */
4717TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4718 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4719 .Authorization(TAG_NO_AUTH_REQUIRED)
4720 .AesEncryptionKey(128)
4721 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4722 .Padding(PaddingMode::NONE)
4723 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4724 .Authorization(TAG_CALLER_NONCE)));
4725
4726 string aad = "foobar";
4727 string message = "123456789012345678901234567890123456";
4728 string nonce1 = "000000000000";
4729 string nonce2 = "111111111111";
4730 string nonce3 = "222222222222";
4731
4732 string ciphertext1 =
4733 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4734 string ciphertext2 =
4735 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4736 string ciphertext3 =
4737 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4738
4739 ASSERT_NE(ciphertext1, ciphertext2);
4740 ASSERT_NE(ciphertext1, ciphertext3);
4741 ASSERT_NE(ciphertext2, ciphertext3);
4742}
4743
4744/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004745 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4746 *
4747 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4748 */
4749TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4750 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4751 .Authorization(TAG_NO_AUTH_REQUIRED)
4752 .AesEncryptionKey(128)
4753 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4754 .Padding(PaddingMode::NONE)
4755 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4756
4757 string aad = "foobar";
4758 string message = "123456789012345678901234567890123456";
4759
4760 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4761 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4762 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4763
4764 ASSERT_NE(ciphertext1, ciphertext2);
4765 ASSERT_NE(ciphertext1, ciphertext3);
4766 ASSERT_NE(ciphertext2, ciphertext3);
4767}
4768
4769/*
Selene Huang31ab4042020-04-29 04:22:39 -07004770 * EncryptionOperationsTest.AesGcmTooShortTag
4771 *
4772 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4773 */
4774TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4775 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4776 .Authorization(TAG_NO_AUTH_REQUIRED)
4777 .AesEncryptionKey(128)
4778 .BlockMode(BlockMode::GCM)
4779 .Padding(PaddingMode::NONE)
4780 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4781 string message = "123456789012345678901234567890123456";
4782 auto params = AuthorizationSetBuilder()
4783 .BlockMode(BlockMode::GCM)
4784 .Padding(PaddingMode::NONE)
4785 .Authorization(TAG_MAC_LENGTH, 96);
4786
4787 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4788}
4789
4790/*
4791 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4792 *
4793 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4794 */
4795TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4796 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4797 .Authorization(TAG_NO_AUTH_REQUIRED)
4798 .AesEncryptionKey(128)
4799 .BlockMode(BlockMode::GCM)
4800 .Padding(PaddingMode::NONE)
4801 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4802 string aad = "foobar";
4803 string message = "123456789012345678901234567890123456";
4804 auto params = AuthorizationSetBuilder()
4805 .BlockMode(BlockMode::GCM)
4806 .Padding(PaddingMode::NONE)
4807 .Authorization(TAG_MAC_LENGTH, 128);
4808
Selene Huang31ab4042020-04-29 04:22:39 -07004809 // Encrypt
4810 AuthorizationSet begin_out_params;
4811 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4812 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004813 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004814
4815 AuthorizationSet finish_out_params;
4816 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004817 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4818 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004819
4820 params = AuthorizationSetBuilder()
4821 .Authorizations(begin_out_params)
4822 .BlockMode(BlockMode::GCM)
4823 .Padding(PaddingMode::NONE)
4824 .Authorization(TAG_MAC_LENGTH, 96);
4825
4826 // Decrypt.
4827 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
4828}
4829
4830/*
4831 * EncryptionOperationsTest.AesGcmCorruptKey
4832 *
4833 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
4834 */
4835TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
4836 const uint8_t nonce_bytes[] = {
4837 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
4838 };
4839 string nonce = make_string(nonce_bytes);
4840 const uint8_t ciphertext_bytes[] = {
4841 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
4842 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
4843 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
4844 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
4845 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
4846 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
4847 };
4848 string ciphertext = make_string(ciphertext_bytes);
4849
4850 auto params = AuthorizationSetBuilder()
4851 .BlockMode(BlockMode::GCM)
4852 .Padding(PaddingMode::NONE)
4853 .Authorization(TAG_MAC_LENGTH, 128)
4854 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
4855
4856 auto import_params = AuthorizationSetBuilder()
4857 .Authorization(TAG_NO_AUTH_REQUIRED)
4858 .AesEncryptionKey(128)
4859 .BlockMode(BlockMode::GCM)
4860 .Padding(PaddingMode::NONE)
4861 .Authorization(TAG_CALLER_NONCE)
4862 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4863
4864 // Import correct key and decrypt
4865 const uint8_t key_bytes[] = {
4866 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
4867 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
4868 };
4869 string key = make_string(key_bytes);
4870 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
4871 string plaintext = DecryptMessage(ciphertext, params);
4872 CheckedDeleteKey();
4873
4874 // Corrupt key and attempt to decrypt
4875 key[0] = 0;
4876 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
4877 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4878 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
4879 CheckedDeleteKey();
4880}
4881
4882/*
4883 * EncryptionOperationsTest.AesGcmAadNoData
4884 *
4885 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
4886 * encrypt.
4887 */
4888TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
4889 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4890 .Authorization(TAG_NO_AUTH_REQUIRED)
4891 .AesEncryptionKey(128)
4892 .BlockMode(BlockMode::GCM)
4893 .Padding(PaddingMode::NONE)
4894 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4895
4896 string aad = "1234567890123456";
4897 auto params = AuthorizationSetBuilder()
4898 .BlockMode(BlockMode::GCM)
4899 .Padding(PaddingMode::NONE)
4900 .Authorization(TAG_MAC_LENGTH, 128);
4901
Selene Huang31ab4042020-04-29 04:22:39 -07004902 // Encrypt
4903 AuthorizationSet begin_out_params;
4904 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4905 string ciphertext;
4906 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004907 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4908 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004909 EXPECT_TRUE(finish_out_params.empty());
4910
4911 // Grab nonce
4912 params.push_back(begin_out_params);
4913
4914 // Decrypt.
4915 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004916 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004917 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004918 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004919
4920 EXPECT_TRUE(finish_out_params.empty());
4921
4922 EXPECT_EQ("", plaintext);
4923}
4924
4925/*
4926 * EncryptionOperationsTest.AesGcmMultiPartAad
4927 *
4928 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
4929 * chunks.
4930 */
4931TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
4932 const size_t tag_bits = 128;
4933 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4934 .Authorization(TAG_NO_AUTH_REQUIRED)
4935 .AesEncryptionKey(128)
4936 .BlockMode(BlockMode::GCM)
4937 .Padding(PaddingMode::NONE)
4938 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4939
4940 string message = "123456789012345678901234567890123456";
4941 auto begin_params = AuthorizationSetBuilder()
4942 .BlockMode(BlockMode::GCM)
4943 .Padding(PaddingMode::NONE)
4944 .Authorization(TAG_MAC_LENGTH, tag_bits);
4945 AuthorizationSet begin_out_params;
4946
Selene Huang31ab4042020-04-29 04:22:39 -07004947 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
4948
4949 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07004950 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
4951 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004952 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004953 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
4954 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004955
Selene Huang31ab4042020-04-29 04:22:39 -07004956 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07004957 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004958
4959 // Grab nonce.
4960 begin_params.push_back(begin_out_params);
4961
4962 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07004963 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004964 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004965 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004966 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004967 EXPECT_EQ(message, plaintext);
4968}
4969
4970/*
4971 * EncryptionOperationsTest.AesGcmAadOutOfOrder
4972 *
4973 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
4974 */
4975TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
4976 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4977 .Authorization(TAG_NO_AUTH_REQUIRED)
4978 .AesEncryptionKey(128)
4979 .BlockMode(BlockMode::GCM)
4980 .Padding(PaddingMode::NONE)
4981 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4982
4983 string message = "123456789012345678901234567890123456";
4984 auto begin_params = AuthorizationSetBuilder()
4985 .BlockMode(BlockMode::GCM)
4986 .Padding(PaddingMode::NONE)
4987 .Authorization(TAG_MAC_LENGTH, 128);
4988 AuthorizationSet begin_out_params;
4989
Selene Huang31ab4042020-04-29 04:22:39 -07004990 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
4991
Shawn Willden92d79c02021-02-19 07:31:55 -07004992 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004993 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004994 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
4995 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004996
David Drysdaled2cc8c22021-04-15 13:29:45 +01004997 // The failure should have already cancelled the operation.
4998 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
4999
Shawn Willden92d79c02021-02-19 07:31:55 -07005000 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005001}
5002
5003/*
5004 * EncryptionOperationsTest.AesGcmBadAad
5005 *
5006 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5007 */
5008TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5009 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5010 .Authorization(TAG_NO_AUTH_REQUIRED)
5011 .AesEncryptionKey(128)
5012 .BlockMode(BlockMode::GCM)
5013 .Padding(PaddingMode::NONE)
5014 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5015
5016 string message = "12345678901234567890123456789012";
5017 auto begin_params = AuthorizationSetBuilder()
5018 .BlockMode(BlockMode::GCM)
5019 .Padding(PaddingMode::NONE)
5020 .Authorization(TAG_MAC_LENGTH, 128);
5021
Selene Huang31ab4042020-04-29 04:22:39 -07005022 // Encrypt
5023 AuthorizationSet begin_out_params;
5024 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005025 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005026 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005027 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005028
5029 // Grab nonce
5030 begin_params.push_back(begin_out_params);
5031
Selene Huang31ab4042020-04-29 04:22:39 -07005032 // Decrypt.
5033 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005034 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005035 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005036 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005037}
5038
5039/*
5040 * EncryptionOperationsTest.AesGcmWrongNonce
5041 *
5042 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5043 */
5044TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5045 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5046 .Authorization(TAG_NO_AUTH_REQUIRED)
5047 .AesEncryptionKey(128)
5048 .BlockMode(BlockMode::GCM)
5049 .Padding(PaddingMode::NONE)
5050 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5051
5052 string message = "12345678901234567890123456789012";
5053 auto begin_params = AuthorizationSetBuilder()
5054 .BlockMode(BlockMode::GCM)
5055 .Padding(PaddingMode::NONE)
5056 .Authorization(TAG_MAC_LENGTH, 128);
5057
Selene Huang31ab4042020-04-29 04:22:39 -07005058 // Encrypt
5059 AuthorizationSet begin_out_params;
5060 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005061 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005062 string ciphertext;
5063 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005064 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005065
5066 // Wrong nonce
5067 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5068
5069 // Decrypt.
5070 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005071 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005072 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005073 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005074
5075 // With wrong nonce, should have gotten garbage plaintext (or none).
5076 EXPECT_NE(message, plaintext);
5077}
5078
5079/*
5080 * EncryptionOperationsTest.AesGcmCorruptTag
5081 *
5082 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5083 */
5084TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5085 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5086 .Authorization(TAG_NO_AUTH_REQUIRED)
5087 .AesEncryptionKey(128)
5088 .BlockMode(BlockMode::GCM)
5089 .Padding(PaddingMode::NONE)
5090 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5091
5092 string aad = "1234567890123456";
5093 string message = "123456789012345678901234567890123456";
5094
5095 auto params = AuthorizationSetBuilder()
5096 .BlockMode(BlockMode::GCM)
5097 .Padding(PaddingMode::NONE)
5098 .Authorization(TAG_MAC_LENGTH, 128);
5099
Selene Huang31ab4042020-04-29 04:22:39 -07005100 // Encrypt
5101 AuthorizationSet begin_out_params;
5102 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005103 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005104 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005105 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005106
5107 // Corrupt tag
5108 ++(*ciphertext.rbegin());
5109
5110 // Grab nonce
5111 params.push_back(begin_out_params);
5112
5113 // Decrypt.
5114 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005115 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005116 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005117 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005118}
5119
5120/*
5121 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5122 *
5123 * Verifies that 3DES is basically functional.
5124 */
5125TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5126 auto auths = AuthorizationSetBuilder()
5127 .TripleDesEncryptionKey(168)
5128 .BlockMode(BlockMode::ECB)
5129 .Authorization(TAG_NO_AUTH_REQUIRED)
5130 .Padding(PaddingMode::NONE);
5131
5132 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5133 // Two-block message.
5134 string message = "1234567890123456";
5135 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5136 string ciphertext1 = EncryptMessage(message, inParams);
5137 EXPECT_EQ(message.size(), ciphertext1.size());
5138
5139 string ciphertext2 = EncryptMessage(string(message), inParams);
5140 EXPECT_EQ(message.size(), ciphertext2.size());
5141
5142 // ECB is deterministic.
5143 EXPECT_EQ(ciphertext1, ciphertext2);
5144
5145 string plaintext = DecryptMessage(ciphertext1, inParams);
5146 EXPECT_EQ(message, plaintext);
5147}
5148
5149/*
5150 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5151 *
5152 * Verifies that CBC keys reject ECB usage.
5153 */
5154TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5155 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5156 .TripleDesEncryptionKey(168)
5157 .BlockMode(BlockMode::CBC)
5158 .Authorization(TAG_NO_AUTH_REQUIRED)
5159 .Padding(PaddingMode::NONE)));
5160
5161 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5162 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5163}
5164
5165/*
5166 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5167 *
5168 * Tests ECB mode with PKCS#7 padding, various message sizes.
5169 */
5170TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5171 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5172 .TripleDesEncryptionKey(168)
5173 .BlockMode(BlockMode::ECB)
5174 .Authorization(TAG_NO_AUTH_REQUIRED)
5175 .Padding(PaddingMode::PKCS7)));
5176
5177 for (size_t i = 0; i < 32; ++i) {
5178 string message(i, 'a');
5179 auto inParams =
5180 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5181 string ciphertext = EncryptMessage(message, inParams);
5182 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5183 string plaintext = DecryptMessage(ciphertext, inParams);
5184 EXPECT_EQ(message, plaintext);
5185 }
5186}
5187
5188/*
5189 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5190 *
5191 * Verifies that keys configured for no padding reject PKCS7 padding
5192 */
5193TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5194 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5195 .TripleDesEncryptionKey(168)
5196 .BlockMode(BlockMode::ECB)
5197 .Authorization(TAG_NO_AUTH_REQUIRED)
5198 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005199 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5200 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005201}
5202
5203/*
5204 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5205 *
5206 * Verifies that corrupted padding is detected.
5207 */
5208TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5209 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5210 .TripleDesEncryptionKey(168)
5211 .BlockMode(BlockMode::ECB)
5212 .Authorization(TAG_NO_AUTH_REQUIRED)
5213 .Padding(PaddingMode::PKCS7)));
5214
5215 string message = "a";
5216 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5217 EXPECT_EQ(8U, ciphertext.size());
5218 EXPECT_NE(ciphertext, message);
5219 ++ciphertext[ciphertext.size() / 2];
5220
5221 AuthorizationSetBuilder begin_params;
5222 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5223 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
5224 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5225 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005226 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005227 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5228}
5229
5230struct TripleDesTestVector {
5231 const char* name;
5232 const KeyPurpose purpose;
5233 const BlockMode block_mode;
5234 const PaddingMode padding_mode;
5235 const char* key;
5236 const char* iv;
5237 const char* input;
5238 const char* output;
5239};
5240
5241// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5242// of the NIST vectors are multiples of the block size.
5243static const TripleDesTestVector kTripleDesTestVectors[] = {
5244 {
5245 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5246 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5247 "", // IV
5248 "329d86bdf1bc5af4", // input
5249 "d946c2756d78633f", // output
5250 },
5251 {
5252 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5253 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5254 "", // IV
5255 "6b1540781b01ce1997adae102dbf3c5b", // input
5256 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5257 },
5258 {
5259 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5260 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5261 "", // IV
5262 "6daad94ce08acfe7", // input
5263 "660e7d32dcc90e79", // output
5264 },
5265 {
5266 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5267 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5268 "", // IV
5269 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5270 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5271 },
5272 {
5273 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5274 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5275 "43f791134c5647ba", // IV
5276 "dcc153cef81d6f24", // input
5277 "92538bd8af18d3ba", // output
5278 },
5279 {
5280 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5281 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5282 "c2e999cb6249023c", // IV
5283 "c689aee38a301bb316da75db36f110b5", // input
5284 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5285 },
5286 {
5287 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5288 PaddingMode::PKCS7,
5289 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5290 "c2e999cb6249023c", // IV
5291 "c689aee38a301bb316da75db36f110b500", // input
5292 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5293 },
5294 {
5295 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5296 PaddingMode::PKCS7,
5297 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5298 "c2e999cb6249023c", // IV
5299 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5300 "c689aee38a301bb316da75db36f110b500", // output
5301 },
5302 {
5303 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5304 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5305 "41746c7e442d3681", // IV
5306 "c53a7b0ec40600fe", // input
5307 "d4f00eb455de1034", // output
5308 },
5309 {
5310 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5311 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5312 "3982bc02c3727d45", // IV
5313 "6006f10adef52991fcc777a1238bbb65", // input
5314 "edae09288e9e3bc05746d872b48e3b29", // output
5315 },
5316};
5317
5318/*
5319 * EncryptionOperationsTest.TripleDesTestVector
5320 *
5321 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5322 */
5323TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5324 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5325 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5326 SCOPED_TRACE(test->name);
5327 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5328 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5329 hex2str(test->output));
5330 }
5331}
5332
5333/*
5334 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5335 *
5336 * Validates CBC mode functionality.
5337 */
5338TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5339 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5340 .TripleDesEncryptionKey(168)
5341 .BlockMode(BlockMode::CBC)
5342 .Authorization(TAG_NO_AUTH_REQUIRED)
5343 .Padding(PaddingMode::NONE)));
5344
5345 ASSERT_GT(key_blob_.size(), 0U);
5346
5347 // Two-block message.
5348 string message = "1234567890123456";
5349 vector<uint8_t> iv1;
5350 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5351 EXPECT_EQ(message.size(), ciphertext1.size());
5352
5353 vector<uint8_t> iv2;
5354 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5355 EXPECT_EQ(message.size(), ciphertext2.size());
5356
5357 // IVs should be random, so ciphertexts should differ.
5358 EXPECT_NE(iv1, iv2);
5359 EXPECT_NE(ciphertext1, ciphertext2);
5360
5361 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5362 EXPECT_EQ(message, plaintext);
5363}
5364
5365/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005366 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5367 *
5368 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5369 */
5370TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5371 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5372 .TripleDesEncryptionKey(168)
5373 .BlockMode(BlockMode::CBC)
5374 .Authorization(TAG_NO_AUTH_REQUIRED)
5375 .Authorization(TAG_CALLER_NONCE)
5376 .Padding(PaddingMode::NONE)));
5377 auto params = AuthorizationSetBuilder()
5378 .BlockMode(BlockMode::CBC)
5379 .Padding(PaddingMode::NONE)
5380 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5381 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5382}
5383
5384/*
Selene Huang31ab4042020-04-29 04:22:39 -07005385 * EncryptionOperationsTest.TripleDesCallerIv
5386 *
5387 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5388 */
5389TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5390 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5391 .TripleDesEncryptionKey(168)
5392 .BlockMode(BlockMode::CBC)
5393 .Authorization(TAG_NO_AUTH_REQUIRED)
5394 .Authorization(TAG_CALLER_NONCE)
5395 .Padding(PaddingMode::NONE)));
5396 string message = "1234567890123456";
5397 vector<uint8_t> iv;
5398 // Don't specify IV, should get a random one.
5399 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5400 EXPECT_EQ(message.size(), ciphertext1.size());
5401 EXPECT_EQ(8U, iv.size());
5402
5403 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5404 EXPECT_EQ(message, plaintext);
5405
5406 // Now specify an IV, should also work.
5407 iv = AidlBuf("abcdefgh");
5408 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5409
5410 // Decrypt with correct IV.
5411 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5412 EXPECT_EQ(message, plaintext);
5413
5414 // Now try with wrong IV.
5415 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5416 EXPECT_NE(message, plaintext);
5417}
5418
5419/*
5420 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5421 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005422 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005423 */
5424TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5425 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5426 .TripleDesEncryptionKey(168)
5427 .BlockMode(BlockMode::CBC)
5428 .Authorization(TAG_NO_AUTH_REQUIRED)
5429 .Padding(PaddingMode::NONE)));
5430
5431 string message = "12345678901234567890123456789012";
5432 vector<uint8_t> iv;
5433 // Don't specify nonce, should get a random one.
5434 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5435 EXPECT_EQ(message.size(), ciphertext1.size());
5436 EXPECT_EQ(8U, iv.size());
5437
5438 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5439 EXPECT_EQ(message, plaintext);
5440
5441 // Now specify a nonce, should fail.
5442 auto input_params = AuthorizationSetBuilder()
5443 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5444 .BlockMode(BlockMode::CBC)
5445 .Padding(PaddingMode::NONE);
5446 AuthorizationSet output_params;
5447 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5448 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5449}
5450
5451/*
5452 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5453 *
5454 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5455 */
5456TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5457 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5458 .TripleDesEncryptionKey(168)
5459 .BlockMode(BlockMode::ECB)
5460 .Authorization(TAG_NO_AUTH_REQUIRED)
5461 .Padding(PaddingMode::NONE)));
5462 // Two-block message.
5463 string message = "1234567890123456";
5464 auto begin_params =
5465 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5466 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5467}
5468
5469/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005470 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005471 *
5472 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5473 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005474TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5475 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5476 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5477 .TripleDesEncryptionKey(168)
5478 .BlockMode(blockMode)
5479 .Authorization(TAG_NO_AUTH_REQUIRED)
5480 .Padding(PaddingMode::NONE)));
5481 // Message is slightly shorter than two blocks.
5482 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005483
David Drysdaled2cc8c22021-04-15 13:29:45 +01005484 auto begin_params =
5485 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5486 AuthorizationSet output_params;
5487 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5488 string ciphertext;
5489 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5490
5491 CheckedDeleteKey();
5492 }
Selene Huang31ab4042020-04-29 04:22:39 -07005493}
5494
5495/*
5496 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5497 *
5498 * Verifies that PKCS7 padding works correctly in CBC mode.
5499 */
5500TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5501 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5502 .TripleDesEncryptionKey(168)
5503 .BlockMode(BlockMode::CBC)
5504 .Authorization(TAG_NO_AUTH_REQUIRED)
5505 .Padding(PaddingMode::PKCS7)));
5506
5507 // Try various message lengths; all should work.
5508 for (size_t i = 0; i < 32; ++i) {
5509 string message(i, 'a');
5510 vector<uint8_t> iv;
5511 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5512 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5513 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5514 EXPECT_EQ(message, plaintext);
5515 }
5516}
5517
5518/*
5519 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5520 *
5521 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5522 */
5523TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5524 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5525 .TripleDesEncryptionKey(168)
5526 .BlockMode(BlockMode::CBC)
5527 .Authorization(TAG_NO_AUTH_REQUIRED)
5528 .Padding(PaddingMode::NONE)));
5529
5530 // Try various message lengths; all should fail.
5531 for (size_t i = 0; i < 32; ++i) {
5532 auto begin_params =
5533 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5534 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5535 }
5536}
5537
5538/*
5539 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5540 *
5541 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5542 */
5543TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5544 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5545 .TripleDesEncryptionKey(168)
5546 .BlockMode(BlockMode::CBC)
5547 .Authorization(TAG_NO_AUTH_REQUIRED)
5548 .Padding(PaddingMode::PKCS7)));
5549
5550 string message = "a";
5551 vector<uint8_t> iv;
5552 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5553 EXPECT_EQ(8U, ciphertext.size());
5554 EXPECT_NE(ciphertext, message);
5555 ++ciphertext[ciphertext.size() / 2];
5556
5557 auto begin_params = AuthorizationSetBuilder()
5558 .BlockMode(BlockMode::CBC)
5559 .Padding(PaddingMode::PKCS7)
5560 .Authorization(TAG_NONCE, iv);
5561 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5562 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005563 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005564 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5565}
5566
5567/*
5568 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5569 *
5570 * Verifies that 3DES CBC works with many different input sizes.
5571 */
5572TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5573 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5574 .TripleDesEncryptionKey(168)
5575 .BlockMode(BlockMode::CBC)
5576 .Authorization(TAG_NO_AUTH_REQUIRED)
5577 .Padding(PaddingMode::NONE)));
5578
5579 int increment = 7;
5580 string message(240, 'a');
5581 AuthorizationSet input_params =
5582 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5583 AuthorizationSet output_params;
5584 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5585
5586 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005587 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005588 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005589 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5590 EXPECT_EQ(message.size(), ciphertext.size());
5591
5592 // Move TAG_NONCE into input_params
5593 input_params = output_params;
5594 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5595 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5596 output_params.Clear();
5597
5598 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5599 string plaintext;
5600 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005601 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005602 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5603 EXPECT_EQ(ciphertext.size(), plaintext.size());
5604 EXPECT_EQ(message, plaintext);
5605}
5606
5607INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5608
5609typedef KeyMintAidlTestBase MaxOperationsTest;
5610
5611/*
5612 * MaxOperationsTest.TestLimitAes
5613 *
5614 * Verifies that the max uses per boot tag works correctly with AES keys.
5615 */
5616TEST_P(MaxOperationsTest, TestLimitAes) {
5617 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5618
5619 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5620 .Authorization(TAG_NO_AUTH_REQUIRED)
5621 .AesEncryptionKey(128)
5622 .EcbMode()
5623 .Padding(PaddingMode::NONE)
5624 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5625
5626 string message = "1234567890123456";
5627
5628 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5629
5630 EncryptMessage(message, params);
5631 EncryptMessage(message, params);
5632 EncryptMessage(message, params);
5633
5634 // Fourth time should fail.
5635 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5636}
5637
5638/*
Qi Wud22ec842020-11-26 13:27:53 +08005639 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005640 *
5641 * Verifies that the max uses per boot tag works correctly with RSA keys.
5642 */
5643TEST_P(MaxOperationsTest, TestLimitRsa) {
5644 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5645
5646 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5647 .Authorization(TAG_NO_AUTH_REQUIRED)
5648 .RsaSigningKey(1024, 65537)
5649 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005650 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5651 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005652
5653 string message = "1234567890123456";
5654
5655 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5656
5657 SignMessage(message, params);
5658 SignMessage(message, params);
5659 SignMessage(message, params);
5660
5661 // Fourth time should fail.
5662 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5663}
5664
5665INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5666
Qi Wud22ec842020-11-26 13:27:53 +08005667typedef KeyMintAidlTestBase UsageCountLimitTest;
5668
5669/*
Qi Wubeefae42021-01-28 23:16:37 +08005670 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005671 *
Qi Wubeefae42021-01-28 23:16:37 +08005672 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005673 */
Qi Wubeefae42021-01-28 23:16:37 +08005674TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005675 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5676
5677 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5678 .Authorization(TAG_NO_AUTH_REQUIRED)
5679 .AesEncryptionKey(128)
5680 .EcbMode()
5681 .Padding(PaddingMode::NONE)
5682 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5683
5684 // Check the usage count limit tag appears in the authorizations.
5685 AuthorizationSet auths;
5686 for (auto& entry : key_characteristics_) {
5687 auths.push_back(AuthorizationSet(entry.authorizations));
5688 }
5689 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5690 << "key usage count limit " << 1U << " missing";
5691
5692 string message = "1234567890123456";
5693 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5694
Qi Wubeefae42021-01-28 23:16:37 +08005695 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5696 AuthorizationSet keystore_auths =
5697 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5698
Qi Wud22ec842020-11-26 13:27:53 +08005699 // First usage of AES key should work.
5700 EncryptMessage(message, params);
5701
Qi Wud22ec842020-11-26 13:27:53 +08005702 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5703 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5704 // must be invalidated from secure storage (such as RPMB partition).
5705 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5706 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005707 // Usage count limit tag is enforced by keystore, keymint does nothing.
5708 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005709 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5710 }
5711}
5712
5713/*
Qi Wubeefae42021-01-28 23:16:37 +08005714 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005715 *
Qi Wubeefae42021-01-28 23:16:37 +08005716 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005717 */
Qi Wubeefae42021-01-28 23:16:37 +08005718TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5719 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5720
5721 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5722 .Authorization(TAG_NO_AUTH_REQUIRED)
5723 .AesEncryptionKey(128)
5724 .EcbMode()
5725 .Padding(PaddingMode::NONE)
5726 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5727
5728 // Check the usage count limit tag appears in the authorizations.
5729 AuthorizationSet auths;
5730 for (auto& entry : key_characteristics_) {
5731 auths.push_back(AuthorizationSet(entry.authorizations));
5732 }
5733 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5734 << "key usage count limit " << 3U << " missing";
5735
5736 string message = "1234567890123456";
5737 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5738
5739 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5740 AuthorizationSet keystore_auths =
5741 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5742
5743 EncryptMessage(message, params);
5744 EncryptMessage(message, params);
5745 EncryptMessage(message, params);
5746
5747 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5748 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5749 // must be invalidated from secure storage (such as RPMB partition).
5750 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5751 } else {
5752 // Usage count limit tag is enforced by keystore, keymint does nothing.
5753 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5754 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5755 }
5756}
5757
5758/*
5759 * UsageCountLimitTest.TestSingleUseRsa
5760 *
5761 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5762 */
5763TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005764 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5765
5766 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5767 .Authorization(TAG_NO_AUTH_REQUIRED)
5768 .RsaSigningKey(1024, 65537)
5769 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005770 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5771 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005772
5773 // Check the usage count limit tag appears in the authorizations.
5774 AuthorizationSet auths;
5775 for (auto& entry : key_characteristics_) {
5776 auths.push_back(AuthorizationSet(entry.authorizations));
5777 }
5778 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5779 << "key usage count limit " << 1U << " missing";
5780
5781 string message = "1234567890123456";
5782 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5783
Qi Wubeefae42021-01-28 23:16:37 +08005784 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5785 AuthorizationSet keystore_auths =
5786 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5787
Qi Wud22ec842020-11-26 13:27:53 +08005788 // First usage of RSA key should work.
5789 SignMessage(message, params);
5790
Qi Wud22ec842020-11-26 13:27:53 +08005791 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5792 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5793 // must be invalidated from secure storage (such as RPMB partition).
5794 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5795 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005796 // Usage count limit tag is enforced by keystore, keymint does nothing.
5797 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5798 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5799 }
5800}
5801
5802/*
5803 * UsageCountLimitTest.TestLimitUseRsa
5804 *
5805 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5806 */
5807TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
5808 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5809
5810 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5811 .Authorization(TAG_NO_AUTH_REQUIRED)
5812 .RsaSigningKey(1024, 65537)
5813 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005814 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
5815 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08005816
5817 // Check the usage count limit tag appears in the authorizations.
5818 AuthorizationSet auths;
5819 for (auto& entry : key_characteristics_) {
5820 auths.push_back(AuthorizationSet(entry.authorizations));
5821 }
5822 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5823 << "key usage count limit " << 3U << " missing";
5824
5825 string message = "1234567890123456";
5826 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5827
5828 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5829 AuthorizationSet keystore_auths =
5830 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5831
5832 SignMessage(message, params);
5833 SignMessage(message, params);
5834 SignMessage(message, params);
5835
5836 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5837 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5838 // must be invalidated from secure storage (such as RPMB partition).
5839 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5840 } else {
5841 // Usage count limit tag is enforced by keystore, keymint does nothing.
5842 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08005843 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5844 }
5845}
5846
Qi Wu8e727f72021-02-11 02:49:33 +08005847/*
5848 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
5849 *
5850 * Verifies that when rollback resistance is supported by the KeyMint implementation with
5851 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
5852 * in hardware.
5853 */
5854TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
5855 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5856
5857 auto error = GenerateKey(AuthorizationSetBuilder()
5858 .RsaSigningKey(2048, 65537)
5859 .Digest(Digest::NONE)
5860 .Padding(PaddingMode::NONE)
5861 .Authorization(TAG_NO_AUTH_REQUIRED)
5862 .Authorization(TAG_ROLLBACK_RESISTANCE)
5863 .SetDefaultValidity());
5864 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5865
5866 if (error == ErrorCode::OK) {
5867 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
5868 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
5869 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5870 ASSERT_EQ(ErrorCode::OK, DeleteKey());
5871
5872 // The KeyMint should also enforce single use key in hardware when it supports rollback
5873 // resistance.
5874 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5875 .Authorization(TAG_NO_AUTH_REQUIRED)
5876 .RsaSigningKey(1024, 65537)
5877 .NoDigestOrPadding()
5878 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5879 .SetDefaultValidity()));
5880
5881 // Check the usage count limit tag appears in the hardware authorizations.
5882 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5883 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5884 << "key usage count limit " << 1U << " missing";
5885
5886 string message = "1234567890123456";
5887 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5888
5889 // First usage of RSA key should work.
5890 SignMessage(message, params);
5891
5892 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5893 // must be invalidated from secure storage (such as RPMB partition).
5894 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5895 }
5896}
5897
Qi Wud22ec842020-11-26 13:27:53 +08005898INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
5899
David Drysdale7de9feb2021-03-05 14:56:19 +00005900typedef KeyMintAidlTestBase GetHardwareInfoTest;
5901
5902TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
5903 // Retrieving hardware info should give the same result each time.
5904 KeyMintHardwareInfo info;
5905 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
5906 KeyMintHardwareInfo info2;
5907 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
5908 EXPECT_EQ(info, info2);
5909}
5910
5911INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
5912
Selene Huang31ab4042020-04-29 04:22:39 -07005913typedef KeyMintAidlTestBase AddEntropyTest;
5914
5915/*
5916 * AddEntropyTest.AddEntropy
5917 *
5918 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
5919 * is actually added.
5920 */
5921TEST_P(AddEntropyTest, AddEntropy) {
5922 string data = "foo";
5923 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
5924}
5925
5926/*
5927 * AddEntropyTest.AddEmptyEntropy
5928 *
5929 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
5930 */
5931TEST_P(AddEntropyTest, AddEmptyEntropy) {
5932 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
5933}
5934
5935/*
5936 * AddEntropyTest.AddLargeEntropy
5937 *
5938 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
5939 */
5940TEST_P(AddEntropyTest, AddLargeEntropy) {
5941 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
5942}
5943
David Drysdalebb3d85e2021-04-13 11:15:51 +01005944/*
5945 * AddEntropyTest.AddTooLargeEntropy
5946 *
5947 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
5948 */
5949TEST_P(AddEntropyTest, AddTooLargeEntropy) {
5950 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
5951 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
5952}
5953
Selene Huang31ab4042020-04-29 04:22:39 -07005954INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
5955
Selene Huang31ab4042020-04-29 04:22:39 -07005956typedef KeyMintAidlTestBase KeyDeletionTest;
5957
5958/**
5959 * KeyDeletionTest.DeleteKey
5960 *
5961 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
5962 * valid key blob.
5963 */
5964TEST_P(KeyDeletionTest, DeleteKey) {
5965 auto error = GenerateKey(AuthorizationSetBuilder()
5966 .RsaSigningKey(2048, 65537)
5967 .Digest(Digest::NONE)
5968 .Padding(PaddingMode::NONE)
5969 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08005970 .Authorization(TAG_ROLLBACK_RESISTANCE)
5971 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07005972 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5973
5974 // Delete must work if rollback protection is implemented
5975 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07005976 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07005977 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5978
5979 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
5980
5981 string message = "12345678901234567890123456789012";
5982 AuthorizationSet begin_out_params;
5983 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
5984 Begin(KeyPurpose::SIGN, key_blob_,
5985 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
5986 &begin_out_params));
5987 AbortIfNeeded();
5988 key_blob_ = AidlBuf();
5989 }
5990}
5991
5992/**
5993 * KeyDeletionTest.DeleteInvalidKey
5994 *
5995 * This test checks that the HAL excepts invalid key blobs..
5996 */
5997TEST_P(KeyDeletionTest, DeleteInvalidKey) {
5998 // Generate key just to check if rollback protection is implemented
5999 auto error = GenerateKey(AuthorizationSetBuilder()
6000 .RsaSigningKey(2048, 65537)
6001 .Digest(Digest::NONE)
6002 .Padding(PaddingMode::NONE)
6003 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006004 .Authorization(TAG_ROLLBACK_RESISTANCE)
6005 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006006 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6007
6008 // Delete must work if rollback protection is implemented
6009 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006010 AuthorizationSet enforced(SecLevelAuthorizations());
6011 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006012
6013 // Delete the key we don't care about the result at this point.
6014 DeleteKey();
6015
6016 // Now create an invalid key blob and delete it.
6017 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
6018
6019 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6020 }
6021}
6022
6023/**
6024 * KeyDeletionTest.DeleteAllKeys
6025 *
6026 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6027 *
6028 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6029 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6030 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6031 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6032 * credentials stored in Keystore/Keymint.
6033 */
6034TEST_P(KeyDeletionTest, DeleteAllKeys) {
6035 if (!arm_deleteAllKeys) return;
6036 auto error = GenerateKey(AuthorizationSetBuilder()
6037 .RsaSigningKey(2048, 65537)
6038 .Digest(Digest::NONE)
6039 .Padding(PaddingMode::NONE)
6040 .Authorization(TAG_NO_AUTH_REQUIRED)
6041 .Authorization(TAG_ROLLBACK_RESISTANCE));
6042 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6043
6044 // Delete must work if rollback protection is implemented
6045 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006046 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006047 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6048
6049 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
6050
6051 string message = "12345678901234567890123456789012";
6052 AuthorizationSet begin_out_params;
6053
6054 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6055 Begin(KeyPurpose::SIGN, key_blob_,
6056 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6057 &begin_out_params));
6058 AbortIfNeeded();
6059 key_blob_ = AidlBuf();
6060 }
6061}
6062
6063INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6064
David Drysdaled2cc8c22021-04-15 13:29:45 +01006065typedef KeyMintAidlTestBase KeyUpgradeTest;
6066
6067/**
6068 * KeyUpgradeTest.UpgradeInvalidKey
6069 *
6070 * This test checks that the HAL excepts invalid key blobs..
6071 */
6072TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6073 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6074
6075 std::vector<uint8_t> new_blob;
6076 Status result = keymint_->upgradeKey(key_blob,
6077 AuthorizationSetBuilder()
6078 .Authorization(TAG_APPLICATION_ID, "clientid")
6079 .Authorization(TAG_APPLICATION_DATA, "appdata")
6080 .vector_data(),
6081 &new_blob);
6082 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6083}
6084
6085INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6086
Selene Huang31ab4042020-04-29 04:22:39 -07006087using UpgradeKeyTest = KeyMintAidlTestBase;
6088
6089/*
6090 * UpgradeKeyTest.UpgradeKey
6091 *
6092 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6093 */
6094TEST_P(UpgradeKeyTest, UpgradeKey) {
6095 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6096 .AesEncryptionKey(128)
6097 .Padding(PaddingMode::NONE)
6098 .Authorization(TAG_NO_AUTH_REQUIRED)));
6099
6100 auto result = UpgradeKey(key_blob_);
6101
6102 // Key doesn't need upgrading. Should get okay, but no new key blob.
6103 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6104}
6105
6106INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6107
6108using ClearOperationsTest = KeyMintAidlTestBase;
6109
6110/*
6111 * ClearSlotsTest.TooManyOperations
6112 *
6113 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6114 * operations are started without being finished or aborted. Also verifies
6115 * that aborting the operations clears the operations.
6116 *
6117 */
6118TEST_P(ClearOperationsTest, TooManyOperations) {
6119 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6120 .Authorization(TAG_NO_AUTH_REQUIRED)
6121 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006122 .Padding(PaddingMode::NONE)
6123 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006124
6125 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6126 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006127 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006128 AuthorizationSet out_params;
6129 ErrorCode result;
6130 size_t i;
6131
6132 for (i = 0; i < max_operations; i++) {
6133 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6134 if (ErrorCode::OK != result) {
6135 break;
6136 }
6137 }
6138 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6139 // Try again just in case there's a weird overflow bug
6140 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6141 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6142 for (size_t j = 0; j < i; j++) {
6143 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6144 << "Aboort failed for i = " << j << std::endl;
6145 }
6146 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6147 AbortIfNeeded();
6148}
6149
6150INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6151
6152typedef KeyMintAidlTestBase TransportLimitTest;
6153
6154/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006155 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006156 *
6157 * Verifies that passing input data to finish succeeds as expected.
6158 */
6159TEST_P(TransportLimitTest, LargeFinishInput) {
6160 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6161 .Authorization(TAG_NO_AUTH_REQUIRED)
6162 .AesEncryptionKey(128)
6163 .BlockMode(BlockMode::ECB)
6164 .Padding(PaddingMode::NONE)));
6165
6166 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6167 auto cipher_params =
6168 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6169
6170 AuthorizationSet out_params;
6171 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6172
6173 string plain_message = std::string(1 << msg_size, 'x');
6174 string encrypted_message;
6175 auto rc = Finish(plain_message, &encrypted_message);
6176
6177 EXPECT_EQ(ErrorCode::OK, rc);
6178 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6179 << "Encrypt finish returned OK, but did not consume all of the given input";
6180 cipher_params.push_back(out_params);
6181
6182 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6183
6184 string decrypted_message;
6185 rc = Finish(encrypted_message, &decrypted_message);
6186 EXPECT_EQ(ErrorCode::OK, rc);
6187 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6188 << "Decrypt finish returned OK, did not consume all of the given input";
6189 }
6190}
6191
6192INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6193
David Zeuthene0c40892021-01-08 12:54:11 -05006194typedef KeyMintAidlTestBase KeyAgreementTest;
6195
6196int CurveToOpenSslCurveName(EcCurve curve) {
6197 switch (curve) {
6198 case EcCurve::P_224:
6199 return NID_secp224r1;
6200 case EcCurve::P_256:
6201 return NID_X9_62_prime256v1;
6202 case EcCurve::P_384:
6203 return NID_secp384r1;
6204 case EcCurve::P_521:
6205 return NID_secp521r1;
6206 }
6207}
6208
6209/*
6210 * KeyAgreementTest.Ecdh
6211 *
6212 * Verifies that ECDH works for all curves
6213 */
6214TEST_P(KeyAgreementTest, Ecdh) {
6215 // Because it's possible to use this API with keys on different curves, we
6216 // check all N^2 combinations where N is the number of supported
6217 // curves.
6218 //
6219 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6220 // lot more curves we can be smart about things and just pick |otherCurve| so
6221 // it's not |curve| and that way we end up with only 2*N runs
6222 //
6223 for (auto curve : ValidCurves()) {
6224 for (auto localCurve : ValidCurves()) {
6225 // Generate EC key locally (with access to private key material)
6226 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6227 int curveName = CurveToOpenSslCurveName(localCurve);
6228 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6229 ASSERT_NE(group, nullptr);
6230 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6231 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6232 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6233 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6234
6235 // Get encoded form of the public part of the locally generated key...
6236 unsigned char* p = nullptr;
6237 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6238 ASSERT_GT(encodedPublicKeySize, 0);
6239 vector<uint8_t> encodedPublicKey(
6240 reinterpret_cast<const uint8_t*>(p),
6241 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6242 OPENSSL_free(p);
6243
6244 // Generate EC key in KeyMint (only access to public key material)
6245 vector<uint8_t> challenge = {0x41, 0x42};
6246 EXPECT_EQ(
6247 ErrorCode::OK,
6248 GenerateKey(AuthorizationSetBuilder()
6249 .Authorization(TAG_NO_AUTH_REQUIRED)
6250 .Authorization(TAG_EC_CURVE, curve)
6251 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6252 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6253 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006254 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6255 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006256 << "Failed to generate key";
6257 ASSERT_GT(cert_chain_.size(), 0);
6258 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6259 ASSERT_NE(kmKeyCert, nullptr);
6260 // Check that keyAgreement (bit 4) is set in KeyUsage
6261 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6262 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6263 ASSERT_NE(kmPkey, nullptr);
6264 if (dump_Attestations) {
6265 for (size_t n = 0; n < cert_chain_.size(); n++) {
6266 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6267 }
6268 }
6269
6270 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6271 if (curve != localCurve) {
6272 // If the keys are using different curves KeyMint should fail with
6273 // ErrorCode:INVALID_ARGUMENT. Check that.
6274 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6275 string ZabFromKeyMintStr;
6276 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6277 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6278 &ZabFromKeyMintStr));
6279
6280 } else {
6281 // Otherwise if the keys are using the same curve, it should work.
6282 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6283 string ZabFromKeyMintStr;
6284 EXPECT_EQ(ErrorCode::OK,
6285 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6286 &ZabFromKeyMintStr));
6287 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6288
6289 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6290 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6291 ASSERT_NE(ctx, nullptr);
6292 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6293 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6294 size_t ZabFromTestLen = 0;
6295 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6296 vector<uint8_t> ZabFromTest;
6297 ZabFromTest.resize(ZabFromTestLen);
6298 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6299
6300 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6301 }
6302
6303 CheckedDeleteKey();
6304 }
6305 }
6306}
6307
6308INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6309
David Drysdaled2cc8c22021-04-15 13:29:45 +01006310using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6311
6312// This is a problematic test, as it can render the device under test permanently unusable.
6313// Re-enable and run at your own risk.
6314TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6315 auto result = DestroyAttestationIds();
6316 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6317}
6318
6319INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6320
Shawn Willdend659c7c2021-02-19 14:51:51 -07006321using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006322
6323TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
6324 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6325 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6326
6327 CheckedDeleteKey(&aesKeyData.blob);
6328 CheckedDeleteKey(&hmacKeyData.blob);
6329 CheckedDeleteKey(&rsaKeyData.blob);
6330 CheckedDeleteKey(&ecdsaKeyData.blob);
6331}
6332
David Drysdaled2cc8c22021-04-15 13:29:45 +01006333// 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 +00006334// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6335// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6336// early boot, so you'll have to reboot between runs.
6337TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6338 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6339 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6340 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6341 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6342 EXPECT_TRUE(
6343 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6344 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6345 EXPECT_TRUE(
6346 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6347
6348 // Should be able to use keys, since early boot has not ended
6349 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6350 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6351 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6352 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6353
6354 // End early boot
6355 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6356 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6357
6358 // Should not be able to use already-created keys.
6359 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6360 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6361 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6362 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6363
6364 CheckedDeleteKey(&aesKeyData.blob);
6365 CheckedDeleteKey(&hmacKeyData.blob);
6366 CheckedDeleteKey(&rsaKeyData.blob);
6367 CheckedDeleteKey(&ecdsaKeyData.blob);
6368
6369 // Should not be able to create new keys
6370 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6371 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6372
6373 CheckedDeleteKey(&aesKeyData.blob);
6374 CheckedDeleteKey(&hmacKeyData.blob);
6375 CheckedDeleteKey(&rsaKeyData.blob);
6376 CheckedDeleteKey(&ecdsaKeyData.blob);
6377}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006378
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006379INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6380
Shawn Willdend659c7c2021-02-19 14:51:51 -07006381using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006382
6383// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6384// between runs... and on most test devices there are no enrolled credentials so it can't be
6385// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6386// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6387// a manual test process, which includes unlocking between runs, which is why it's included here.
6388// Well, that and the fact that it's the only test we can do without also making calls into the
6389// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6390// implications might be, so that may or may not be a solution.
6391TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6392 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6393 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6394
6395 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6396 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6397 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6398 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6399
6400 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006401 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006402 ASSERT_EQ(ErrorCode::OK, rc);
6403 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6404 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6405 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6406 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6407
6408 CheckedDeleteKey(&aesKeyData.blob);
6409 CheckedDeleteKey(&hmacKeyData.blob);
6410 CheckedDeleteKey(&rsaKeyData.blob);
6411 CheckedDeleteKey(&ecdsaKeyData.blob);
6412}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006413
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006414INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6415
Janis Danisevskis24c04702020-12-16 18:28:39 -08006416} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006417
6418int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006419 std::cout << "Testing ";
6420 auto halInstances =
6421 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6422 std::cout << "HAL instances:\n";
6423 for (auto& entry : halInstances) {
6424 std::cout << " " << entry << '\n';
6425 }
6426
Selene Huang31ab4042020-04-29 04:22:39 -07006427 ::testing::InitGoogleTest(&argc, argv);
6428 for (int i = 1; i < argc; ++i) {
6429 if (argv[i][0] == '-') {
6430 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006431 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6432 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006433 }
6434 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006435 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6436 dump_Attestations = true;
6437 } else {
6438 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006439 }
David Drysdalebb3d85e2021-04-13 11:15:51 +01006440 // TODO(drysdale): Remove this flag when available KeyMint devices comply with spec
6441 if (std::string(argv[i]) == "--check_patchLevels") {
6442 aidl::android::hardware::security::keymint::test::check_patchLevels = true;
6443 }
Selene Huang31ab4042020-04-29 04:22:39 -07006444 }
6445 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006446 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006447}