blob: 016a09e302b69ed06f9ae8c73e8f92789d5fd761 [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));
485 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
486
Selene Huang31ab4042020-04-29 04:22:39 -0700487 // Check that some unexpected tags/values are NOT present.
488 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
489 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000490 }
491
492 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
493 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
494 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
495 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
496
497 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
498 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
499 }
500
501 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
502 // TODO(swillden): Distinguish which params should be in which auth list.
503 AuthorizationSet auths;
504 for (auto& entry : keyCharacteristics) {
505 auths.push_back(AuthorizationSet(entry.authorizations));
506 }
507 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
508
509 // Verify that App data, ROT and auth timeout are NOT included.
510 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
511 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700512 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
513
David Drysdaled2cc8c22021-04-15 13:29:45 +0100514 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
515 // never adds it.
516 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
517
David Drysdale7de9feb2021-03-05 14:56:19 +0000518 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700519 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000520 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700521 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700522 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000523 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700524 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000525
David Drysdalebb3d85e2021-04-13 11:15:51 +0100526 if (check_patchLevels) {
527 // Should include vendor and boot patchlevels.
528 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
529 EXPECT_TRUE(vendor_pl);
530 EXPECT_EQ(*vendor_pl, vendor_patch_level());
531 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
532 EXPECT_TRUE(boot_pl);
533 }
534
David Drysdale7de9feb2021-03-05 14:56:19 +0000535 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700536 }
537};
538
539/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000540 * NewKeyGenerationTest.Aes
541 *
542 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
543 * have correct characteristics.
544 */
545TEST_P(NewKeyGenerationTest, Aes) {
546 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
547 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
548 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
549 SCOPED_TRACE(testing::Message()
550 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
551 vector<uint8_t> key_blob;
552 vector<KeyCharacteristics> key_characteristics;
553 auto builder = AuthorizationSetBuilder()
554 .AesEncryptionKey(key_size)
555 .BlockMode(block_mode)
556 .Padding(padding_mode)
557 .SetDefaultValidity();
558 if (block_mode == BlockMode::GCM) {
559 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
560 }
561 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
562
563 EXPECT_GT(key_blob.size(), 0U);
564 CheckSymmetricParams(key_characteristics);
565
566 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
567
568 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
569 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
570 << "Key size " << key_size << "missing";
571
572 CheckedDeleteKey(&key_blob);
573 }
574 }
575 }
576}
577
578/*
579 * NewKeyGenerationTest.AesInvalidSize
580 *
581 * Verifies that specifying an invalid key size for AES key generation returns
582 * UNSUPPORTED_KEY_SIZE.
583 */
584TEST_P(NewKeyGenerationTest, AesInvalidSize) {
585 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
586 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
587 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
588 SCOPED_TRACE(testing::Message()
589 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
590 vector<uint8_t> key_blob;
591 vector<KeyCharacteristics> key_characteristics;
592 auto builder = AuthorizationSetBuilder()
593 .AesEncryptionKey(key_size)
594 .BlockMode(block_mode)
595 .Padding(padding_mode)
596 .SetDefaultValidity();
597 if (block_mode == BlockMode::GCM) {
598 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
599 }
600 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
601 GenerateKey(builder, &key_blob, &key_characteristics));
602 }
603 }
604 }
605
606 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
607 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
608 vector<uint8_t> key_blob;
609 vector<KeyCharacteristics> key_characteristics;
610 // No key size specified
611 auto builder = AuthorizationSetBuilder()
612 .Authorization(TAG_ALGORITHM, Algorithm::AES)
613 .BlockMode(block_mode)
614 .Padding(padding_mode)
615 .SetDefaultValidity();
616 if (block_mode == BlockMode::GCM) {
617 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
618 }
619 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
620 GenerateKey(builder, &key_blob, &key_characteristics));
621 }
622 }
623}
624
625/*
626 * NewKeyGenerationTest.AesInvalidPadding
627 *
628 * Verifies that specifying an invalid padding on AES keys gives a failure
629 * somewhere along the way.
630 */
631TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
632 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
633 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
634 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
635 SCOPED_TRACE(testing::Message()
636 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000637 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800638 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000639 .AesEncryptionKey(key_size)
640 .BlockMode(block_mode)
641 .Padding(padding_mode)
642 .SetDefaultValidity();
643 if (block_mode == BlockMode::GCM) {
644 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
645 }
646
Tommy Chiu3950b452021-05-03 22:01:46 +0800647 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000648 if (result == ErrorCode::OK) {
649 // Key creation was OK but has generated a key that cannot be used.
650 auto params =
651 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800652 if (block_mode == BlockMode::GCM) {
653 params.Authorization(TAG_MAC_LENGTH, 128);
654 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000655 auto result = Begin(KeyPurpose::ENCRYPT, params);
656 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
657 result == ErrorCode::INVALID_KEY_BLOB);
658 } else {
659 // The KeyMint implementation detected that the generated key
660 // is unusable.
661 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
662 }
663 }
664 }
665 }
666}
667
668/*
669 * NewKeyGenerationTest.AesGcmMissingMinMac
670 *
671 * Verifies that specifying an invalid key size for AES key generation returns
672 * UNSUPPORTED_KEY_SIZE.
673 */
674TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
675 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
676 BlockMode block_mode = BlockMode::GCM;
677 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
678 SCOPED_TRACE(testing::Message()
679 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
680 vector<uint8_t> key_blob;
681 vector<KeyCharacteristics> key_characteristics;
682 // No MIN_MAC_LENGTH provided.
683 auto builder = AuthorizationSetBuilder()
684 .AesEncryptionKey(key_size)
685 .BlockMode(block_mode)
686 .Padding(padding_mode)
687 .SetDefaultValidity();
688 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
689 GenerateKey(builder, &key_blob, &key_characteristics));
690 }
691 }
692}
693
694/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100695 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
696 *
697 * Verifies that specifying an invalid min MAC size for AES key generation returns
698 * UNSUPPORTED_MIN_MAC_LENGTH.
699 */
700TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
701 for (size_t min_mac_len : {88, 136}) {
702 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
703 BlockMode block_mode = BlockMode::GCM;
704 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
705 SCOPED_TRACE(testing::Message()
706 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
707 vector<uint8_t> key_blob;
708 vector<KeyCharacteristics> key_characteristics;
709 auto builder = AuthorizationSetBuilder()
710 .AesEncryptionKey(key_size)
711 .BlockMode(block_mode)
712 .Padding(padding_mode)
713 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
714 .SetDefaultValidity();
715 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
716 GenerateKey(builder, &key_blob, &key_characteristics));
717 }
718 }
719 }
720}
721
722/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000723 * NewKeyGenerationTest.TripleDes
724 *
725 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
726 * have correct characteristics.
727 */
728TEST_P(NewKeyGenerationTest, TripleDes) {
729 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
730 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
731 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
732 SCOPED_TRACE(testing::Message()
733 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
734 vector<uint8_t> key_blob;
735 vector<KeyCharacteristics> key_characteristics;
736 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
737 .TripleDesEncryptionKey(key_size)
738 .BlockMode(block_mode)
739 .Padding(padding_mode)
740 .Authorization(TAG_NO_AUTH_REQUIRED)
741 .SetDefaultValidity(),
742 &key_blob, &key_characteristics));
743
744 EXPECT_GT(key_blob.size(), 0U);
745 CheckSymmetricParams(key_characteristics);
746
747 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
748
749 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
750 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
751 << "Key size " << key_size << "missing";
752
753 CheckedDeleteKey(&key_blob);
754 }
755 }
756 }
757}
758
759/*
760 * NewKeyGenerationTest.TripleDesWithAttestation
761 *
762 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
763 * have correct characteristics.
764 *
765 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
766 * put in a certificate) but which isn't an error.
767 */
768TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
769 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
770 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
771 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
772 SCOPED_TRACE(testing::Message()
773 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
774
775 auto challenge = "hello";
776 auto app_id = "foo";
777
778 vector<uint8_t> key_blob;
779 vector<KeyCharacteristics> key_characteristics;
780 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
781 .TripleDesEncryptionKey(key_size)
782 .BlockMode(block_mode)
783 .Padding(padding_mode)
784 .Authorization(TAG_NO_AUTH_REQUIRED)
785 .AttestationChallenge(challenge)
786 .AttestationApplicationId(app_id)
787 .SetDefaultValidity(),
788 &key_blob, &key_characteristics));
789
790 EXPECT_GT(key_blob.size(), 0U);
791 CheckSymmetricParams(key_characteristics);
792
793 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
794
795 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
796 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
797 << "Key size " << key_size << "missing";
798
799 CheckedDeleteKey(&key_blob);
800 }
801 }
802 }
803}
804
805/*
806 * NewKeyGenerationTest.TripleDesInvalidSize
807 *
808 * Verifies that specifying an invalid key size for 3-DES key generation returns
809 * UNSUPPORTED_KEY_SIZE.
810 */
811TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
812 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
813 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
814 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
815 SCOPED_TRACE(testing::Message()
816 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
817 vector<uint8_t> key_blob;
818 vector<KeyCharacteristics> key_characteristics;
819 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
820 GenerateKey(AuthorizationSetBuilder()
821 .TripleDesEncryptionKey(key_size)
822 .BlockMode(block_mode)
823 .Padding(padding_mode)
824 .Authorization(TAG_NO_AUTH_REQUIRED)
825 .SetDefaultValidity(),
826 &key_blob, &key_characteristics));
827 }
828 }
829 }
830
831 // Omitting the key size fails.
832 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
833 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
834 SCOPED_TRACE(testing::Message()
835 << "3DES-default-" << block_mode << "-" << padding_mode);
836 vector<uint8_t> key_blob;
837 vector<KeyCharacteristics> key_characteristics;
838 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
839 GenerateKey(AuthorizationSetBuilder()
840 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
841 .BlockMode(block_mode)
842 .Padding(padding_mode)
843 .Authorization(TAG_NO_AUTH_REQUIRED)
844 .SetDefaultValidity(),
845 &key_blob, &key_characteristics));
846 }
847 }
848}
849
850/*
Selene Huang31ab4042020-04-29 04:22:39 -0700851 * NewKeyGenerationTest.Rsa
852 *
853 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
854 * have correct characteristics.
855 */
856TEST_P(NewKeyGenerationTest, Rsa) {
857 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
858 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700859 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700860 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
861 .RsaSigningKey(key_size, 65537)
862 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800863 .Padding(PaddingMode::NONE)
864 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700865 &key_blob, &key_characteristics));
866
867 ASSERT_GT(key_blob.size(), 0U);
868 CheckBaseParams(key_characteristics);
869
Shawn Willden7f424372021-01-10 18:06:50 -0700870 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700871
872 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
873 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
874 << "Key size " << key_size << "missing";
875 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
876
877 CheckedDeleteKey(&key_blob);
878 }
879}
880
881/*
Qi Wud22ec842020-11-26 13:27:53 +0800882 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700883 *
David Drysdaled2cc8c22021-04-15 13:29:45 +0100884 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
885 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700886 */
887TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700888 auto challenge = "hello";
889 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700890
Selene Huang6e46f142021-04-20 19:20:11 -0700891 auto subject = "cert subj 2";
892 vector<uint8_t> subject_der(make_name_from_str(subject));
893
894 uint64_t serial_int = 66;
895 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
896
Selene Huang4f64c222021-04-13 19:54:36 -0700897 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700898 vector<uint8_t> key_blob;
899 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700900 ASSERT_EQ(ErrorCode::OK,
901 GenerateKey(AuthorizationSetBuilder()
902 .RsaSigningKey(key_size, 65537)
903 .Digest(Digest::NONE)
904 .Padding(PaddingMode::NONE)
905 .AttestationChallenge(challenge)
906 .AttestationApplicationId(app_id)
907 .Authorization(TAG_NO_AUTH_REQUIRED)
908 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
909 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
910 .SetDefaultValidity(),
911 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700912
913 ASSERT_GT(key_blob.size(), 0U);
914 CheckBaseParams(key_characteristics);
915
916 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
917
918 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
919 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
920 << "Key size " << key_size << "missing";
921 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
922
Selene Huang6e46f142021-04-20 19:20:11 -0700923 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700924 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700925 ASSERT_GT(cert_chain_.size(), 0);
926
927 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
928 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
929 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
930 sw_enforced, hw_enforced, SecLevel(),
931 cert_chain_[0].encodedCertificate));
932
933 CheckedDeleteKey(&key_blob);
934 }
935}
936
937/*
David Drysdale4dc01072021-04-01 12:17:35 +0100938 * NewKeyGenerationTest.RsaWithRpkAttestation
939 *
940 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
941 * that has been generated using an associate IRemotelyProvisionedComponent.
942 */
943TEST_P(NewKeyGenerationTest, RsaWithRpkAttestation) {
944 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
945 // instance.
946 std::shared_ptr<IRemotelyProvisionedComponent> rp;
947 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
948 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
949
950 // Generate a P-256 keypair to use as an attestation key.
951 MacedPublicKey macedPubKey;
952 std::vector<uint8_t> privateKeyBlob;
953 auto status =
954 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
955 ASSERT_TRUE(status.isOk());
956 vector<uint8_t> coseKeyData;
957 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
958
959 AttestationKey attestation_key;
960 attestation_key.keyBlob = std::move(privateKeyBlob);
961 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
962
963 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
964 auto challenge = "hello";
965 auto app_id = "foo";
966
967 vector<uint8_t> key_blob;
968 vector<KeyCharacteristics> key_characteristics;
969 ASSERT_EQ(ErrorCode::OK,
970 GenerateKey(AuthorizationSetBuilder()
971 .RsaSigningKey(key_size, 65537)
972 .Digest(Digest::NONE)
973 .Padding(PaddingMode::NONE)
974 .AttestationChallenge(challenge)
975 .AttestationApplicationId(app_id)
976 .Authorization(TAG_NO_AUTH_REQUIRED)
977 .SetDefaultValidity(),
978 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
979
980 ASSERT_GT(key_blob.size(), 0U);
981 CheckBaseParams(key_characteristics);
982
983 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
984
985 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
986 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
987 << "Key size " << key_size << "missing";
988 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
989
990 // Attestation by itself is not valid (last entry is not self-signed).
991 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
992
993 // The signature over the attested key should correspond to the P256 public key.
994 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
995 ASSERT_TRUE(key_cert.get());
996 EVP_PKEY_Ptr signing_pubkey;
997 p256_pub_key(coseKeyData, &signing_pubkey);
998 ASSERT_TRUE(signing_pubkey.get());
999
1000 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1001 << "Verification of attested certificate failed "
1002 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1003
1004 CheckedDeleteKey(&key_blob);
1005 }
1006}
1007
1008/*
Selene Huang4f64c222021-04-13 19:54:36 -07001009 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1010 *
1011 * Verifies that keymint attestation for RSA encryption keys with challenge and
1012 * app id is also successful.
1013 */
1014TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1015 auto key_size = 2048;
1016 auto challenge = "hello";
1017 auto app_id = "foo";
1018
Selene Huang6e46f142021-04-20 19:20:11 -07001019 auto subject = "subj 2";
1020 vector<uint8_t> subject_der(make_name_from_str(subject));
1021
1022 uint64_t serial_int = 111166;
1023 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1024
Selene Huang4f64c222021-04-13 19:54:36 -07001025 vector<uint8_t> key_blob;
1026 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001027 ASSERT_EQ(ErrorCode::OK,
1028 GenerateKey(AuthorizationSetBuilder()
1029 .RsaEncryptionKey(key_size, 65537)
1030 .Padding(PaddingMode::NONE)
1031 .AttestationChallenge(challenge)
1032 .AttestationApplicationId(app_id)
1033 .Authorization(TAG_NO_AUTH_REQUIRED)
1034 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1035 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1036 .SetDefaultValidity(),
1037 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001038
1039 ASSERT_GT(key_blob.size(), 0U);
1040 AuthorizationSet auths;
1041 for (auto& entry : key_characteristics) {
1042 auths.push_back(AuthorizationSet(entry.authorizations));
1043 }
1044
1045 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1046 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1047
1048 // Verify that App data and ROT are NOT included.
1049 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1050 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1051
1052 // Check that some unexpected tags/values are NOT present.
1053 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1054 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1055
1056 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1057
1058 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1059 ASSERT_TRUE(os_ver);
1060 EXPECT_EQ(*os_ver, os_version());
1061
1062 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1063
1064 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1065 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1066 << "Key size " << key_size << "missing";
1067 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1068
Selene Huang6e46f142021-04-20 19:20:11 -07001069 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001070 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1071 ASSERT_GT(cert_chain_.size(), 0);
1072
1073 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1074 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1075 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1076 sw_enforced, hw_enforced, SecLevel(),
1077 cert_chain_[0].encodedCertificate));
1078
1079 CheckedDeleteKey(&key_blob);
1080}
1081
1082/*
1083 * NewKeyGenerationTest.RsaWithSelfSign
1084 *
1085 * Verifies that attesting to RSA key generation is successful, and returns
1086 * self signed certificate if no challenge is provided. And signing etc
1087 * works as expected.
1088 */
1089TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001090 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1091 vector<uint8_t> subject_der(make_name_from_str(subject));
1092
1093 uint64_t serial_int = 0;
1094 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1095
Selene Huang4f64c222021-04-13 19:54:36 -07001096 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1097 vector<uint8_t> key_blob;
1098 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001099 ASSERT_EQ(ErrorCode::OK,
1100 GenerateKey(AuthorizationSetBuilder()
1101 .RsaSigningKey(key_size, 65537)
1102 .Digest(Digest::NONE)
1103 .Padding(PaddingMode::NONE)
1104 .Authorization(TAG_NO_AUTH_REQUIRED)
1105 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1106 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1107 .SetDefaultValidity(),
1108 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001109
1110 ASSERT_GT(key_blob.size(), 0U);
1111 CheckBaseParams(key_characteristics);
1112
1113 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1114
1115 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1116 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1117 << "Key size " << key_size << "missing";
1118 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1119
Selene Huang6e46f142021-04-20 19:20:11 -07001120 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001121 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1122 ASSERT_EQ(cert_chain_.size(), 1);
1123
1124 CheckedDeleteKey(&key_blob);
1125 }
1126}
1127
1128/*
1129 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1130 *
1131 * Verifies that attesting to RSA checks for missing app ID.
1132 */
1133TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1134 auto challenge = "hello";
1135 vector<uint8_t> key_blob;
1136 vector<KeyCharacteristics> key_characteristics;
1137
1138 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1139 GenerateKey(AuthorizationSetBuilder()
1140 .RsaSigningKey(2048, 65537)
1141 .Digest(Digest::NONE)
1142 .Padding(PaddingMode::NONE)
1143 .AttestationChallenge(challenge)
1144 .Authorization(TAG_NO_AUTH_REQUIRED)
1145 .SetDefaultValidity(),
1146 &key_blob, &key_characteristics));
1147}
1148
1149/*
1150 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1151 *
1152 * Verifies that attesting to RSA ignores app id if challenge is missing.
1153 */
1154TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1155 auto key_size = 2048;
1156 auto app_id = "foo";
1157
Selene Huang6e46f142021-04-20 19:20:11 -07001158 auto subject = "cert subj 2";
1159 vector<uint8_t> subject_der(make_name_from_str(subject));
1160
1161 uint64_t serial_int = 1;
1162 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1163
Selene Huang4f64c222021-04-13 19:54:36 -07001164 vector<uint8_t> key_blob;
1165 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001166 ASSERT_EQ(ErrorCode::OK,
1167 GenerateKey(AuthorizationSetBuilder()
1168 .RsaSigningKey(key_size, 65537)
1169 .Digest(Digest::NONE)
1170 .Padding(PaddingMode::NONE)
1171 .AttestationApplicationId(app_id)
1172 .Authorization(TAG_NO_AUTH_REQUIRED)
1173 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1174 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1175 .SetDefaultValidity(),
1176 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001177
1178 ASSERT_GT(key_blob.size(), 0U);
1179 CheckBaseParams(key_characteristics);
1180
1181 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1182
1183 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1184 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1185 << "Key size " << key_size << "missing";
1186 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1187
Selene Huang6e46f142021-04-20 19:20:11 -07001188 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001189 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1190 ASSERT_EQ(cert_chain_.size(), 1);
1191
1192 CheckedDeleteKey(&key_blob);
1193}
1194
1195/*
Qi Wud22ec842020-11-26 13:27:53 +08001196 * NewKeyGenerationTest.LimitedUsageRsa
1197 *
1198 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1199 * resulting keys have correct characteristics.
1200 */
1201TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1202 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1203 vector<uint8_t> key_blob;
1204 vector<KeyCharacteristics> key_characteristics;
1205 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1206 .RsaSigningKey(key_size, 65537)
1207 .Digest(Digest::NONE)
1208 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001209 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1210 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001211 &key_blob, &key_characteristics));
1212
1213 ASSERT_GT(key_blob.size(), 0U);
1214 CheckBaseParams(key_characteristics);
1215
1216 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1217
1218 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1219 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1220 << "Key size " << key_size << "missing";
1221 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1222
1223 // Check the usage count limit tag appears in the authorizations.
1224 AuthorizationSet auths;
1225 for (auto& entry : key_characteristics) {
1226 auths.push_back(AuthorizationSet(entry.authorizations));
1227 }
1228 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1229 << "key usage count limit " << 1U << " missing";
1230
1231 CheckedDeleteKey(&key_blob);
1232 }
1233}
1234
1235/*
Qi Wubeefae42021-01-28 23:16:37 +08001236 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1237 *
1238 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1239 * resulting keys have correct characteristics and attestation.
1240 */
1241TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001242 auto challenge = "hello";
1243 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001244
Selene Huang6e46f142021-04-20 19:20:11 -07001245 auto subject = "cert subj 2";
1246 vector<uint8_t> subject_der(make_name_from_str(subject));
1247
1248 uint64_t serial_int = 66;
1249 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1250
Selene Huang4f64c222021-04-13 19:54:36 -07001251 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001252 vector<uint8_t> key_blob;
1253 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001254 ASSERT_EQ(ErrorCode::OK,
1255 GenerateKey(AuthorizationSetBuilder()
1256 .RsaSigningKey(key_size, 65537)
1257 .Digest(Digest::NONE)
1258 .Padding(PaddingMode::NONE)
1259 .AttestationChallenge(challenge)
1260 .AttestationApplicationId(app_id)
1261 .Authorization(TAG_NO_AUTH_REQUIRED)
1262 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1263 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1264 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1265 .SetDefaultValidity(),
1266 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001267
1268 ASSERT_GT(key_blob.size(), 0U);
1269 CheckBaseParams(key_characteristics);
1270
1271 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1272
1273 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1274 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1275 << "Key size " << key_size << "missing";
1276 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1277
1278 // Check the usage count limit tag appears in the authorizations.
1279 AuthorizationSet auths;
1280 for (auto& entry : key_characteristics) {
1281 auths.push_back(AuthorizationSet(entry.authorizations));
1282 }
1283 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1284 << "key usage count limit " << 1U << " missing";
1285
1286 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001287 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001288 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001289 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001290
1291 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1292 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1293 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1294 sw_enforced, hw_enforced, SecLevel(),
1295 cert_chain_[0].encodedCertificate));
1296
1297 CheckedDeleteKey(&key_blob);
1298 }
1299}
1300
1301/*
Selene Huang31ab4042020-04-29 04:22:39 -07001302 * NewKeyGenerationTest.NoInvalidRsaSizes
1303 *
1304 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1305 */
1306TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1307 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1308 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001309 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001310 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1311 GenerateKey(AuthorizationSetBuilder()
1312 .RsaSigningKey(key_size, 65537)
1313 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001314 .Padding(PaddingMode::NONE)
1315 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001316 &key_blob, &key_characteristics));
1317 }
1318}
1319
1320/*
1321 * NewKeyGenerationTest.RsaNoDefaultSize
1322 *
1323 * Verifies that failing to specify a key size for RSA key generation returns
1324 * UNSUPPORTED_KEY_SIZE.
1325 */
1326TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1327 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1328 GenerateKey(AuthorizationSetBuilder()
1329 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1330 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001331 .SigningKey()
1332 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001333}
1334
1335/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001336 * NewKeyGenerationTest.RsaMissingParams
1337 *
1338 * Verifies that omitting optional tags works.
1339 */
1340TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1341 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1342 ASSERT_EQ(ErrorCode::OK,
1343 GenerateKey(
1344 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1345 CheckedDeleteKey();
1346 }
1347}
1348
1349/*
Selene Huang31ab4042020-04-29 04:22:39 -07001350 * NewKeyGenerationTest.Ecdsa
1351 *
1352 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1353 * have correct characteristics.
1354 */
1355TEST_P(NewKeyGenerationTest, Ecdsa) {
1356 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1357 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001358 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001359 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1360 .EcdsaSigningKey(key_size)
1361 .Digest(Digest::NONE)
1362 .SetDefaultValidity(),
1363 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001364 ASSERT_GT(key_blob.size(), 0U);
1365 CheckBaseParams(key_characteristics);
1366
Shawn Willden7f424372021-01-10 18:06:50 -07001367 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001368
1369 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1370 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1371 << "Key size " << key_size << "missing";
1372
1373 CheckedDeleteKey(&key_blob);
1374 }
1375}
1376
1377/*
Selene Huang4f64c222021-04-13 19:54:36 -07001378 * NewKeyGenerationTest.EcdsaAttestation
1379 *
1380 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1381 * an attestation will be generated.
1382 */
1383TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1384 auto challenge = "hello";
1385 auto app_id = "foo";
1386
Selene Huang6e46f142021-04-20 19:20:11 -07001387 auto subject = "cert subj 2";
1388 vector<uint8_t> subject_der(make_name_from_str(subject));
1389
1390 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1391 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1392
Selene Huang4f64c222021-04-13 19:54:36 -07001393 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1394 vector<uint8_t> key_blob;
1395 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001396 ASSERT_EQ(ErrorCode::OK,
1397 GenerateKey(AuthorizationSetBuilder()
1398 .Authorization(TAG_NO_AUTH_REQUIRED)
1399 .EcdsaSigningKey(key_size)
1400 .Digest(Digest::NONE)
1401 .AttestationChallenge(challenge)
1402 .AttestationApplicationId(app_id)
1403 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1404 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1405 .SetDefaultValidity(),
1406 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001407 ASSERT_GT(key_blob.size(), 0U);
1408 CheckBaseParams(key_characteristics);
1409
1410 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1411
1412 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1413 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1414 << "Key size " << key_size << "missing";
1415
1416 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1417 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001418 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001419
1420 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1421 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1422 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1423 sw_enforced, hw_enforced, SecLevel(),
1424 cert_chain_[0].encodedCertificate));
1425
1426 CheckedDeleteKey(&key_blob);
1427 }
1428}
1429
1430/*
1431 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1432 *
1433 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1434 * the key will generate a self signed attestation.
1435 */
1436TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001437 auto subject = "cert subj 2";
1438 vector<uint8_t> subject_der(make_name_from_str(subject));
1439
1440 uint64_t serial_int = 0x123456FFF1234;
1441 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1442
Selene Huang4f64c222021-04-13 19:54:36 -07001443 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1444 vector<uint8_t> key_blob;
1445 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001446 ASSERT_EQ(ErrorCode::OK,
1447 GenerateKey(AuthorizationSetBuilder()
1448 .EcdsaSigningKey(key_size)
1449 .Digest(Digest::NONE)
1450 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1451 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1452 .SetDefaultValidity(),
1453 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001454 ASSERT_GT(key_blob.size(), 0U);
1455 CheckBaseParams(key_characteristics);
1456
1457 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1458
1459 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1460 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1461 << "Key size " << key_size << "missing";
1462
1463 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001464 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001465 ASSERT_EQ(cert_chain_.size(), 1);
1466
1467 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1468 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1469
1470 CheckedDeleteKey(&key_blob);
1471 }
1472}
1473
1474/*
1475 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1476 *
1477 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1478 * app id must also be provided or else it will fail.
1479 */
1480TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1481 auto challenge = "hello";
1482 vector<uint8_t> key_blob;
1483 vector<KeyCharacteristics> key_characteristics;
1484
1485 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1486 GenerateKey(AuthorizationSetBuilder()
1487 .EcdsaSigningKey(EcCurve::P_256)
1488 .Digest(Digest::NONE)
1489 .AttestationChallenge(challenge)
1490 .SetDefaultValidity(),
1491 &key_blob, &key_characteristics));
1492}
1493
1494/*
1495 * NewKeyGenerationTest.EcdsaIgnoreAppId
1496 *
1497 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1498 * any appid will be ignored, and keymint will generate a self sign certificate.
1499 */
1500TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1501 auto app_id = "foo";
1502
1503 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1504 vector<uint8_t> key_blob;
1505 vector<KeyCharacteristics> key_characteristics;
1506 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1507 .EcdsaSigningKey(key_size)
1508 .Digest(Digest::NONE)
1509 .AttestationApplicationId(app_id)
1510 .SetDefaultValidity(),
1511 &key_blob, &key_characteristics));
1512
1513 ASSERT_GT(key_blob.size(), 0U);
1514 CheckBaseParams(key_characteristics);
1515
1516 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1517
1518 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1519 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1520 << "Key size " << key_size << "missing";
1521
1522 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1523 ASSERT_EQ(cert_chain_.size(), 1);
1524
1525 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1526 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1527
1528 CheckedDeleteKey(&key_blob);
1529 }
1530}
1531
1532/*
1533 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1534 *
1535 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1536 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1537 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1538 * to specify how many following bytes will be used to encode the length.
1539 */
1540TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1541 auto challenge = "hello";
1542 auto key_size = 256;
1543 std::vector<uint32_t> app_id_lengths{143, 258};
1544
1545 for (uint32_t length : app_id_lengths) {
1546 const string app_id(length, 'a');
1547 vector<uint8_t> key_blob;
1548 vector<KeyCharacteristics> key_characteristics;
1549 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1550 .Authorization(TAG_NO_AUTH_REQUIRED)
1551 .EcdsaSigningKey(key_size)
1552 .Digest(Digest::NONE)
1553 .AttestationChallenge(challenge)
1554 .AttestationApplicationId(app_id)
1555 .SetDefaultValidity(),
1556 &key_blob, &key_characteristics));
1557 ASSERT_GT(key_blob.size(), 0U);
1558 CheckBaseParams(key_characteristics);
1559
1560 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1561
1562 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1563 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1564 << "Key size " << key_size << "missing";
1565
1566 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1567 ASSERT_GT(cert_chain_.size(), 0);
1568
1569 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1570 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1571 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1572 sw_enforced, hw_enforced, SecLevel(),
1573 cert_chain_[0].encodedCertificate));
1574
1575 CheckedDeleteKey(&key_blob);
1576 }
1577}
1578
1579/*
Qi Wud22ec842020-11-26 13:27:53 +08001580 * NewKeyGenerationTest.LimitedUsageEcdsa
1581 *
1582 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1583 * resulting keys have correct characteristics.
1584 */
1585TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
1586 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1587 vector<uint8_t> key_blob;
1588 vector<KeyCharacteristics> key_characteristics;
1589 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1590 .EcdsaSigningKey(key_size)
1591 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001592 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1593 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001594 &key_blob, &key_characteristics));
1595
1596 ASSERT_GT(key_blob.size(), 0U);
1597 CheckBaseParams(key_characteristics);
1598
1599 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1600
1601 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1602 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1603 << "Key size " << key_size << "missing";
1604
1605 // Check the usage count limit tag appears in the authorizations.
1606 AuthorizationSet auths;
1607 for (auto& entry : key_characteristics) {
1608 auths.push_back(AuthorizationSet(entry.authorizations));
1609 }
1610 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1611 << "key usage count limit " << 1U << " missing";
1612
1613 CheckedDeleteKey(&key_blob);
1614 }
1615}
1616
1617/*
Selene Huang31ab4042020-04-29 04:22:39 -07001618 * NewKeyGenerationTest.EcdsaDefaultSize
1619 *
1620 * Verifies that failing to specify a key size for EC key generation returns
1621 * UNSUPPORTED_KEY_SIZE.
1622 */
1623TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1624 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1625 GenerateKey(AuthorizationSetBuilder()
1626 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1627 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001628 .Digest(Digest::NONE)
1629 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001630}
1631
1632/*
1633 * NewKeyGenerationTest.EcdsaInvalidSize
1634 *
1635 * Verifies that specifying an invalid key size for EC key generation returns
1636 * UNSUPPORTED_KEY_SIZE.
1637 */
1638TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
1639 for (auto key_size : InvalidKeySizes(Algorithm::EC)) {
1640 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001641 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001642 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1643 .EcdsaSigningKey(key_size)
1644 .Digest(Digest::NONE)
1645 .SetDefaultValidity(),
1646 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001647 }
1648
Janis Danisevskis164bb872021-02-09 11:30:25 -08001649 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1650 .EcdsaSigningKey(190)
1651 .Digest(Digest::NONE)
1652 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001653}
1654
1655/*
1656 * NewKeyGenerationTest.EcdsaMismatchKeySize
1657 *
1658 * Verifies that specifying mismatched key size and curve for EC key generation returns
1659 * INVALID_ARGUMENT.
1660 */
1661TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1662 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1663
1664 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT,
1665 GenerateKey(AuthorizationSetBuilder()
1666 .EcdsaSigningKey(224)
1667 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001668 .Digest(Digest::NONE)
1669 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001670}
1671
1672/*
1673 * NewKeyGenerationTest.EcdsaAllValidSizes
1674 *
1675 * Verifies that keymint supports all required EC key sizes.
1676 */
1677TEST_P(NewKeyGenerationTest, EcdsaAllValidSizes) {
1678 auto valid_sizes = ValidKeySizes(Algorithm::EC);
1679 for (size_t size : valid_sizes) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001680 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1681 .EcdsaSigningKey(size)
1682 .Digest(Digest::NONE)
1683 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001684 << "Failed to generate size: " << size;
1685 CheckedDeleteKey();
1686 }
1687}
1688
1689/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001690 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07001691 *
1692 * Verifies that keymint does not support any curve designated as unsupported.
1693 */
1694TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1695 Digest digest;
1696 if (SecLevel() == SecurityLevel::STRONGBOX) {
1697 digest = Digest::SHA_2_256;
1698 } else {
1699 digest = Digest::SHA_2_512;
1700 }
1701 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001702 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1703 .EcdsaSigningKey(curve)
1704 .Digest(digest)
1705 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001706 << "Failed to generate key on curve: " << curve;
1707 CheckedDeleteKey();
1708 }
1709}
1710
1711/*
1712 * NewKeyGenerationTest.Hmac
1713 *
1714 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1715 * characteristics.
1716 */
1717TEST_P(NewKeyGenerationTest, Hmac) {
1718 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1719 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001720 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001721 constexpr size_t key_size = 128;
1722 ASSERT_EQ(ErrorCode::OK,
1723 GenerateKey(
1724 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1725 TAG_MIN_MAC_LENGTH, 128),
1726 &key_blob, &key_characteristics));
1727
1728 ASSERT_GT(key_blob.size(), 0U);
1729 CheckBaseParams(key_characteristics);
1730
Shawn Willden7f424372021-01-10 18:06:50 -07001731 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1732 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1733 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1734 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001735
1736 CheckedDeleteKey(&key_blob);
1737 }
1738}
1739
1740/*
Selene Huang4f64c222021-04-13 19:54:36 -07001741 * NewKeyGenerationTest.HmacNoAttestation
1742 *
1743 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1744 * and app id are provided.
1745 */
1746TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1747 auto challenge = "hello";
1748 auto app_id = "foo";
1749
1750 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1751 vector<uint8_t> key_blob;
1752 vector<KeyCharacteristics> key_characteristics;
1753 constexpr size_t key_size = 128;
1754 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1755 .HmacKey(key_size)
1756 .Digest(digest)
1757 .AttestationChallenge(challenge)
1758 .AttestationApplicationId(app_id)
1759 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1760 &key_blob, &key_characteristics));
1761
1762 ASSERT_GT(key_blob.size(), 0U);
1763 ASSERT_EQ(cert_chain_.size(), 0);
1764 CheckBaseParams(key_characteristics);
1765
1766 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1767 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1768 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1769 << "Key size " << key_size << "missing";
1770
1771 CheckedDeleteKey(&key_blob);
1772 }
1773}
1774
1775/*
Qi Wud22ec842020-11-26 13:27:53 +08001776 * NewKeyGenerationTest.LimitedUsageHmac
1777 *
1778 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1779 * resulting keys have correct characteristics.
1780 */
1781TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1782 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1783 vector<uint8_t> key_blob;
1784 vector<KeyCharacteristics> key_characteristics;
1785 constexpr size_t key_size = 128;
1786 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1787 .HmacKey(key_size)
1788 .Digest(digest)
1789 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1790 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1791 &key_blob, &key_characteristics));
1792
1793 ASSERT_GT(key_blob.size(), 0U);
1794 CheckBaseParams(key_characteristics);
1795
1796 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1797 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1798 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1799 << "Key size " << key_size << "missing";
1800
1801 // Check the usage count limit tag appears in the authorizations.
1802 AuthorizationSet auths;
1803 for (auto& entry : key_characteristics) {
1804 auths.push_back(AuthorizationSet(entry.authorizations));
1805 }
1806 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1807 << "key usage count limit " << 1U << " missing";
1808
1809 CheckedDeleteKey(&key_blob);
1810 }
1811}
1812
1813/*
Selene Huang31ab4042020-04-29 04:22:39 -07001814 * NewKeyGenerationTest.HmacCheckKeySizes
1815 *
1816 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1817 */
1818TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1819 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1820 if (key_size < 64 || key_size % 8 != 0) {
1821 // To keep this test from being very slow, we only test a random fraction of
1822 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1823 // them, we expect to run ~40 of them in each run.
1824 if (key_size % 8 == 0 || random() % 10 == 0) {
1825 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1826 GenerateKey(AuthorizationSetBuilder()
1827 .HmacKey(key_size)
1828 .Digest(Digest::SHA_2_256)
1829 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1830 << "HMAC key size " << key_size << " invalid";
1831 }
1832 } else {
1833 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1834 .HmacKey(key_size)
1835 .Digest(Digest::SHA_2_256)
1836 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1837 << "Failed to generate HMAC key of size " << key_size;
1838 CheckedDeleteKey();
1839 }
1840 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01001841 if (SecLevel() == SecurityLevel::STRONGBOX) {
1842 // STRONGBOX devices must not support keys larger than 512 bits.
1843 size_t key_size = 520;
1844 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1845 GenerateKey(AuthorizationSetBuilder()
1846 .HmacKey(key_size)
1847 .Digest(Digest::SHA_2_256)
1848 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1849 << "HMAC key size " << key_size << " unexpectedly valid";
1850 }
Selene Huang31ab4042020-04-29 04:22:39 -07001851}
1852
1853/*
1854 * NewKeyGenerationTest.HmacCheckMinMacLengths
1855 *
1856 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
1857 * test is probabilistic in order to keep the runtime down, but any failure prints out the
1858 * specific MAC length that failed, so reproducing a failed run will be easy.
1859 */
1860TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
1861 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
1862 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
1863 // To keep this test from being very long, we only test a random fraction of
1864 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
1865 // we expect to run ~17 of them in each run.
1866 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
1867 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
1868 GenerateKey(AuthorizationSetBuilder()
1869 .HmacKey(128)
1870 .Digest(Digest::SHA_2_256)
1871 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1872 << "HMAC min mac length " << min_mac_length << " invalid.";
1873 }
1874 } else {
1875 EXPECT_EQ(ErrorCode::OK,
1876 GenerateKey(AuthorizationSetBuilder()
1877 .HmacKey(128)
1878 .Digest(Digest::SHA_2_256)
1879 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1880 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
1881 CheckedDeleteKey();
1882 }
1883 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01001884
1885 // Minimum MAC length must be no more than 512 bits.
1886 size_t min_mac_length = 520;
1887 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
1888 GenerateKey(AuthorizationSetBuilder()
1889 .HmacKey(128)
1890 .Digest(Digest::SHA_2_256)
1891 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1892 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07001893}
1894
1895/*
1896 * NewKeyGenerationTest.HmacMultipleDigests
1897 *
1898 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
1899 */
1900TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
1901 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1902
1903 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1904 GenerateKey(AuthorizationSetBuilder()
1905 .HmacKey(128)
1906 .Digest(Digest::SHA1)
1907 .Digest(Digest::SHA_2_256)
1908 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1909}
1910
1911/*
1912 * NewKeyGenerationTest.HmacDigestNone
1913 *
1914 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
1915 */
1916TEST_P(NewKeyGenerationTest, HmacDigestNone) {
1917 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1918 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
1919 128)));
1920
1921 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1922 GenerateKey(AuthorizationSetBuilder()
1923 .HmacKey(128)
1924 .Digest(Digest::NONE)
1925 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1926}
1927
Selene Huang4f64c222021-04-13 19:54:36 -07001928/*
1929 * NewKeyGenerationTest.AesNoAttestation
1930 *
1931 * Verifies that attestation parameters to AES keys are ignored and generateKey
1932 * will succeed.
1933 */
1934TEST_P(NewKeyGenerationTest, AesNoAttestation) {
1935 auto challenge = "hello";
1936 auto app_id = "foo";
1937
1938 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1939 .Authorization(TAG_NO_AUTH_REQUIRED)
1940 .AesEncryptionKey(128)
1941 .EcbMode()
1942 .Padding(PaddingMode::PKCS7)
1943 .AttestationChallenge(challenge)
1944 .AttestationApplicationId(app_id)));
1945
1946 ASSERT_EQ(cert_chain_.size(), 0);
1947}
1948
1949/*
1950 * NewKeyGenerationTest.TripleDesNoAttestation
1951 *
1952 * Verifies that attesting parameters to 3DES keys are ignored and generate key
1953 * will be successful. No attestation should be generated.
1954 */
1955TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
1956 auto challenge = "hello";
1957 auto app_id = "foo";
1958
1959 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1960 .TripleDesEncryptionKey(168)
1961 .BlockMode(BlockMode::ECB)
1962 .Authorization(TAG_NO_AUTH_REQUIRED)
1963 .Padding(PaddingMode::NONE)
1964 .AttestationChallenge(challenge)
1965 .AttestationApplicationId(app_id)));
1966 ASSERT_EQ(cert_chain_.size(), 0);
1967}
1968
Selene Huang31ab4042020-04-29 04:22:39 -07001969INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
1970
1971typedef KeyMintAidlTestBase SigningOperationsTest;
1972
1973/*
1974 * SigningOperationsTest.RsaSuccess
1975 *
1976 * Verifies that raw RSA signature operations succeed.
1977 */
1978TEST_P(SigningOperationsTest, RsaSuccess) {
1979 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1980 .RsaSigningKey(2048, 65537)
1981 .Digest(Digest::NONE)
1982 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001983 .Authorization(TAG_NO_AUTH_REQUIRED)
1984 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001985 string message = "12345678901234567890123456789012";
1986 string signature = SignMessage(
1987 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1988}
1989
1990/*
1991 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
1992 *
Shawn Willden7f424372021-01-10 18:06:50 -07001993 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07001994 */
1995TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
1996 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1997 .Authorization(TAG_NO_AUTH_REQUIRED)
1998 .RsaSigningKey(2048, 65537)
1999 .Digest(Digest::NONE)
2000 .Padding(PaddingMode::NONE)
2001 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002002 .Authorization(TAG_APPLICATION_DATA, "appdata")
2003 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002004 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2005 Begin(KeyPurpose::SIGN,
2006 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2007 AbortIfNeeded();
2008 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2009 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2010 .Digest(Digest::NONE)
2011 .Padding(PaddingMode::NONE)
2012 .Authorization(TAG_APPLICATION_ID, "clientid")));
2013 AbortIfNeeded();
2014 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2015 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2016 .Digest(Digest::NONE)
2017 .Padding(PaddingMode::NONE)
2018 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2019 AbortIfNeeded();
2020 EXPECT_EQ(ErrorCode::OK,
2021 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2022 .Digest(Digest::NONE)
2023 .Padding(PaddingMode::NONE)
2024 .Authorization(TAG_APPLICATION_DATA, "appdata")
2025 .Authorization(TAG_APPLICATION_ID, "clientid")));
2026 AbortIfNeeded();
2027}
2028
2029/*
2030 * SigningOperationsTest.RsaPssSha256Success
2031 *
2032 * Verifies that RSA-PSS signature operations succeed.
2033 */
2034TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2035 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2036 .RsaSigningKey(2048, 65537)
2037 .Digest(Digest::SHA_2_256)
2038 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002039 .Authorization(TAG_NO_AUTH_REQUIRED)
2040 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002041 // Use large message, which won't work without digesting.
2042 string message(1024, 'a');
2043 string signature = SignMessage(
2044 message,
2045 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2046}
2047
2048/*
2049 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2050 *
2051 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2052 * supports only unpadded operations.
2053 */
2054TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2055 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2056 .RsaSigningKey(2048, 65537)
2057 .Digest(Digest::NONE)
2058 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002059 .Padding(PaddingMode::NONE)
2060 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002061 string message = "12345678901234567890123456789012";
2062 string signature;
2063
2064 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2065 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2066 .Digest(Digest::NONE)
2067 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2068}
2069
2070/*
2071 * SigningOperationsTest.NoUserConfirmation
2072 *
2073 * Verifies that keymint rejects signing operations for keys with
2074 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2075 * presented.
2076 */
2077TEST_P(SigningOperationsTest, NoUserConfirmation) {
2078 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08002079 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2080 .RsaSigningKey(1024, 65537)
2081 .Digest(Digest::NONE)
2082 .Padding(PaddingMode::NONE)
2083 .Authorization(TAG_NO_AUTH_REQUIRED)
2084 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2085 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002086
2087 const string message = "12345678901234567890123456789012";
2088 EXPECT_EQ(ErrorCode::OK,
2089 Begin(KeyPurpose::SIGN,
2090 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2091 string signature;
2092 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2093}
2094
2095/*
2096 * SigningOperationsTest.RsaPkcs1Sha256Success
2097 *
2098 * Verifies that digested RSA-PKCS1 signature operations succeed.
2099 */
2100TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2101 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2102 .RsaSigningKey(2048, 65537)
2103 .Digest(Digest::SHA_2_256)
2104 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002105 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2106 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002107 string message(1024, 'a');
2108 string signature = SignMessage(message, AuthorizationSetBuilder()
2109 .Digest(Digest::SHA_2_256)
2110 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2111}
2112
2113/*
2114 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2115 *
2116 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2117 */
2118TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2119 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2120 .RsaSigningKey(2048, 65537)
2121 .Digest(Digest::NONE)
2122 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002123 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2124 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002125 string message(53, 'a');
2126 string signature = SignMessage(message, AuthorizationSetBuilder()
2127 .Digest(Digest::NONE)
2128 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2129}
2130
2131/*
2132 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2133 *
2134 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2135 * given a too-long message.
2136 */
2137TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2138 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2139 .RsaSigningKey(2048, 65537)
2140 .Digest(Digest::NONE)
2141 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002142 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2143 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002144 string message(257, 'a');
2145
2146 EXPECT_EQ(ErrorCode::OK,
2147 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2148 .Digest(Digest::NONE)
2149 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2150 string signature;
2151 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2152}
2153
2154/*
2155 * SigningOperationsTest.RsaPssSha512TooSmallKey
2156 *
2157 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2158 * used with a key that is too small for the message.
2159 *
2160 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2161 * keymint specification requires that salt_size == digest_size, so the message will be
2162 * digest_size * 2 +
2163 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2164 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2165 * for a 1024-bit key.
2166 */
2167TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
2168 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2169 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2170 .RsaSigningKey(1024, 65537)
2171 .Digest(Digest::SHA_2_512)
2172 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002173 .Padding(PaddingMode::RSA_PSS)
2174 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002175 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2176 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2177 .Digest(Digest::SHA_2_512)
2178 .Padding(PaddingMode::RSA_PSS)));
2179}
2180
2181/*
2182 * SigningOperationsTest.RsaNoPaddingTooLong
2183 *
2184 * Verifies that raw RSA signature operations fail with the correct error code when
2185 * given a too-long message.
2186 */
2187TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2188 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2189 .RsaSigningKey(2048, 65537)
2190 .Digest(Digest::NONE)
2191 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002192 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2193 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002194 // One byte too long
2195 string message(2048 / 8 + 1, 'a');
2196 ASSERT_EQ(ErrorCode::OK,
2197 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2198 .Digest(Digest::NONE)
2199 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2200 string result;
2201 ErrorCode finish_error_code = Finish(message, &result);
2202 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2203 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2204
2205 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2206 message = string(128 * 1024, 'a');
2207 ASSERT_EQ(ErrorCode::OK,
2208 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2209 .Digest(Digest::NONE)
2210 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2211 finish_error_code = Finish(message, &result);
2212 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2213 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2214}
2215
2216/*
2217 * SigningOperationsTest.RsaAbort
2218 *
2219 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2220 * test, but the behavior should be algorithm and purpose-independent.
2221 */
2222TEST_P(SigningOperationsTest, RsaAbort) {
2223 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2224 .RsaSigningKey(2048, 65537)
2225 .Digest(Digest::NONE)
2226 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002227 .Padding(PaddingMode::NONE)
2228 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002229
2230 ASSERT_EQ(ErrorCode::OK,
2231 Begin(KeyPurpose::SIGN,
2232 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2233 EXPECT_EQ(ErrorCode::OK, Abort());
2234
2235 // Another abort should fail
2236 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2237
2238 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002239 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002240}
2241
2242/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002243 * SigningOperationsTest.RsaNonUniqueParams
2244 *
2245 * Verifies that an operation with multiple padding modes is rejected.
2246 */
2247TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2248 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2249 .RsaSigningKey(2048, 65537)
2250 .Digest(Digest::NONE)
2251 .Digest(Digest::SHA1)
2252 .Authorization(TAG_NO_AUTH_REQUIRED)
2253 .Padding(PaddingMode::NONE)
2254 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2255 .SetDefaultValidity()));
2256
2257 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2258 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2259 .Digest(Digest::NONE)
2260 .Padding(PaddingMode::NONE)
2261 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2262
2263 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2264 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2265 .Digest(Digest::NONE)
2266 .Digest(Digest::SHA1)
2267 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2268
2269 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2270 Begin(KeyPurpose::SIGN,
2271 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2272}
2273
2274/*
Selene Huang31ab4042020-04-29 04:22:39 -07002275 * SigningOperationsTest.RsaUnsupportedPadding
2276 *
2277 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2278 * with a padding mode inappropriate for RSA.
2279 */
2280TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2281 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2282 .RsaSigningKey(2048, 65537)
2283 .Authorization(TAG_NO_AUTH_REQUIRED)
2284 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002285 .Padding(PaddingMode::PKCS7)
2286 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002287 ASSERT_EQ(
2288 ErrorCode::UNSUPPORTED_PADDING_MODE,
2289 Begin(KeyPurpose::SIGN,
2290 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002291 CheckedDeleteKey();
2292
2293 ASSERT_EQ(ErrorCode::OK,
2294 GenerateKey(
2295 AuthorizationSetBuilder()
2296 .RsaSigningKey(2048, 65537)
2297 .Authorization(TAG_NO_AUTH_REQUIRED)
2298 .Digest(Digest::SHA_2_256 /* supported digest */)
2299 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2300 .SetDefaultValidity()));
2301 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2302 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2303 .Digest(Digest::SHA_2_256)
2304 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002305}
2306
2307/*
2308 * SigningOperationsTest.RsaPssNoDigest
2309 *
2310 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2311 */
2312TEST_P(SigningOperationsTest, RsaNoDigest) {
2313 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2314 .RsaSigningKey(2048, 65537)
2315 .Authorization(TAG_NO_AUTH_REQUIRED)
2316 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002317 .Padding(PaddingMode::RSA_PSS)
2318 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002319 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2320 Begin(KeyPurpose::SIGN,
2321 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2322
2323 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2324 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2325}
2326
2327/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002328 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002329 *
2330 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2331 * supported in some cases (as validated in other tests), but a mode must be specified.
2332 */
2333TEST_P(SigningOperationsTest, RsaNoPadding) {
2334 // Padding must be specified
2335 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2336 .RsaKey(2048, 65537)
2337 .Authorization(TAG_NO_AUTH_REQUIRED)
2338 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002339 .Digest(Digest::NONE)
2340 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002341 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2342 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2343}
2344
2345/*
2346 * SigningOperationsTest.RsaShortMessage
2347 *
2348 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2349 */
2350TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2351 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2352 .Authorization(TAG_NO_AUTH_REQUIRED)
2353 .RsaSigningKey(2048, 65537)
2354 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002355 .Padding(PaddingMode::NONE)
2356 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002357
2358 // Barely shorter
2359 string message(2048 / 8 - 1, 'a');
2360 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2361
2362 // Much shorter
2363 message = "a";
2364 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2365}
2366
2367/*
2368 * SigningOperationsTest.RsaSignWithEncryptionKey
2369 *
2370 * Verifies that RSA encryption keys cannot be used to sign.
2371 */
2372TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2373 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2374 .Authorization(TAG_NO_AUTH_REQUIRED)
2375 .RsaEncryptionKey(2048, 65537)
2376 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002377 .Padding(PaddingMode::NONE)
2378 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002379 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2380 Begin(KeyPurpose::SIGN,
2381 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2382}
2383
2384/*
2385 * SigningOperationsTest.RsaSignTooLargeMessage
2386 *
2387 * Verifies that attempting a raw signature of a message which is the same length as the key,
2388 * but numerically larger than the public modulus, fails with the correct error.
2389 */
2390TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2391 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2392 .Authorization(TAG_NO_AUTH_REQUIRED)
2393 .RsaSigningKey(2048, 65537)
2394 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002395 .Padding(PaddingMode::NONE)
2396 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002397
2398 // Largest possible message will always be larger than the public modulus.
2399 string message(2048 / 8, static_cast<char>(0xff));
2400 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2401 .Authorization(TAG_NO_AUTH_REQUIRED)
2402 .Digest(Digest::NONE)
2403 .Padding(PaddingMode::NONE)));
2404 string signature;
2405 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2406}
2407
2408/*
2409 * SigningOperationsTest.EcdsaAllSizesAndHashes
2410 *
2411 * Verifies that ECDSA operations succeed with all possible key sizes and hashes.
2412 */
2413TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
2414 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
2415 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2416 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2417 .Authorization(TAG_NO_AUTH_REQUIRED)
2418 .EcdsaSigningKey(key_size)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002419 .Digest(digest)
2420 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002421 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size
2422 << " and digest " << digest;
2423 if (error != ErrorCode::OK) continue;
2424
2425 string message(1024, 'a');
2426 if (digest == Digest::NONE) message.resize(key_size / 8);
2427 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2428 CheckedDeleteKey();
2429 }
2430 }
2431}
2432
2433/*
2434 * SigningOperationsTest.EcdsaAllCurves
2435 *
2436 * Verifies that ECDSA operations succeed with all possible curves.
2437 */
2438TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2439 for (auto curve : ValidCurves()) {
2440 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2441 .Authorization(TAG_NO_AUTH_REQUIRED)
2442 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002443 .Digest(Digest::SHA_2_256)
2444 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002445 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2446 if (error != ErrorCode::OK) continue;
2447
2448 string message(1024, 'a');
2449 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2450 CheckedDeleteKey();
2451 }
2452}
2453
2454/*
2455 * SigningOperationsTest.EcdsaNoDigestHugeData
2456 *
2457 * Verifies that ECDSA operations support very large messages, even without digesting. This
2458 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2459 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2460 * the framework.
2461 */
2462TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2463 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2464 .Authorization(TAG_NO_AUTH_REQUIRED)
2465 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002466 .Digest(Digest::NONE)
2467 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002468 string message(1 * 1024, 'a');
2469 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2470}
2471
2472/*
2473 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2474 *
2475 * Verifies that using an EC key requires the correct app ID/data.
2476 */
2477TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2478 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2479 .Authorization(TAG_NO_AUTH_REQUIRED)
2480 .EcdsaSigningKey(256)
2481 .Digest(Digest::NONE)
2482 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002483 .Authorization(TAG_APPLICATION_DATA, "appdata")
2484 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002485 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2486 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2487 AbortIfNeeded();
2488 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2489 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2490 .Digest(Digest::NONE)
2491 .Authorization(TAG_APPLICATION_ID, "clientid")));
2492 AbortIfNeeded();
2493 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2494 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2495 .Digest(Digest::NONE)
2496 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2497 AbortIfNeeded();
2498 EXPECT_EQ(ErrorCode::OK,
2499 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2500 .Digest(Digest::NONE)
2501 .Authorization(TAG_APPLICATION_DATA, "appdata")
2502 .Authorization(TAG_APPLICATION_ID, "clientid")));
2503 AbortIfNeeded();
2504}
2505
2506/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002507 * SigningOperationsTest.EcdsaIncompatibleDigest
2508 *
2509 * Verifies that using an EC key requires compatible digest.
2510 */
2511TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2512 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2513 .Authorization(TAG_NO_AUTH_REQUIRED)
2514 .EcdsaSigningKey(256)
2515 .Digest(Digest::NONE)
2516 .Digest(Digest::SHA1)
2517 .SetDefaultValidity()));
2518 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2519 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2520 AbortIfNeeded();
2521}
2522
2523/*
Selene Huang31ab4042020-04-29 04:22:39 -07002524 * SigningOperationsTest.AesEcbSign
2525 *
2526 * Verifies that attempts to use AES keys to sign fail in the correct way.
2527 */
2528TEST_P(SigningOperationsTest, AesEcbSign) {
2529 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2530 .Authorization(TAG_NO_AUTH_REQUIRED)
2531 .SigningKey()
2532 .AesEncryptionKey(128)
2533 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2534
2535 AuthorizationSet out_params;
2536 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2537 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2538 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2539 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2540}
2541
2542/*
2543 * SigningOperationsTest.HmacAllDigests
2544 *
2545 * Verifies that HMAC works with all digests.
2546 */
2547TEST_P(SigningOperationsTest, HmacAllDigests) {
2548 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2549 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2550 .Authorization(TAG_NO_AUTH_REQUIRED)
2551 .HmacKey(128)
2552 .Digest(digest)
2553 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2554 << "Failed to create HMAC key with digest " << digest;
2555 string message = "12345678901234567890123456789012";
2556 string signature = MacMessage(message, digest, 160);
2557 EXPECT_EQ(160U / 8U, signature.size())
2558 << "Failed to sign with HMAC key with digest " << digest;
2559 CheckedDeleteKey();
2560 }
2561}
2562
2563/*
2564 * SigningOperationsTest.HmacSha256TooLargeMacLength
2565 *
2566 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2567 * digest size.
2568 */
2569TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2570 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2571 .Authorization(TAG_NO_AUTH_REQUIRED)
2572 .HmacKey(128)
2573 .Digest(Digest::SHA_2_256)
2574 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2575 AuthorizationSet output_params;
2576 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2577 AuthorizationSetBuilder()
2578 .Digest(Digest::SHA_2_256)
2579 .Authorization(TAG_MAC_LENGTH, 264),
2580 &output_params));
2581}
2582
2583/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002584 * SigningOperationsTest.HmacSha256InvalidMacLength
2585 *
2586 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2587 * not a multiple of 8.
2588 */
2589TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2590 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2591 .Authorization(TAG_NO_AUTH_REQUIRED)
2592 .HmacKey(128)
2593 .Digest(Digest::SHA_2_256)
2594 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2595 AuthorizationSet output_params;
2596 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2597 AuthorizationSetBuilder()
2598 .Digest(Digest::SHA_2_256)
2599 .Authorization(TAG_MAC_LENGTH, 161),
2600 &output_params));
2601}
2602
2603/*
Selene Huang31ab4042020-04-29 04:22:39 -07002604 * SigningOperationsTest.HmacSha256TooSmallMacLength
2605 *
2606 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2607 * specified minimum MAC length.
2608 */
2609TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2610 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2611 .Authorization(TAG_NO_AUTH_REQUIRED)
2612 .HmacKey(128)
2613 .Digest(Digest::SHA_2_256)
2614 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2615 AuthorizationSet output_params;
2616 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2617 AuthorizationSetBuilder()
2618 .Digest(Digest::SHA_2_256)
2619 .Authorization(TAG_MAC_LENGTH, 120),
2620 &output_params));
2621}
2622
2623/*
2624 * SigningOperationsTest.HmacRfc4231TestCase3
2625 *
2626 * Validates against the test vectors from RFC 4231 test case 3.
2627 */
2628TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2629 string key(20, 0xaa);
2630 string message(50, 0xdd);
2631 uint8_t sha_224_expected[] = {
2632 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2633 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2634 };
2635 uint8_t sha_256_expected[] = {
2636 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2637 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2638 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2639 };
2640 uint8_t sha_384_expected[] = {
2641 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2642 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2643 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2644 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2645 };
2646 uint8_t sha_512_expected[] = {
2647 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2648 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2649 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2650 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2651 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2652 };
2653
2654 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2655 if (SecLevel() != SecurityLevel::STRONGBOX) {
2656 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2657 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2658 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2659 }
2660}
2661
2662/*
2663 * SigningOperationsTest.HmacRfc4231TestCase5
2664 *
2665 * Validates against the test vectors from RFC 4231 test case 5.
2666 */
2667TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2668 string key(20, 0x0c);
2669 string message = "Test With Truncation";
2670
2671 uint8_t sha_224_expected[] = {
2672 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2673 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2674 };
2675 uint8_t sha_256_expected[] = {
2676 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2677 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2678 };
2679 uint8_t sha_384_expected[] = {
2680 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2681 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2682 };
2683 uint8_t sha_512_expected[] = {
2684 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2685 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2686 };
2687
2688 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2689 if (SecLevel() != SecurityLevel::STRONGBOX) {
2690 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2691 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2692 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2693 }
2694}
2695
2696INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2697
2698typedef KeyMintAidlTestBase VerificationOperationsTest;
2699
2700/*
2701 * VerificationOperationsTest.RsaSuccess
2702 *
2703 * Verifies that a simple RSA signature/verification sequence succeeds.
2704 */
2705TEST_P(VerificationOperationsTest, RsaSuccess) {
2706 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2707 .Authorization(TAG_NO_AUTH_REQUIRED)
2708 .RsaSigningKey(2048, 65537)
2709 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002710 .Padding(PaddingMode::NONE)
2711 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002712 string message = "12345678901234567890123456789012";
2713 string signature = SignMessage(
2714 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2715 VerifyMessage(message, signature,
2716 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2717}
2718
2719/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002720 * VerificationOperationsTest.RsaAllPaddingsAndDigests
Selene Huang31ab4042020-04-29 04:22:39 -07002721 *
2722 * Verifies RSA signature/verification for all padding modes and digests.
2723 */
2724TEST_P(VerificationOperationsTest, RsaAllPaddingsAndDigests) {
2725 auto authorizations = AuthorizationSetBuilder()
2726 .Authorization(TAG_NO_AUTH_REQUIRED)
2727 .RsaSigningKey(2048, 65537)
2728 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2729 .Padding(PaddingMode::NONE)
2730 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002731 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2732 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002733
2734 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2735
2736 string message(128, 'a');
2737 string corrupt_message(message);
2738 ++corrupt_message[corrupt_message.size() / 2];
2739
2740 for (auto padding :
2741 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2742 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2743 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2744 // Digesting only makes sense with padding.
2745 continue;
2746 }
2747
2748 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2749 // PSS requires digesting.
2750 continue;
2751 }
2752
2753 string signature =
2754 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2755 VerifyMessage(message, signature,
2756 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2757
2758 /* TODO(seleneh) add exportkey tests back later when we have decided on
2759 * the new api.
2760 if (digest != Digest::NONE) {
2761 // Verify with OpenSSL.
2762 vector<uint8_t> pubkey;
2763 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey));
2764
2765 const uint8_t* p = pubkey.data();
2766 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
2767 ASSERT_TRUE(pkey.get());
2768
2769 EVP_MD_CTX digest_ctx;
2770 EVP_MD_CTX_init(&digest_ctx);
2771 EVP_PKEY_CTX* pkey_ctx;
2772 const EVP_MD* md = openssl_digest(digest);
2773 ASSERT_NE(md, nullptr);
2774 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
2775 nullptr, pkey.get()));
2776
2777 switch (padding) {
2778 case PaddingMode::RSA_PSS:
2779 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx,
2780 RSA_PKCS1_PSS_PADDING), 0); EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx,
2781 EVP_MD_size(md)), 0); break; case PaddingMode::RSA_PKCS1_1_5_SIGN:
2782 // PKCS1 is the default; don't need to set anything.
2783 break;
2784 default:
2785 FAIL();
2786 break;
2787 }
2788
2789 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
2790 message.size())); EXPECT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
2791 reinterpret_cast<const
2792 uint8_t*>(signature.data()), signature.size())); EVP_MD_CTX_cleanup(&digest_ctx);
2793 }
2794 */
2795
2796 // Corrupt signature shouldn't verify.
2797 string corrupt_signature(signature);
2798 ++corrupt_signature[corrupt_signature.size() / 2];
2799
2800 EXPECT_EQ(ErrorCode::OK,
2801 Begin(KeyPurpose::VERIFY,
2802 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2803 string result;
2804 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result));
2805
2806 // Corrupt message shouldn't verify
2807 EXPECT_EQ(ErrorCode::OK,
2808 Begin(KeyPurpose::VERIFY,
2809 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2810 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result));
2811 }
2812 }
2813}
2814
2815/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002816 * VerificationOperationsTest.RsaAllDigestsAndCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002817 *
2818 * Verifies ECDSA signature/verification for all digests and curves.
2819 */
2820TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndCurves) {
2821 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2822
2823 string message = "1234567890";
2824 string corrupt_message = "2234567890";
2825 for (auto curve : ValidCurves()) {
2826 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2827 .Authorization(TAG_NO_AUTH_REQUIRED)
2828 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002829 .Digest(digests)
2830 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002831 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2832 if (error != ErrorCode::OK) {
2833 continue;
2834 }
2835
2836 for (auto digest : digests) {
2837 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2838 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2839
2840 /* TODO(seleneh) add exportkey tests back later when we have decided on
2841 * the new api.
2842
2843 // Verify with OpenSSL
2844 if (digest != Digest::NONE) {
2845 vector<uint8_t> pubkey;
2846 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey))
2847 << curve << ' ' << digest;
2848
2849 const uint8_t* p = pubkey.data();
2850 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
2851 ASSERT_TRUE(pkey.get());
2852
2853 EVP_MD_CTX digest_ctx;
2854 EVP_MD_CTX_init(&digest_ctx);
2855 EVP_PKEY_CTX* pkey_ctx;
2856 const EVP_MD* md = openssl_digest(digest);
2857
2858 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
2859 nullptr, pkey.get()))
2860 << curve << ' ' << digest;
2861
2862 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
2863 message.size()))
2864 << curve << ' ' << digest;
2865
2866 EXPECT_EQ(1,
2867 EVP_DigestVerifyFinal(&digest_ctx,
2868 reinterpret_cast<const
2869 uint8_t*>(signature.data()), signature.size()))
2870 << curve << ' ' << digest;
2871
2872 EVP_MD_CTX_cleanup(&digest_ctx);
2873 }
2874 */
2875 // Corrupt signature shouldn't verify.
2876 string corrupt_signature(signature);
2877 ++corrupt_signature[corrupt_signature.size() / 2];
2878
2879 EXPECT_EQ(ErrorCode::OK,
2880 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2881 << curve << ' ' << digest;
2882
2883 string result;
2884 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result))
2885 << curve << ' ' << digest;
2886
2887 // Corrupt message shouldn't verify
2888 EXPECT_EQ(ErrorCode::OK,
2889 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2890 << curve << ' ' << digest;
2891
2892 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result))
2893 << curve << ' ' << digest;
2894 }
2895
2896 auto rc = DeleteKey();
2897 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2898 }
2899}
2900
2901/*
2902 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2903 *
2904 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2905 */
2906TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2907 string key_material = "HelloThisIsAKey";
2908
2909 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002910 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002911 EXPECT_EQ(ErrorCode::OK,
2912 ImportKey(AuthorizationSetBuilder()
2913 .Authorization(TAG_NO_AUTH_REQUIRED)
2914 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2915 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2916 .Digest(Digest::SHA_2_256)
2917 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2918 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2919 EXPECT_EQ(ErrorCode::OK,
2920 ImportKey(AuthorizationSetBuilder()
2921 .Authorization(TAG_NO_AUTH_REQUIRED)
2922 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2923 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2924 .Digest(Digest::SHA_2_256)
2925 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2926 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2927
2928 string message = "This is a message.";
2929 string signature = SignMessage(
2930 signing_key, message,
2931 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2932
2933 // Signing key should not work.
2934 AuthorizationSet out_params;
2935 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2936 Begin(KeyPurpose::VERIFY, signing_key,
2937 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2938
2939 // Verification key should work.
2940 VerifyMessage(verification_key, message, signature,
2941 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2942
2943 CheckedDeleteKey(&signing_key);
2944 CheckedDeleteKey(&verification_key);
2945}
2946
2947INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2948
2949typedef KeyMintAidlTestBase ExportKeyTest;
2950
2951/*
2952 * ExportKeyTest.RsaUnsupportedKeyFormat
2953 *
2954 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2955 */
2956// TODO(seleneh) add ExportKey to GenerateKey
2957// check result
2958
2959class ImportKeyTest : public KeyMintAidlTestBase {
2960 public:
2961 template <TagType tag_type, Tag tag, typename ValueT>
2962 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2963 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002964 for (auto& entry : key_characteristics_) {
2965 if (entry.securityLevel == SecLevel()) {
2966 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2967 << "Tag " << tag << " with value " << expected
2968 << " not found at security level" << entry.securityLevel;
2969 } else {
2970 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
2971 << "Tag " << tag << " found at security level " << entry.securityLevel;
2972 }
Selene Huang31ab4042020-04-29 04:22:39 -07002973 }
2974 }
2975
2976 void CheckOrigin() {
2977 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07002978 // Origin isn't a crypto param, but it always lives with them.
2979 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07002980 }
2981};
2982
2983/*
2984 * ImportKeyTest.RsaSuccess
2985 *
2986 * Verifies that importing and using an RSA key pair works correctly.
2987 */
2988TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07002989 uint32_t key_size;
2990 string key;
2991
2992 if (SecLevel() == SecurityLevel::STRONGBOX) {
2993 key_size = 2048;
2994 key = rsa_2048_key;
2995 } else {
2996 key_size = 1024;
2997 key = rsa_key;
2998 }
2999
Selene Huang31ab4042020-04-29 04:22:39 -07003000 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3001 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003002 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003003 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003004 .Padding(PaddingMode::RSA_PSS)
3005 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003006 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003007
3008 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003009 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003010 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3011 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3012 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3013 CheckOrigin();
3014
3015 string message(1024 / 8, 'a');
3016 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3017 string signature = SignMessage(message, params);
3018 VerifyMessage(message, signature, params);
3019}
3020
3021/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003022 * ImportKeyTest.RsaSuccessWithoutParams
3023 *
3024 * Verifies that importing and using an RSA key pair without specifying parameters
3025 * works correctly.
3026 */
3027TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3028 uint32_t key_size;
3029 string key;
3030
3031 if (SecLevel() == SecurityLevel::STRONGBOX) {
3032 key_size = 2048;
3033 key = rsa_2048_key;
3034 } else {
3035 key_size = 1024;
3036 key = rsa_key;
3037 }
3038
3039 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3040 .Authorization(TAG_NO_AUTH_REQUIRED)
3041 .SigningKey()
3042 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3043 .Digest(Digest::SHA_2_256)
3044 .Padding(PaddingMode::RSA_PSS)
3045 .SetDefaultValidity(),
3046 KeyFormat::PKCS8, key));
3047
3048 // Key size and public exponent are determined from the imported key material.
3049 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3050 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3051
3052 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3053 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3054 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3055 CheckOrigin();
3056
3057 string message(1024 / 8, 'a');
3058 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3059 string signature = SignMessage(message, params);
3060 VerifyMessage(message, signature, params);
3061}
3062
3063/*
Selene Huang31ab4042020-04-29 04:22:39 -07003064 * ImportKeyTest.RsaKeySizeMismatch
3065 *
3066 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3067 * correct way.
3068 */
3069TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3070 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3071 ImportKey(AuthorizationSetBuilder()
3072 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3073 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003074 .Padding(PaddingMode::NONE)
3075 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003076 KeyFormat::PKCS8, rsa_key));
3077}
3078
3079/*
3080 * ImportKeyTest.RsaPublicExponentMismatch
3081 *
3082 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3083 * fails in the correct way.
3084 */
3085TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3086 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3087 ImportKey(AuthorizationSetBuilder()
3088 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3089 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003090 .Padding(PaddingMode::NONE)
3091 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003092 KeyFormat::PKCS8, rsa_key));
3093}
3094
3095/*
3096 * ImportKeyTest.EcdsaSuccess
3097 *
3098 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3099 */
3100TEST_P(ImportKeyTest, EcdsaSuccess) {
3101 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3102 .Authorization(TAG_NO_AUTH_REQUIRED)
3103 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003104 .Digest(Digest::SHA_2_256)
3105 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003106 KeyFormat::PKCS8, ec_256_key));
3107
3108 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3109 CheckCryptoParam(TAG_KEY_SIZE, 256U);
3110 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3111 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3112
3113 CheckOrigin();
3114
3115 string message(32, 'a');
3116 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3117 string signature = SignMessage(message, params);
3118 VerifyMessage(message, signature, params);
3119}
3120
3121/*
3122 * ImportKeyTest.EcdsaP256RFC5915Success
3123 *
3124 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3125 * correctly.
3126 */
3127TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3128 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3129 .Authorization(TAG_NO_AUTH_REQUIRED)
3130 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003131 .Digest(Digest::SHA_2_256)
3132 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003133 KeyFormat::PKCS8, ec_256_key_rfc5915));
3134
3135 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3136 CheckCryptoParam(TAG_KEY_SIZE, 256U);
3137 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3138 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3139
3140 CheckOrigin();
3141
3142 string message(32, 'a');
3143 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3144 string signature = SignMessage(message, params);
3145 VerifyMessage(message, signature, params);
3146}
3147
3148/*
3149 * ImportKeyTest.EcdsaP256SEC1Success
3150 *
3151 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3152 */
3153TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3154 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3155 .Authorization(TAG_NO_AUTH_REQUIRED)
3156 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003157 .Digest(Digest::SHA_2_256)
3158 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003159 KeyFormat::PKCS8, ec_256_key_sec1));
3160
3161 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3162 CheckCryptoParam(TAG_KEY_SIZE, 256U);
3163 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3164 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3165
3166 CheckOrigin();
3167
3168 string message(32, 'a');
3169 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3170 string signature = SignMessage(message, params);
3171 VerifyMessage(message, signature, params);
3172}
3173
3174/*
3175 * ImportKeyTest.Ecdsa521Success
3176 *
3177 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3178 */
3179TEST_P(ImportKeyTest, Ecdsa521Success) {
3180 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3181 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3182 .Authorization(TAG_NO_AUTH_REQUIRED)
3183 .EcdsaSigningKey(521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003184 .Digest(Digest::SHA_2_256)
3185 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003186 KeyFormat::PKCS8, ec_521_key));
3187
3188 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3189 CheckCryptoParam(TAG_KEY_SIZE, 521U);
3190 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3191 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3192 CheckOrigin();
3193
3194 string message(32, 'a');
3195 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3196 string signature = SignMessage(message, params);
3197 VerifyMessage(message, signature, params);
3198}
3199
3200/*
3201 * ImportKeyTest.EcdsaSizeMismatch
3202 *
3203 * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the
3204 * correct way.
3205 */
3206TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
3207 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3208 ImportKey(AuthorizationSetBuilder()
3209 .EcdsaSigningKey(224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003210 .Digest(Digest::NONE)
3211 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003212 KeyFormat::PKCS8, ec_256_key));
3213}
3214
3215/*
3216 * ImportKeyTest.EcdsaCurveMismatch
3217 *
3218 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3219 * the correct way.
3220 */
3221TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3222 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3223 ImportKey(AuthorizationSetBuilder()
3224 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003225 .Digest(Digest::NONE)
3226 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003227 KeyFormat::PKCS8, ec_256_key));
3228}
3229
3230/*
3231 * ImportKeyTest.AesSuccess
3232 *
3233 * Verifies that importing and using an AES key works.
3234 */
3235TEST_P(ImportKeyTest, AesSuccess) {
3236 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3237 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3238 .Authorization(TAG_NO_AUTH_REQUIRED)
3239 .AesEncryptionKey(key.size() * 8)
3240 .EcbMode()
3241 .Padding(PaddingMode::PKCS7),
3242 KeyFormat::RAW, key));
3243
3244 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3245 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3246 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3247 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3248 CheckOrigin();
3249
3250 string message = "Hello World!";
3251 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3252 string ciphertext = EncryptMessage(message, params);
3253 string plaintext = DecryptMessage(ciphertext, params);
3254 EXPECT_EQ(message, plaintext);
3255}
3256
3257/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003258 * ImportKeyTest.AesFailure
3259 *
3260 * Verifies that importing an invalid AES key fails.
3261 */
3262TEST_P(ImportKeyTest, AesFailure) {
3263 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3264 uint32_t bitlen = key.size() * 8;
3265 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
Tommy Chiu3950b452021-05-03 22:01:46 +08003266 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003267 .Authorization(TAG_NO_AUTH_REQUIRED)
3268 .AesEncryptionKey(key_size)
3269 .EcbMode()
3270 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003271 KeyFormat::RAW, key);
3272 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
3273 result == ErrorCode::UNSUPPORTED_KEY_SIZE);
David Drysdale7de9feb2021-03-05 14:56:19 +00003274 }
3275}
3276
3277/*
3278 * ImportKeyTest.TripleDesSuccess
3279 *
3280 * Verifies that importing and using a 3DES key works.
3281 */
3282TEST_P(ImportKeyTest, TripleDesSuccess) {
3283 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3284 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3285 .Authorization(TAG_NO_AUTH_REQUIRED)
3286 .TripleDesEncryptionKey(168)
3287 .EcbMode()
3288 .Padding(PaddingMode::PKCS7),
3289 KeyFormat::RAW, key));
3290
3291 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3292 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3293 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3294 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3295 CheckOrigin();
3296
3297 string message = "Hello World!";
3298 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3299 string ciphertext = EncryptMessage(message, params);
3300 string plaintext = DecryptMessage(ciphertext, params);
3301 EXPECT_EQ(message, plaintext);
3302}
3303
3304/*
3305 * ImportKeyTest.TripleDesFailure
3306 *
3307 * Verifies that importing an invalid 3DES key fails.
3308 */
3309TEST_P(ImportKeyTest, TripleDesFailure) {
3310 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3311 uint32_t bitlen = key.size() * 8;
3312 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
Tommy Chiu3950b452021-05-03 22:01:46 +08003313 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003314 .Authorization(TAG_NO_AUTH_REQUIRED)
3315 .TripleDesEncryptionKey(key_size)
3316 .EcbMode()
3317 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003318 KeyFormat::RAW, key);
3319 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
3320 result == ErrorCode::UNSUPPORTED_KEY_SIZE);
David Drysdale7de9feb2021-03-05 14:56:19 +00003321 }
3322}
3323
3324/*
3325 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003326 *
3327 * Verifies that importing and using an HMAC key works.
3328 */
3329TEST_P(ImportKeyTest, HmacKeySuccess) {
3330 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3331 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3332 .Authorization(TAG_NO_AUTH_REQUIRED)
3333 .HmacKey(key.size() * 8)
3334 .Digest(Digest::SHA_2_256)
3335 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3336 KeyFormat::RAW, key));
3337
3338 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3339 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3340 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3341 CheckOrigin();
3342
3343 string message = "Hello World!";
3344 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3345 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3346}
3347
3348INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3349
3350auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003351 // IKeyMintDevice.aidl
3352 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3353 "020100" // INTEGER length 1 value 0x00 (version)
3354 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3355 "934bf94e2aa28a3f83c9f79297250262"
3356 "fbe3276b5a1c91159bbfa3ef8957aac8"
3357 "4b59b30b455a79c2973480823d8b3863"
3358 "c3deef4a8e243590268d80e18751a0e1"
3359 "30f67ce6a1ace9f79b95e097474febc9"
3360 "81195b1d13a69086c0863f66a7b7fdb4"
3361 "8792227b1ac5e2489febdf087ab54864"
3362 "83033a6f001ca5d1ec1e27f5c30f4cec"
3363 "2642074a39ae68aee552e196627a8e3d"
3364 "867e67a8c01b11e75f13cca0a97ab668"
3365 "b50cda07a8ecb7cd8e3dd7009c963653"
3366 "4f6f239cffe1fc8daa466f78b676c711"
3367 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3368 "99b801597d5220e307eaa5bee507fb94"
3369 "d1fa69f9e519b2de315bac92c36f2ea1"
3370 "fa1df4478c0ddedeae8c70e0233cd098"
3371 "040c" // OCTET STRING length 0x0c (initializationVector)
3372 "d796b02c370f1fa4cc0124f1"
3373 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3374 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3375 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3376 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3377 "3106" // SET length 0x06
3378 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3379 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3380 // } end SET
3381 // } end [1]
3382 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3383 "020120" // INTEGER length 1 value 0x20 (AES)
3384 // } end [2]
3385 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3386 "02020100" // INTEGER length 2 value 0x100
3387 // } end [3]
3388 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3389 "3103" // SET length 0x03 {
3390 "020101" // INTEGER length 1 value 0x01 (ECB)
3391 // } end SET
3392 // } end [4]
3393 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3394 "3103" // SET length 0x03 {
3395 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3396 // } end SET
3397 // } end [5]
3398 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3399 // (noAuthRequired)
3400 "0500" // NULL
3401 // } end [503]
3402 // } end SEQUENCE (AuthorizationList)
3403 // } end SEQUENCE (KeyDescription)
3404 "0420" // OCTET STRING length 0x20 (encryptedKey)
3405 "ccd540855f833a5e1480bfd2d36faf3a"
3406 "eee15df5beabe2691bc82dde2a7aa910"
3407 "0410" // OCTET STRING length 0x10 (tag)
3408 "64c9f689c60ff6223ab6e6999e0eb6e5"
3409 // } SEQUENCE (SecureKeyWrapper)
3410);
Selene Huang31ab4042020-04-29 04:22:39 -07003411
3412auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003413 // IKeyMintDevice.aidl
3414 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3415 "020100" // INTEGER length 1 value 0x00 (version)
3416 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3417 "aad93ed5924f283b4bb5526fbe7a1412"
3418 "f9d9749ec30db9062b29e574a8546f33"
3419 "c88732452f5b8e6a391ee76c39ed1712"
3420 "c61d8df6213dec1cffbc17a8c6d04c7b"
3421 "30893d8daa9b2015213e219468215532"
3422 "07f8f9931c4caba23ed3bee28b36947e"
3423 "47f10e0a5c3dc51c988a628daad3e5e1"
3424 "f4005e79c2d5a96c284b4b8d7e4948f3"
3425 "31e5b85dd5a236f85579f3ea1d1b8484"
3426 "87470bdb0ab4f81a12bee42c99fe0df4"
3427 "bee3759453e69ad1d68a809ce06b949f"
3428 "7694a990429b2fe81e066ff43e56a216"
3429 "02db70757922a4bcc23ab89f1e35da77"
3430 "586775f423e519c2ea394caf48a28d0c"
3431 "8020f1dcf6b3a68ec246f615ae96dae9"
3432 "a079b1f6eb959033c1af5c125fd94168"
3433 "040c" // OCTET STRING length 0x0c (initializationVector)
3434 "6d9721d08589581ab49204a3"
3435 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3436 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3437 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3438 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3439 "3106" // SET length 0x06
3440 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3441 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3442 // } end SET
3443 // } end [1]
3444 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3445 "020120" // INTEGER length 1 value 0x20 (AES)
3446 // } end [2]
3447 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3448 "02020100" // INTEGER length 2 value 0x100
3449 // } end [3]
3450 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3451 "3103" // SET length 0x03 {
3452 "020101" // INTEGER length 1 value 0x01 (ECB)
3453 // } end SET
3454 // } end [4]
3455 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3456 "3103" // SET length 0x03 {
3457 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3458 // } end SET
3459 // } end [5]
3460 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3461 // (noAuthRequired)
3462 "0500" // NULL
3463 // } end [503]
3464 // } end SEQUENCE (AuthorizationList)
3465 // } end SEQUENCE (KeyDescription)
3466 "0420" // OCTET STRING length 0x20 (encryptedKey)
3467 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3468 "c20d1f99a9a024a76f35c8e2cab9b68d"
3469 "0410" // OCTET STRING length 0x10 (tag)
3470 "2560c70109ae67c030f00b98b512a670"
3471 // } SEQUENCE (SecureKeyWrapper)
3472);
Selene Huang31ab4042020-04-29 04:22:39 -07003473
3474auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003475 // RFC 5208 s5
3476 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3477 "020100" // INTEGER length 1 value 0x00 (version)
3478 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3479 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3480 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3481 "0500" // NULL (parameters)
3482 // } SEQUENCE (AlgorithmIdentifier)
3483 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3484 // RFC 8017 A.1.2
3485 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3486 "020100" // INTEGER length 1 value 0x00 (version)
3487 "02820101" // INTEGER length 0x0101 (modulus) value...
3488 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3489 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3490 "7b06e673a837313d56b1c725150a3fef" // 0x30
3491 "86acbddc41bb759c2854eae32d35841e" // 0x40
3492 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3493 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3494 "312d7bd5921ffaea1347c157406fef71" // 0x70
3495 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3496 "f4645c11f5c1374c3886427411c44979" // 0x90
3497 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3498 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3499 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3500 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3501 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3502 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3503 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3504 "55" // 0x101
3505 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3506 "02820100" // INTEGER length 0x100 (privateExponent) value...
3507 "431447b6251908112b1ee76f99f3711a" // 0x10
3508 "52b6630960046c2de70de188d833f8b8" // 0x20
3509 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3510 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3511 "e710b630a03adc683b5d2c43080e52be" // 0x50
3512 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3513 "822bccff087d63c940ba8a45f670feb2" // 0x70
3514 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3515 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3516 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3517 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3518 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3519 "52659d5a5ba05b663737a8696281865b" // 0xd0
3520 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3521 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3522 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3523 "028181" // INTEGER length 0x81 (prime1) value...
3524 "00de392e18d682c829266cc3454e1d61" // 0x10
3525 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3526 "ff841be5bac82a164c5970007047b8c5" // 0x30
3527 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3528 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3529 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3530 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3531 "9e91346130748a6e3c124f9149d71c74" // 0x80
3532 "35"
3533 "028181" // INTEGER length 0x81 (prime2) value...
3534 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3535 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3536 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3537 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3538 "9ed39a2d934c880440aed8832f984316" // 0x50
3539 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3540 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3541 "b880677c068e1be936e81288815252a8" // 0x80
3542 "a1"
3543 "028180" // INTEGER length 0x80 (exponent1) value...
3544 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3545 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3546 "5a063212a4f105a3764743e53281988a" // 0x30
3547 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3548 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3549 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3550 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3551 "4719d6e2b9439823719cd08bcd031781" // 0x80
3552 "028181" // INTEGER length 0x81 (exponent2) value...
3553 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3554 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3555 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3556 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3557 "1254186af30b22c10582a8a43e34fe94" // 0x50
3558 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3559 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3560 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3561 "61"
3562 "028181" // INTEGER length 0x81 (coefficient) value...
3563 "00c931617c77829dfb1270502be9195c" // 0x10
3564 "8f2830885f57dba869536811e6864236" // 0x20
3565 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3566 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3567 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3568 "959356210723287b0affcc9f727044d4" // 0x60
3569 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3570 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3571 "22"
3572 // } SEQUENCE
3573 // } SEQUENCE ()
3574);
Selene Huang31ab4042020-04-29 04:22:39 -07003575
3576string zero_masking_key =
3577 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3578string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3579
3580class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3581
3582TEST_P(ImportWrappedKeyTest, Success) {
3583 auto wrapping_key_desc = AuthorizationSetBuilder()
3584 .RsaEncryptionKey(2048, 65537)
3585 .Digest(Digest::SHA_2_256)
3586 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003587 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3588 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003589
3590 ASSERT_EQ(ErrorCode::OK,
3591 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3592 AuthorizationSetBuilder()
3593 .Digest(Digest::SHA_2_256)
3594 .Padding(PaddingMode::RSA_OAEP)));
3595
3596 string message = "Hello World!";
3597 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3598 string ciphertext = EncryptMessage(message, params);
3599 string plaintext = DecryptMessage(ciphertext, params);
3600 EXPECT_EQ(message, plaintext);
3601}
3602
David Drysdaled2cc8c22021-04-15 13:29:45 +01003603/*
3604 * ImportWrappedKeyTest.SuccessSidsIgnored
3605 *
3606 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3607 * include Tag:USER_SECURE_ID.
3608 */
3609TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3610 auto wrapping_key_desc = AuthorizationSetBuilder()
3611 .RsaEncryptionKey(2048, 65537)
3612 .Digest(Digest::SHA_2_256)
3613 .Padding(PaddingMode::RSA_OAEP)
3614 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3615 .SetDefaultValidity();
3616
3617 int64_t password_sid = 42;
3618 int64_t biometric_sid = 24;
3619 ASSERT_EQ(ErrorCode::OK,
3620 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3621 AuthorizationSetBuilder()
3622 .Digest(Digest::SHA_2_256)
3623 .Padding(PaddingMode::RSA_OAEP),
3624 password_sid, biometric_sid));
3625
3626 string message = "Hello World!";
3627 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3628 string ciphertext = EncryptMessage(message, params);
3629 string plaintext = DecryptMessage(ciphertext, params);
3630 EXPECT_EQ(message, plaintext);
3631}
3632
Selene Huang31ab4042020-04-29 04:22:39 -07003633TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3634 auto wrapping_key_desc = AuthorizationSetBuilder()
3635 .RsaEncryptionKey(2048, 65537)
3636 .Digest(Digest::SHA_2_256)
3637 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003638 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3639 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003640
3641 ASSERT_EQ(ErrorCode::OK,
3642 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3643 AuthorizationSetBuilder()
3644 .Digest(Digest::SHA_2_256)
3645 .Padding(PaddingMode::RSA_OAEP)));
3646}
3647
3648TEST_P(ImportWrappedKeyTest, WrongMask) {
3649 auto wrapping_key_desc = AuthorizationSetBuilder()
3650 .RsaEncryptionKey(2048, 65537)
3651 .Digest(Digest::SHA_2_256)
3652 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003653 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3654 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003655
3656 ASSERT_EQ(
3657 ErrorCode::VERIFICATION_FAILED,
3658 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3659 AuthorizationSetBuilder()
3660 .Digest(Digest::SHA_2_256)
3661 .Padding(PaddingMode::RSA_OAEP)));
3662}
3663
3664TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3665 auto wrapping_key_desc = AuthorizationSetBuilder()
3666 .RsaEncryptionKey(2048, 65537)
3667 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003668 .Padding(PaddingMode::RSA_OAEP)
3669 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003670
3671 ASSERT_EQ(
3672 ErrorCode::INCOMPATIBLE_PURPOSE,
3673 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3674 AuthorizationSetBuilder()
3675 .Digest(Digest::SHA_2_256)
3676 .Padding(PaddingMode::RSA_OAEP)));
3677}
3678
David Drysdaled2cc8c22021-04-15 13:29:45 +01003679TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3680 auto wrapping_key_desc = AuthorizationSetBuilder()
3681 .RsaEncryptionKey(2048, 65537)
3682 .Digest(Digest::SHA_2_256)
3683 .Padding(PaddingMode::RSA_PSS)
3684 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3685 .SetDefaultValidity();
3686
3687 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3688 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3689 AuthorizationSetBuilder()
3690 .Digest(Digest::SHA_2_256)
3691 .Padding(PaddingMode::RSA_OAEP)));
3692}
3693
3694TEST_P(ImportWrappedKeyTest, WrongDigest) {
3695 auto wrapping_key_desc = AuthorizationSetBuilder()
3696 .RsaEncryptionKey(2048, 65537)
3697 .Digest(Digest::SHA_2_512)
3698 .Padding(PaddingMode::RSA_OAEP)
3699 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3700 .SetDefaultValidity();
3701
3702 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3703 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3704 AuthorizationSetBuilder()
3705 .Digest(Digest::SHA_2_256)
3706 .Padding(PaddingMode::RSA_OAEP)));
3707}
3708
Selene Huang31ab4042020-04-29 04:22:39 -07003709INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3710
3711typedef KeyMintAidlTestBase EncryptionOperationsTest;
3712
3713/*
3714 * EncryptionOperationsTest.RsaNoPaddingSuccess
3715 *
3716 * Verifies that raw RSA encryption works.
3717 */
3718TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003719 for (uint64_t exponent : {3, 65537}) {
3720 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3721 .Authorization(TAG_NO_AUTH_REQUIRED)
3722 .RsaEncryptionKey(2048, exponent)
3723 .Padding(PaddingMode::NONE)
3724 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003725
David Drysdaled2cc8c22021-04-15 13:29:45 +01003726 string message = string(2048 / 8, 'a');
3727 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3728 string ciphertext1 = EncryptMessage(message, params);
3729 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003730
David Drysdaled2cc8c22021-04-15 13:29:45 +01003731 string ciphertext2 = EncryptMessage(message, params);
3732 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003733
David Drysdaled2cc8c22021-04-15 13:29:45 +01003734 // Unpadded RSA is deterministic
3735 EXPECT_EQ(ciphertext1, ciphertext2);
3736
3737 CheckedDeleteKey();
3738 }
Selene Huang31ab4042020-04-29 04:22:39 -07003739}
3740
3741/*
3742 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3743 *
3744 * Verifies that raw RSA encryption of short messages works.
3745 */
3746TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3747 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3748 .Authorization(TAG_NO_AUTH_REQUIRED)
3749 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003750 .Padding(PaddingMode::NONE)
3751 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003752
3753 string message = "1";
3754 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3755
3756 string ciphertext = EncryptMessage(message, params);
3757 EXPECT_EQ(2048U / 8, ciphertext.size());
3758
3759 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3760 string plaintext = DecryptMessage(ciphertext, params);
3761
3762 EXPECT_EQ(expected_plaintext, plaintext);
3763
3764 // Degenerate case, encrypting a numeric 1 yields 0x00..01 as the ciphertext.
3765 message = static_cast<char>(1);
3766 ciphertext = EncryptMessage(message, params);
3767 EXPECT_EQ(2048U / 8, ciphertext.size());
3768 EXPECT_EQ(ciphertext, string(2048U / 8 - 1, 0) + message);
3769}
3770
3771/*
3772 * EncryptionOperationsTest.RsaNoPaddingTooLong
3773 *
3774 * Verifies that raw RSA encryption of too-long messages fails in the expected way.
3775 */
3776TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
3777 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3778 .Authorization(TAG_NO_AUTH_REQUIRED)
3779 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003780 .Padding(PaddingMode::NONE)
3781 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003782
3783 string message(2048 / 8 + 1, 'a');
3784
3785 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3786 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3787
3788 string result;
3789 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
3790}
3791
3792/*
3793 * EncryptionOperationsTest.RsaNoPaddingTooLarge
3794 *
3795 * Verifies that raw RSA encryption of too-large (numerically) messages fails in the expected
3796 * way.
3797 */
3798// TODO(seleneh) add RsaNoPaddingTooLarge test back after decided and implemented new
3799// version of ExportKey inside generateKey
3800
3801/*
3802 * EncryptionOperationsTest.RsaOaepSuccess
3803 *
3804 * Verifies that RSA-OAEP encryption operations work, with all digests.
3805 */
3806TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3807 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3808
3809 size_t key_size = 2048; // Need largish key for SHA-512 test.
3810 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3811 .Authorization(TAG_NO_AUTH_REQUIRED)
3812 .RsaEncryptionKey(key_size, 65537)
3813 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003814 .Digest(digests)
3815 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003816
3817 string message = "Hello";
3818
3819 for (auto digest : digests) {
3820 auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP);
3821 string ciphertext1 = EncryptMessage(message, params);
3822 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3823 EXPECT_EQ(key_size / 8, ciphertext1.size());
3824
3825 string ciphertext2 = EncryptMessage(message, params);
3826 EXPECT_EQ(key_size / 8, ciphertext2.size());
3827
3828 // OAEP randomizes padding so every result should be different (with astronomically high
3829 // probability).
3830 EXPECT_NE(ciphertext1, ciphertext2);
3831
3832 string plaintext1 = DecryptMessage(ciphertext1, params);
3833 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3834 string plaintext2 = DecryptMessage(ciphertext2, params);
3835 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3836
3837 // Decrypting corrupted ciphertext should fail.
3838 size_t offset_to_corrupt = random() % ciphertext1.size();
3839 char corrupt_byte;
3840 do {
3841 corrupt_byte = static_cast<char>(random() % 256);
3842 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3843 ciphertext1[offset_to_corrupt] = corrupt_byte;
3844
3845 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3846 string result;
3847 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3848 EXPECT_EQ(0U, result.size());
3849 }
3850}
3851
3852/*
3853 * EncryptionOperationsTest.RsaOaepInvalidDigest
3854 *
3855 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3856 * without a digest.
3857 */
3858TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3859 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3860 .Authorization(TAG_NO_AUTH_REQUIRED)
3861 .RsaEncryptionKey(2048, 65537)
3862 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003863 .Digest(Digest::NONE)
3864 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003865
3866 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
3867 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3868}
3869
3870/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003871 * EncryptionOperationsTest.RsaOaepInvalidPadding
3872 *
3873 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3874 * with a padding value that is only suitable for signing/verifying.
3875 */
3876TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3877 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3878 .Authorization(TAG_NO_AUTH_REQUIRED)
3879 .RsaEncryptionKey(2048, 65537)
3880 .Padding(PaddingMode::RSA_PSS)
3881 .Digest(Digest::NONE)
3882 .SetDefaultValidity()));
3883
3884 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
3885 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3886}
3887
3888/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003889 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003890 *
3891 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt
3892 * with a different digest than was used to encrypt.
3893 */
3894TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3895 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3896
3897 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3898 .Authorization(TAG_NO_AUTH_REQUIRED)
3899 .RsaEncryptionKey(1024, 65537)
3900 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003901 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3902 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003903 string message = "Hello World!";
3904 string ciphertext = EncryptMessage(
3905 message,
3906 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3907
3908 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3909 .Digest(Digest::SHA_2_256)
3910 .Padding(PaddingMode::RSA_OAEP)));
3911 string result;
3912 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3913 EXPECT_EQ(0U, result.size());
3914}
3915
3916/*
3917 * EncryptionOperationsTest.RsaOaepTooLarge
3918 *
3919 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a
3920 * too-large message.
3921 */
3922TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
3923 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3924 .Authorization(TAG_NO_AUTH_REQUIRED)
3925 .RsaEncryptionKey(2048, 65537)
3926 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003927 .Digest(Digest::SHA_2_256)
3928 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003929 constexpr size_t digest_size = 256 /* SHA_2_256 */ / 8;
3930 constexpr size_t oaep_overhead = 2 * digest_size + 2;
3931 string message(2048 / 8 - oaep_overhead + 1, 'a');
3932 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
3933 .Padding(PaddingMode::RSA_OAEP)
3934 .Digest(Digest::SHA_2_256)));
3935 string result;
3936 ErrorCode error = Finish(message, &result);
3937 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
3938 EXPECT_EQ(0U, result.size());
3939}
3940
3941/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003942 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3943 *
3944 * Verifies that RSA-OAEP encryption operations work, with all SHA 256 digests and all type of MGF1
3945 * digests.
3946 */
3947TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3948 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3949
3950 size_t key_size = 2048; // Need largish key for SHA-512 test.
3951 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3952 .OaepMGFDigest(digests)
3953 .Authorization(TAG_NO_AUTH_REQUIRED)
3954 .RsaEncryptionKey(key_size, 65537)
3955 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003956 .Digest(Digest::SHA_2_256)
3957 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003958
3959 string message = "Hello";
3960
3961 for (auto digest : digests) {
3962 auto params = AuthorizationSetBuilder()
3963 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
3964 .Digest(Digest::SHA_2_256)
3965 .Padding(PaddingMode::RSA_OAEP);
3966 string ciphertext1 = EncryptMessage(message, params);
3967 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3968 EXPECT_EQ(key_size / 8, ciphertext1.size());
3969
3970 string ciphertext2 = EncryptMessage(message, params);
3971 EXPECT_EQ(key_size / 8, ciphertext2.size());
3972
3973 // OAEP randomizes padding so every result should be different (with astronomically high
3974 // probability).
3975 EXPECT_NE(ciphertext1, ciphertext2);
3976
3977 string plaintext1 = DecryptMessage(ciphertext1, params);
3978 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3979 string plaintext2 = DecryptMessage(ciphertext2, params);
3980 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3981
3982 // Decrypting corrupted ciphertext should fail.
3983 size_t offset_to_corrupt = random() % ciphertext1.size();
3984 char corrupt_byte;
3985 do {
3986 corrupt_byte = static_cast<char>(random() % 256);
3987 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3988 ciphertext1[offset_to_corrupt] = corrupt_byte;
3989
3990 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3991 string result;
3992 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3993 EXPECT_EQ(0U, result.size());
3994 }
3995}
3996
3997/*
3998 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
3999 *
4000 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4001 * with incompatible MGF digest.
4002 */
4003TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4004 ASSERT_EQ(ErrorCode::OK,
4005 GenerateKey(AuthorizationSetBuilder()
4006 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4007 .Authorization(TAG_NO_AUTH_REQUIRED)
4008 .RsaEncryptionKey(2048, 65537)
4009 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004010 .Digest(Digest::SHA_2_256)
4011 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004012 string message = "Hello World!";
4013
4014 auto params = AuthorizationSetBuilder()
4015 .Padding(PaddingMode::RSA_OAEP)
4016 .Digest(Digest::SHA_2_256)
4017 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
4018 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
4019}
4020
4021/*
4022 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4023 *
4024 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4025 * with unsupported MGF digest.
4026 */
4027TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4028 ASSERT_EQ(ErrorCode::OK,
4029 GenerateKey(AuthorizationSetBuilder()
4030 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4031 .Authorization(TAG_NO_AUTH_REQUIRED)
4032 .RsaEncryptionKey(2048, 65537)
4033 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004034 .Digest(Digest::SHA_2_256)
4035 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004036 string message = "Hello World!";
4037
4038 auto params = AuthorizationSetBuilder()
4039 .Padding(PaddingMode::RSA_OAEP)
4040 .Digest(Digest::SHA_2_256)
4041 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
4042 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
4043}
4044
4045/*
Selene Huang31ab4042020-04-29 04:22:39 -07004046 * EncryptionOperationsTest.RsaPkcs1Success
4047 *
4048 * Verifies that RSA PKCS encryption/decrypts works.
4049 */
4050TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4051 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4052 .Authorization(TAG_NO_AUTH_REQUIRED)
4053 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004054 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4055 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004056
4057 string message = "Hello World!";
4058 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
4059 string ciphertext1 = EncryptMessage(message, params);
4060 EXPECT_EQ(2048U / 8, ciphertext1.size());
4061
4062 string ciphertext2 = EncryptMessage(message, params);
4063 EXPECT_EQ(2048U / 8, ciphertext2.size());
4064
4065 // PKCS1 v1.5 randomizes padding so every result should be different.
4066 EXPECT_NE(ciphertext1, ciphertext2);
4067
4068 string plaintext = DecryptMessage(ciphertext1, params);
4069 EXPECT_EQ(message, plaintext);
4070
4071 // Decrypting corrupted ciphertext should fail.
4072 size_t offset_to_corrupt = random() % ciphertext1.size();
4073 char corrupt_byte;
4074 do {
4075 corrupt_byte = static_cast<char>(random() % 256);
4076 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4077 ciphertext1[offset_to_corrupt] = corrupt_byte;
4078
4079 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4080 string result;
4081 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4082 EXPECT_EQ(0U, result.size());
4083}
4084
4085/*
4086 * EncryptionOperationsTest.RsaPkcs1TooLarge
4087 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01004088 * Verifies that RSA PKCS encryption fails in the correct way when the message is too large.
Selene Huang31ab4042020-04-29 04:22:39 -07004089 */
4090TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
4091 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4092 .Authorization(TAG_NO_AUTH_REQUIRED)
4093 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004094 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4095 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004096 string message(2048 / 8 - 10, 'a');
4097
4098 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
4099 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
4100 string result;
4101 ErrorCode error = Finish(message, &result);
4102 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
4103 EXPECT_EQ(0U, result.size());
4104}
4105
4106/*
4107 * EncryptionOperationsTest.EcdsaEncrypt
4108 *
4109 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4110 */
4111TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4112 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4113 .Authorization(TAG_NO_AUTH_REQUIRED)
4114 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004115 .Digest(Digest::NONE)
4116 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004117 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4118 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4119 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4120}
4121
4122/*
4123 * EncryptionOperationsTest.HmacEncrypt
4124 *
4125 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4126 */
4127TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4128 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4129 .Authorization(TAG_NO_AUTH_REQUIRED)
4130 .HmacKey(128)
4131 .Digest(Digest::SHA_2_256)
4132 .Padding(PaddingMode::NONE)
4133 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4134 auto params = AuthorizationSetBuilder()
4135 .Digest(Digest::SHA_2_256)
4136 .Padding(PaddingMode::NONE)
4137 .Authorization(TAG_MAC_LENGTH, 128);
4138 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4139 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4140}
4141
4142/*
4143 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4144 *
4145 * Verifies that AES ECB mode works.
4146 */
4147TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4148 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4149 .Authorization(TAG_NO_AUTH_REQUIRED)
4150 .AesEncryptionKey(128)
4151 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4152 .Padding(PaddingMode::NONE)));
4153
4154 ASSERT_GT(key_blob_.size(), 0U);
4155 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4156
4157 // Two-block message.
4158 string message = "12345678901234567890123456789012";
4159 string ciphertext1 = EncryptMessage(message, params);
4160 EXPECT_EQ(message.size(), ciphertext1.size());
4161
4162 string ciphertext2 = EncryptMessage(string(message), params);
4163 EXPECT_EQ(message.size(), ciphertext2.size());
4164
4165 // ECB is deterministic.
4166 EXPECT_EQ(ciphertext1, ciphertext2);
4167
4168 string plaintext = DecryptMessage(ciphertext1, params);
4169 EXPECT_EQ(message, plaintext);
4170}
4171
4172/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004173 * EncryptionOperationsTest.AesEcbUnknownTag
4174 *
4175 * Verifies that AES ECB operations ignore unknown tags.
4176 */
4177TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4178 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4179 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4180 KeyParameter unknown_param;
4181 unknown_param.tag = unknown_tag;
4182
4183 vector<KeyCharacteristics> key_characteristics;
4184 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4185 .Authorization(TAG_NO_AUTH_REQUIRED)
4186 .AesEncryptionKey(128)
4187 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4188 .Padding(PaddingMode::NONE)
4189 .Authorization(unknown_param),
4190 &key_blob_, &key_characteristics));
4191 ASSERT_GT(key_blob_.size(), 0U);
4192
4193 // Unknown tags should not be returned in key characteristics.
4194 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4195 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4196 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4197 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4198
4199 // Encrypt without mentioning the unknown parameter.
4200 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4201 string message = "12345678901234567890123456789012";
4202 string ciphertext = EncryptMessage(message, params);
4203 EXPECT_EQ(message.size(), ciphertext.size());
4204
4205 // Decrypt including the unknown parameter.
4206 auto decrypt_params = AuthorizationSetBuilder()
4207 .BlockMode(BlockMode::ECB)
4208 .Padding(PaddingMode::NONE)
4209 .Authorization(unknown_param);
4210 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4211 EXPECT_EQ(message, plaintext);
4212}
4213
4214/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004215 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004216 *
4217 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4218 */
4219TEST_P(EncryptionOperationsTest, AesWrongMode) {
4220 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4221 .Authorization(TAG_NO_AUTH_REQUIRED)
4222 .AesEncryptionKey(128)
4223 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4224 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004225 ASSERT_GT(key_blob_.size(), 0U);
4226
Selene Huang31ab4042020-04-29 04:22:39 -07004227 EXPECT_EQ(
4228 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4229 Begin(KeyPurpose::ENCRYPT,
4230 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4231}
4232
4233/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004234 * EncryptionOperationsTest.AesWrongPadding
4235 *
4236 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4237 */
4238TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4239 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4240 .Authorization(TAG_NO_AUTH_REQUIRED)
4241 .AesEncryptionKey(128)
4242 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4243 .Padding(PaddingMode::NONE)));
4244 ASSERT_GT(key_blob_.size(), 0U);
4245
4246 EXPECT_EQ(
4247 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4248 Begin(KeyPurpose::ENCRYPT,
4249 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4250}
4251
4252/*
4253 * EncryptionOperationsTest.AesInvalidParams
4254 *
4255 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4256 */
4257TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4258 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4259 .Authorization(TAG_NO_AUTH_REQUIRED)
4260 .AesEncryptionKey(128)
4261 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4262 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4263 .Padding(PaddingMode::NONE)
4264 .Padding(PaddingMode::PKCS7)));
4265 ASSERT_GT(key_blob_.size(), 0U);
4266
4267 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4268 .BlockMode(BlockMode::CBC)
4269 .BlockMode(BlockMode::ECB)
4270 .Padding(PaddingMode::NONE));
4271 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4272 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4273
4274 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4275 .BlockMode(BlockMode::ECB)
4276 .Padding(PaddingMode::NONE)
4277 .Padding(PaddingMode::PKCS7));
4278 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4279 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4280}
4281
4282/*
Selene Huang31ab4042020-04-29 04:22:39 -07004283 * EncryptionOperationsTest.AesWrongPurpose
4284 *
4285 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4286 * specified.
4287 */
4288TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4289 auto err = GenerateKey(AuthorizationSetBuilder()
4290 .Authorization(TAG_NO_AUTH_REQUIRED)
4291 .AesKey(128)
4292 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4293 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4294 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4295 .Padding(PaddingMode::NONE));
4296 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4297 ASSERT_GT(key_blob_.size(), 0U);
4298
4299 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4300 .BlockMode(BlockMode::GCM)
4301 .Padding(PaddingMode::NONE)
4302 .Authorization(TAG_MAC_LENGTH, 128));
4303 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4304
4305 CheckedDeleteKey();
4306
4307 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4308 .Authorization(TAG_NO_AUTH_REQUIRED)
4309 .AesKey(128)
4310 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4311 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4312 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4313 .Padding(PaddingMode::NONE)));
4314
4315 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4316 .BlockMode(BlockMode::GCM)
4317 .Padding(PaddingMode::NONE)
4318 .Authorization(TAG_MAC_LENGTH, 128));
4319 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4320}
4321
4322/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004323 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004324 *
4325 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4326 * multiple of the block size and no padding is specified.
4327 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004328TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4329 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4330 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4331 .Authorization(TAG_NO_AUTH_REQUIRED)
4332 .AesEncryptionKey(128)
4333 .Authorization(TAG_BLOCK_MODE, blockMode)
4334 .Padding(PaddingMode::NONE)));
4335 // Message is slightly shorter than two blocks.
4336 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004337
David Drysdaled2cc8c22021-04-15 13:29:45 +01004338 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4339 AuthorizationSet out_params;
4340 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4341 string ciphertext;
4342 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4343 EXPECT_EQ(0U, ciphertext.size());
4344
4345 CheckedDeleteKey();
4346 }
Selene Huang31ab4042020-04-29 04:22:39 -07004347}
4348
4349/*
4350 * EncryptionOperationsTest.AesEcbPkcs7Padding
4351 *
4352 * Verifies that AES PKCS7 padding works for any message length.
4353 */
4354TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4355 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4356 .Authorization(TAG_NO_AUTH_REQUIRED)
4357 .AesEncryptionKey(128)
4358 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4359 .Padding(PaddingMode::PKCS7)));
4360
4361 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4362
4363 // Try various message lengths; all should work.
4364 for (size_t i = 0; i < 32; ++i) {
4365 string message(i, 'a');
4366 string ciphertext = EncryptMessage(message, params);
4367 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4368 string plaintext = DecryptMessage(ciphertext, params);
4369 EXPECT_EQ(message, plaintext);
4370 }
4371}
4372
4373/*
4374 * EncryptionOperationsTest.AesEcbWrongPadding
4375 *
4376 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4377 * specified.
4378 */
4379TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4380 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4381 .Authorization(TAG_NO_AUTH_REQUIRED)
4382 .AesEncryptionKey(128)
4383 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4384 .Padding(PaddingMode::NONE)));
4385
4386 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4387
4388 // Try various message lengths; all should fail
4389 for (size_t i = 0; i < 32; ++i) {
4390 string message(i, 'a');
4391 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4392 }
4393}
4394
4395/*
4396 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4397 *
4398 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4399 */
4400TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4401 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4402 .Authorization(TAG_NO_AUTH_REQUIRED)
4403 .AesEncryptionKey(128)
4404 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4405 .Padding(PaddingMode::PKCS7)));
4406
4407 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4408
4409 string message = "a";
4410 string ciphertext = EncryptMessage(message, params);
4411 EXPECT_EQ(16U, ciphertext.size());
4412 EXPECT_NE(ciphertext, message);
4413 ++ciphertext[ciphertext.size() / 2];
4414
4415 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4416 string plaintext;
4417 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
4418}
4419
4420vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4421 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004422 EXPECT_TRUE(iv);
4423 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004424}
4425
4426/*
4427 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4428 *
4429 * Verifies that AES CTR mode works.
4430 */
4431TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4432 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4433 .Authorization(TAG_NO_AUTH_REQUIRED)
4434 .AesEncryptionKey(128)
4435 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4436 .Padding(PaddingMode::NONE)));
4437
4438 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4439
4440 string message = "123";
4441 AuthorizationSet out_params;
4442 string ciphertext1 = EncryptMessage(message, params, &out_params);
4443 vector<uint8_t> iv1 = CopyIv(out_params);
4444 EXPECT_EQ(16U, iv1.size());
4445
4446 EXPECT_EQ(message.size(), ciphertext1.size());
4447
4448 out_params.Clear();
4449 string ciphertext2 = EncryptMessage(message, params, &out_params);
4450 vector<uint8_t> iv2 = CopyIv(out_params);
4451 EXPECT_EQ(16U, iv2.size());
4452
4453 // IVs should be random, so ciphertexts should differ.
4454 EXPECT_NE(ciphertext1, ciphertext2);
4455
4456 auto params_iv1 =
4457 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4458 auto params_iv2 =
4459 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4460
4461 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4462 EXPECT_EQ(message, plaintext);
4463 plaintext = DecryptMessage(ciphertext2, params_iv2);
4464 EXPECT_EQ(message, plaintext);
4465
4466 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4467 plaintext = DecryptMessage(ciphertext1, params_iv2);
4468 EXPECT_NE(message, plaintext);
4469 plaintext = DecryptMessage(ciphertext2, params_iv1);
4470 EXPECT_NE(message, plaintext);
4471}
4472
4473/*
4474 * EncryptionOperationsTest.AesIncremental
4475 *
4476 * Verifies that AES works, all modes, when provided data in various size increments.
4477 */
4478TEST_P(EncryptionOperationsTest, AesIncremental) {
4479 auto block_modes = {
4480 BlockMode::ECB,
4481 BlockMode::CBC,
4482 BlockMode::CTR,
4483 BlockMode::GCM,
4484 };
4485
4486 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4487 .Authorization(TAG_NO_AUTH_REQUIRED)
4488 .AesEncryptionKey(128)
4489 .BlockMode(block_modes)
4490 .Padding(PaddingMode::NONE)
4491 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4492
4493 for (int increment = 1; increment <= 240; ++increment) {
4494 for (auto block_mode : block_modes) {
4495 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004496 auto params =
4497 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4498 if (block_mode == BlockMode::GCM) {
4499 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4500 }
Selene Huang31ab4042020-04-29 04:22:39 -07004501
4502 AuthorizationSet output_params;
4503 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4504
4505 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004506 string to_send;
4507 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004508 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004509 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004510 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4511 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004512
4513 switch (block_mode) {
4514 case BlockMode::GCM:
4515 EXPECT_EQ(message.size() + 16, ciphertext.size());
4516 break;
4517 case BlockMode::CTR:
4518 EXPECT_EQ(message.size(), ciphertext.size());
4519 break;
4520 case BlockMode::CBC:
4521 case BlockMode::ECB:
4522 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4523 break;
4524 }
4525
4526 auto iv = output_params.GetTagValue(TAG_NONCE);
4527 switch (block_mode) {
4528 case BlockMode::CBC:
4529 case BlockMode::GCM:
4530 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004531 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4532 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4533 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004534 break;
4535
4536 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004537 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004538 break;
4539 }
4540
4541 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4542 << "Decrypt begin() failed for block mode " << block_mode;
4543
4544 string plaintext;
4545 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004546 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004547 }
4548 ErrorCode error = Finish(to_send, &plaintext);
4549 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4550 << " and increment " << increment;
4551 if (error == ErrorCode::OK) {
4552 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4553 << block_mode << " and increment " << increment;
4554 }
4555 }
4556 }
4557}
4558
4559struct AesCtrSp80038aTestVector {
4560 const char* key;
4561 const char* nonce;
4562 const char* plaintext;
4563 const char* ciphertext;
4564};
4565
4566// These test vectors are taken from
4567// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4568static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4569 // AES-128
4570 {
4571 "2b7e151628aed2a6abf7158809cf4f3c",
4572 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4573 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4574 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4575 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4576 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4577 },
4578 // AES-192
4579 {
4580 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4581 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4582 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4583 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4584 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4585 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4586 },
4587 // AES-256
4588 {
4589 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4590 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4591 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4592 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4593 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4594 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4595 },
4596};
4597
4598/*
4599 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4600 *
4601 * Verifies AES CTR implementation against SP800-38A test vectors.
4602 */
4603TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4604 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4605 for (size_t i = 0; i < 3; i++) {
4606 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4607 const string key = hex2str(test.key);
4608 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4609 InvalidSizes.end())
4610 continue;
4611 const string nonce = hex2str(test.nonce);
4612 const string plaintext = hex2str(test.plaintext);
4613 const string ciphertext = hex2str(test.ciphertext);
4614 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4615 }
4616}
4617
4618/*
4619 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4620 *
4621 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4622 */
4623TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4624 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4625 .Authorization(TAG_NO_AUTH_REQUIRED)
4626 .AesEncryptionKey(128)
4627 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4628 .Padding(PaddingMode::PKCS7)));
4629 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4630 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4631}
4632
4633/*
4634 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4635 *
4636 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4637 */
4638TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4639 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4640 .Authorization(TAG_NO_AUTH_REQUIRED)
4641 .AesEncryptionKey(128)
4642 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4643 .Authorization(TAG_CALLER_NONCE)
4644 .Padding(PaddingMode::NONE)));
4645
4646 auto params = AuthorizationSetBuilder()
4647 .BlockMode(BlockMode::CTR)
4648 .Padding(PaddingMode::NONE)
4649 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4650 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4651
4652 params = AuthorizationSetBuilder()
4653 .BlockMode(BlockMode::CTR)
4654 .Padding(PaddingMode::NONE)
4655 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4656 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4657
4658 params = AuthorizationSetBuilder()
4659 .BlockMode(BlockMode::CTR)
4660 .Padding(PaddingMode::NONE)
4661 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4662 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4663}
4664
4665/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004666 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004667 *
4668 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4669 */
4670TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4671 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4672 .Authorization(TAG_NO_AUTH_REQUIRED)
4673 .AesEncryptionKey(128)
4674 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4675 .Padding(PaddingMode::NONE)));
4676 // Two-block message.
4677 string message = "12345678901234567890123456789012";
4678 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4679 AuthorizationSet out_params;
4680 string ciphertext1 = EncryptMessage(message, params, &out_params);
4681 vector<uint8_t> iv1 = CopyIv(out_params);
4682 EXPECT_EQ(message.size(), ciphertext1.size());
4683
4684 out_params.Clear();
4685
4686 string ciphertext2 = EncryptMessage(message, params, &out_params);
4687 vector<uint8_t> iv2 = CopyIv(out_params);
4688 EXPECT_EQ(message.size(), ciphertext2.size());
4689
4690 // IVs should be random, so ciphertexts should differ.
4691 EXPECT_NE(ciphertext1, ciphertext2);
4692
4693 params.push_back(TAG_NONCE, iv1);
4694 string plaintext = DecryptMessage(ciphertext1, params);
4695 EXPECT_EQ(message, plaintext);
4696}
4697
4698/*
4699 * EncryptionOperationsTest.AesCallerNonce
4700 *
4701 * Verifies that AES caller-provided nonces work correctly.
4702 */
4703TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4704 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4705 .Authorization(TAG_NO_AUTH_REQUIRED)
4706 .AesEncryptionKey(128)
4707 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4708 .Authorization(TAG_CALLER_NONCE)
4709 .Padding(PaddingMode::NONE)));
4710
4711 string message = "12345678901234567890123456789012";
4712
4713 // Don't specify nonce, should get a random one.
4714 AuthorizationSetBuilder params =
4715 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4716 AuthorizationSet out_params;
4717 string ciphertext = EncryptMessage(message, params, &out_params);
4718 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004719 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004720
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004721 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004722 string plaintext = DecryptMessage(ciphertext, params);
4723 EXPECT_EQ(message, plaintext);
4724
4725 // Now specify a nonce, should also work.
4726 params = AuthorizationSetBuilder()
4727 .BlockMode(BlockMode::CBC)
4728 .Padding(PaddingMode::NONE)
4729 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4730 out_params.Clear();
4731 ciphertext = EncryptMessage(message, params, &out_params);
4732
4733 // Decrypt with correct nonce.
4734 plaintext = DecryptMessage(ciphertext, params);
4735 EXPECT_EQ(message, plaintext);
4736
4737 // Try with wrong nonce.
4738 params = AuthorizationSetBuilder()
4739 .BlockMode(BlockMode::CBC)
4740 .Padding(PaddingMode::NONE)
4741 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4742 plaintext = DecryptMessage(ciphertext, params);
4743 EXPECT_NE(message, plaintext);
4744}
4745
4746/*
4747 * EncryptionOperationsTest.AesCallerNonceProhibited
4748 *
4749 * Verifies that caller-provided nonces are not permitted when not specified in the key
4750 * authorizations.
4751 */
4752TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4753 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4754 .Authorization(TAG_NO_AUTH_REQUIRED)
4755 .AesEncryptionKey(128)
4756 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4757 .Padding(PaddingMode::NONE)));
4758
4759 string message = "12345678901234567890123456789012";
4760
4761 // Don't specify nonce, should get a random one.
4762 AuthorizationSetBuilder params =
4763 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4764 AuthorizationSet out_params;
4765 string ciphertext = EncryptMessage(message, params, &out_params);
4766 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004767 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004768
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004769 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004770 string plaintext = DecryptMessage(ciphertext, params);
4771 EXPECT_EQ(message, plaintext);
4772
4773 // Now specify a nonce, should fail
4774 params = AuthorizationSetBuilder()
4775 .BlockMode(BlockMode::CBC)
4776 .Padding(PaddingMode::NONE)
4777 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4778 out_params.Clear();
4779 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4780}
4781
4782/*
4783 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4784 *
4785 * Verifies that AES GCM mode works.
4786 */
4787TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4788 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4789 .Authorization(TAG_NO_AUTH_REQUIRED)
4790 .AesEncryptionKey(128)
4791 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4792 .Padding(PaddingMode::NONE)
4793 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4794
4795 string aad = "foobar";
4796 string message = "123456789012345678901234567890123456";
4797
4798 auto begin_params = AuthorizationSetBuilder()
4799 .BlockMode(BlockMode::GCM)
4800 .Padding(PaddingMode::NONE)
4801 .Authorization(TAG_MAC_LENGTH, 128);
4802
Selene Huang31ab4042020-04-29 04:22:39 -07004803 // Encrypt
4804 AuthorizationSet begin_out_params;
4805 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4806 << "Begin encrypt";
4807 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004808 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4809 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004810 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4811
4812 // Grab nonce
4813 begin_params.push_back(begin_out_params);
4814
4815 // Decrypt.
4816 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004817 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004818 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004819 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004820 EXPECT_EQ(message.length(), plaintext.length());
4821 EXPECT_EQ(message, plaintext);
4822}
4823
4824/*
4825 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4826 *
4827 * Verifies that AES GCM mode works, even when there's a long delay
4828 * between operations.
4829 */
4830TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4831 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4832 .Authorization(TAG_NO_AUTH_REQUIRED)
4833 .AesEncryptionKey(128)
4834 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4835 .Padding(PaddingMode::NONE)
4836 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4837
4838 string aad = "foobar";
4839 string message = "123456789012345678901234567890123456";
4840
4841 auto begin_params = AuthorizationSetBuilder()
4842 .BlockMode(BlockMode::GCM)
4843 .Padding(PaddingMode::NONE)
4844 .Authorization(TAG_MAC_LENGTH, 128);
4845
Selene Huang31ab4042020-04-29 04:22:39 -07004846 // Encrypt
4847 AuthorizationSet begin_out_params;
4848 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4849 << "Begin encrypt";
4850 string ciphertext;
4851 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004852 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004853 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004854 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004855
4856 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4857
4858 // Grab nonce
4859 begin_params.push_back(begin_out_params);
4860
4861 // Decrypt.
4862 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4863 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004864 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004865 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004866 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004867 sleep(5);
4868 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4869 EXPECT_EQ(message.length(), plaintext.length());
4870 EXPECT_EQ(message, plaintext);
4871}
4872
4873/*
4874 * EncryptionOperationsTest.AesGcmDifferentNonces
4875 *
4876 * Verifies that encrypting the same data with different nonces produces different outputs.
4877 */
4878TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4879 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4880 .Authorization(TAG_NO_AUTH_REQUIRED)
4881 .AesEncryptionKey(128)
4882 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4883 .Padding(PaddingMode::NONE)
4884 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4885 .Authorization(TAG_CALLER_NONCE)));
4886
4887 string aad = "foobar";
4888 string message = "123456789012345678901234567890123456";
4889 string nonce1 = "000000000000";
4890 string nonce2 = "111111111111";
4891 string nonce3 = "222222222222";
4892
4893 string ciphertext1 =
4894 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4895 string ciphertext2 =
4896 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4897 string ciphertext3 =
4898 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4899
4900 ASSERT_NE(ciphertext1, ciphertext2);
4901 ASSERT_NE(ciphertext1, ciphertext3);
4902 ASSERT_NE(ciphertext2, ciphertext3);
4903}
4904
4905/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004906 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4907 *
4908 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4909 */
4910TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4911 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4912 .Authorization(TAG_NO_AUTH_REQUIRED)
4913 .AesEncryptionKey(128)
4914 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4915 .Padding(PaddingMode::NONE)
4916 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4917
4918 string aad = "foobar";
4919 string message = "123456789012345678901234567890123456";
4920
4921 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4922 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4923 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4924
4925 ASSERT_NE(ciphertext1, ciphertext2);
4926 ASSERT_NE(ciphertext1, ciphertext3);
4927 ASSERT_NE(ciphertext2, ciphertext3);
4928}
4929
4930/*
Selene Huang31ab4042020-04-29 04:22:39 -07004931 * EncryptionOperationsTest.AesGcmTooShortTag
4932 *
4933 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4934 */
4935TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4936 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4937 .Authorization(TAG_NO_AUTH_REQUIRED)
4938 .AesEncryptionKey(128)
4939 .BlockMode(BlockMode::GCM)
4940 .Padding(PaddingMode::NONE)
4941 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4942 string message = "123456789012345678901234567890123456";
4943 auto params = AuthorizationSetBuilder()
4944 .BlockMode(BlockMode::GCM)
4945 .Padding(PaddingMode::NONE)
4946 .Authorization(TAG_MAC_LENGTH, 96);
4947
4948 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4949}
4950
4951/*
4952 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4953 *
4954 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4955 */
4956TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4957 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4958 .Authorization(TAG_NO_AUTH_REQUIRED)
4959 .AesEncryptionKey(128)
4960 .BlockMode(BlockMode::GCM)
4961 .Padding(PaddingMode::NONE)
4962 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4963 string aad = "foobar";
4964 string message = "123456789012345678901234567890123456";
4965 auto params = AuthorizationSetBuilder()
4966 .BlockMode(BlockMode::GCM)
4967 .Padding(PaddingMode::NONE)
4968 .Authorization(TAG_MAC_LENGTH, 128);
4969
Selene Huang31ab4042020-04-29 04:22:39 -07004970 // Encrypt
4971 AuthorizationSet begin_out_params;
4972 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4973 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004974 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004975
4976 AuthorizationSet finish_out_params;
4977 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004978 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4979 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004980
4981 params = AuthorizationSetBuilder()
4982 .Authorizations(begin_out_params)
4983 .BlockMode(BlockMode::GCM)
4984 .Padding(PaddingMode::NONE)
4985 .Authorization(TAG_MAC_LENGTH, 96);
4986
4987 // Decrypt.
4988 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
4989}
4990
4991/*
4992 * EncryptionOperationsTest.AesGcmCorruptKey
4993 *
4994 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
4995 */
4996TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
4997 const uint8_t nonce_bytes[] = {
4998 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
4999 };
5000 string nonce = make_string(nonce_bytes);
5001 const uint8_t ciphertext_bytes[] = {
5002 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
5003 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
5004 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
5005 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5006 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5007 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5008 };
5009 string ciphertext = make_string(ciphertext_bytes);
5010
5011 auto params = AuthorizationSetBuilder()
5012 .BlockMode(BlockMode::GCM)
5013 .Padding(PaddingMode::NONE)
5014 .Authorization(TAG_MAC_LENGTH, 128)
5015 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5016
5017 auto import_params = AuthorizationSetBuilder()
5018 .Authorization(TAG_NO_AUTH_REQUIRED)
5019 .AesEncryptionKey(128)
5020 .BlockMode(BlockMode::GCM)
5021 .Padding(PaddingMode::NONE)
5022 .Authorization(TAG_CALLER_NONCE)
5023 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5024
5025 // Import correct key and decrypt
5026 const uint8_t key_bytes[] = {
5027 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5028 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5029 };
5030 string key = make_string(key_bytes);
5031 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5032 string plaintext = DecryptMessage(ciphertext, params);
5033 CheckedDeleteKey();
5034
5035 // Corrupt key and attempt to decrypt
5036 key[0] = 0;
5037 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5038 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5039 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5040 CheckedDeleteKey();
5041}
5042
5043/*
5044 * EncryptionOperationsTest.AesGcmAadNoData
5045 *
5046 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5047 * encrypt.
5048 */
5049TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5050 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5051 .Authorization(TAG_NO_AUTH_REQUIRED)
5052 .AesEncryptionKey(128)
5053 .BlockMode(BlockMode::GCM)
5054 .Padding(PaddingMode::NONE)
5055 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5056
5057 string aad = "1234567890123456";
5058 auto params = AuthorizationSetBuilder()
5059 .BlockMode(BlockMode::GCM)
5060 .Padding(PaddingMode::NONE)
5061 .Authorization(TAG_MAC_LENGTH, 128);
5062
Selene Huang31ab4042020-04-29 04:22:39 -07005063 // Encrypt
5064 AuthorizationSet begin_out_params;
5065 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5066 string ciphertext;
5067 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005068 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5069 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005070 EXPECT_TRUE(finish_out_params.empty());
5071
5072 // Grab nonce
5073 params.push_back(begin_out_params);
5074
5075 // Decrypt.
5076 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005077 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005078 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005079 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005080
5081 EXPECT_TRUE(finish_out_params.empty());
5082
5083 EXPECT_EQ("", plaintext);
5084}
5085
5086/*
5087 * EncryptionOperationsTest.AesGcmMultiPartAad
5088 *
5089 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5090 * chunks.
5091 */
5092TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5093 const size_t tag_bits = 128;
5094 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5095 .Authorization(TAG_NO_AUTH_REQUIRED)
5096 .AesEncryptionKey(128)
5097 .BlockMode(BlockMode::GCM)
5098 .Padding(PaddingMode::NONE)
5099 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5100
5101 string message = "123456789012345678901234567890123456";
5102 auto begin_params = AuthorizationSetBuilder()
5103 .BlockMode(BlockMode::GCM)
5104 .Padding(PaddingMode::NONE)
5105 .Authorization(TAG_MAC_LENGTH, tag_bits);
5106 AuthorizationSet begin_out_params;
5107
Selene Huang31ab4042020-04-29 04:22:39 -07005108 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5109
5110 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005111 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5112 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005113 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005114 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5115 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005116
Selene Huang31ab4042020-04-29 04:22:39 -07005117 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005118 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005119
5120 // Grab nonce.
5121 begin_params.push_back(begin_out_params);
5122
5123 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005124 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005125 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005126 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005127 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005128 EXPECT_EQ(message, plaintext);
5129}
5130
5131/*
5132 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5133 *
5134 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5135 */
5136TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5137 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5138 .Authorization(TAG_NO_AUTH_REQUIRED)
5139 .AesEncryptionKey(128)
5140 .BlockMode(BlockMode::GCM)
5141 .Padding(PaddingMode::NONE)
5142 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5143
5144 string message = "123456789012345678901234567890123456";
5145 auto begin_params = AuthorizationSetBuilder()
5146 .BlockMode(BlockMode::GCM)
5147 .Padding(PaddingMode::NONE)
5148 .Authorization(TAG_MAC_LENGTH, 128);
5149 AuthorizationSet begin_out_params;
5150
Selene Huang31ab4042020-04-29 04:22:39 -07005151 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5152
Shawn Willden92d79c02021-02-19 07:31:55 -07005153 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005154 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005155 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5156 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005157
David Drysdaled2cc8c22021-04-15 13:29:45 +01005158 // The failure should have already cancelled the operation.
5159 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5160
Shawn Willden92d79c02021-02-19 07:31:55 -07005161 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005162}
5163
5164/*
5165 * EncryptionOperationsTest.AesGcmBadAad
5166 *
5167 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5168 */
5169TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5170 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5171 .Authorization(TAG_NO_AUTH_REQUIRED)
5172 .AesEncryptionKey(128)
5173 .BlockMode(BlockMode::GCM)
5174 .Padding(PaddingMode::NONE)
5175 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5176
5177 string message = "12345678901234567890123456789012";
5178 auto begin_params = AuthorizationSetBuilder()
5179 .BlockMode(BlockMode::GCM)
5180 .Padding(PaddingMode::NONE)
5181 .Authorization(TAG_MAC_LENGTH, 128);
5182
Selene Huang31ab4042020-04-29 04:22:39 -07005183 // Encrypt
5184 AuthorizationSet begin_out_params;
5185 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005186 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005187 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005188 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005189
5190 // Grab nonce
5191 begin_params.push_back(begin_out_params);
5192
Selene Huang31ab4042020-04-29 04:22:39 -07005193 // Decrypt.
5194 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005195 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005196 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005197 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005198}
5199
5200/*
5201 * EncryptionOperationsTest.AesGcmWrongNonce
5202 *
5203 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5204 */
5205TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5206 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5207 .Authorization(TAG_NO_AUTH_REQUIRED)
5208 .AesEncryptionKey(128)
5209 .BlockMode(BlockMode::GCM)
5210 .Padding(PaddingMode::NONE)
5211 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5212
5213 string message = "12345678901234567890123456789012";
5214 auto begin_params = AuthorizationSetBuilder()
5215 .BlockMode(BlockMode::GCM)
5216 .Padding(PaddingMode::NONE)
5217 .Authorization(TAG_MAC_LENGTH, 128);
5218
Selene Huang31ab4042020-04-29 04:22:39 -07005219 // Encrypt
5220 AuthorizationSet begin_out_params;
5221 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005222 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005223 string ciphertext;
5224 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005225 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005226
5227 // Wrong nonce
5228 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5229
5230 // Decrypt.
5231 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005232 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005233 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005234 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005235
5236 // With wrong nonce, should have gotten garbage plaintext (or none).
5237 EXPECT_NE(message, plaintext);
5238}
5239
5240/*
5241 * EncryptionOperationsTest.AesGcmCorruptTag
5242 *
5243 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5244 */
5245TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5246 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5247 .Authorization(TAG_NO_AUTH_REQUIRED)
5248 .AesEncryptionKey(128)
5249 .BlockMode(BlockMode::GCM)
5250 .Padding(PaddingMode::NONE)
5251 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5252
5253 string aad = "1234567890123456";
5254 string message = "123456789012345678901234567890123456";
5255
5256 auto params = AuthorizationSetBuilder()
5257 .BlockMode(BlockMode::GCM)
5258 .Padding(PaddingMode::NONE)
5259 .Authorization(TAG_MAC_LENGTH, 128);
5260
Selene Huang31ab4042020-04-29 04:22:39 -07005261 // Encrypt
5262 AuthorizationSet begin_out_params;
5263 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005264 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005265 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005266 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005267
5268 // Corrupt tag
5269 ++(*ciphertext.rbegin());
5270
5271 // Grab nonce
5272 params.push_back(begin_out_params);
5273
5274 // Decrypt.
5275 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005276 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005277 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005278 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005279}
5280
5281/*
5282 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5283 *
5284 * Verifies that 3DES is basically functional.
5285 */
5286TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5287 auto auths = AuthorizationSetBuilder()
5288 .TripleDesEncryptionKey(168)
5289 .BlockMode(BlockMode::ECB)
5290 .Authorization(TAG_NO_AUTH_REQUIRED)
5291 .Padding(PaddingMode::NONE);
5292
5293 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5294 // Two-block message.
5295 string message = "1234567890123456";
5296 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5297 string ciphertext1 = EncryptMessage(message, inParams);
5298 EXPECT_EQ(message.size(), ciphertext1.size());
5299
5300 string ciphertext2 = EncryptMessage(string(message), inParams);
5301 EXPECT_EQ(message.size(), ciphertext2.size());
5302
5303 // ECB is deterministic.
5304 EXPECT_EQ(ciphertext1, ciphertext2);
5305
5306 string plaintext = DecryptMessage(ciphertext1, inParams);
5307 EXPECT_EQ(message, plaintext);
5308}
5309
5310/*
5311 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5312 *
5313 * Verifies that CBC keys reject ECB usage.
5314 */
5315TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5316 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5317 .TripleDesEncryptionKey(168)
5318 .BlockMode(BlockMode::CBC)
5319 .Authorization(TAG_NO_AUTH_REQUIRED)
5320 .Padding(PaddingMode::NONE)));
5321
5322 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5323 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5324}
5325
5326/*
5327 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5328 *
5329 * Tests ECB mode with PKCS#7 padding, various message sizes.
5330 */
5331TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5332 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5333 .TripleDesEncryptionKey(168)
5334 .BlockMode(BlockMode::ECB)
5335 .Authorization(TAG_NO_AUTH_REQUIRED)
5336 .Padding(PaddingMode::PKCS7)));
5337
5338 for (size_t i = 0; i < 32; ++i) {
5339 string message(i, 'a');
5340 auto inParams =
5341 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5342 string ciphertext = EncryptMessage(message, inParams);
5343 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5344 string plaintext = DecryptMessage(ciphertext, inParams);
5345 EXPECT_EQ(message, plaintext);
5346 }
5347}
5348
5349/*
5350 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5351 *
5352 * Verifies that keys configured for no padding reject PKCS7 padding
5353 */
5354TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5355 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5356 .TripleDesEncryptionKey(168)
5357 .BlockMode(BlockMode::ECB)
5358 .Authorization(TAG_NO_AUTH_REQUIRED)
5359 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005360 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5361 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005362}
5363
5364/*
5365 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5366 *
5367 * Verifies that corrupted padding is detected.
5368 */
5369TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5370 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5371 .TripleDesEncryptionKey(168)
5372 .BlockMode(BlockMode::ECB)
5373 .Authorization(TAG_NO_AUTH_REQUIRED)
5374 .Padding(PaddingMode::PKCS7)));
5375
5376 string message = "a";
5377 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5378 EXPECT_EQ(8U, ciphertext.size());
5379 EXPECT_NE(ciphertext, message);
5380 ++ciphertext[ciphertext.size() / 2];
5381
5382 AuthorizationSetBuilder begin_params;
5383 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5384 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
5385 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5386 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005387 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005388 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5389}
5390
5391struct TripleDesTestVector {
5392 const char* name;
5393 const KeyPurpose purpose;
5394 const BlockMode block_mode;
5395 const PaddingMode padding_mode;
5396 const char* key;
5397 const char* iv;
5398 const char* input;
5399 const char* output;
5400};
5401
5402// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5403// of the NIST vectors are multiples of the block size.
5404static const TripleDesTestVector kTripleDesTestVectors[] = {
5405 {
5406 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5407 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5408 "", // IV
5409 "329d86bdf1bc5af4", // input
5410 "d946c2756d78633f", // output
5411 },
5412 {
5413 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5414 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5415 "", // IV
5416 "6b1540781b01ce1997adae102dbf3c5b", // input
5417 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5418 },
5419 {
5420 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5421 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5422 "", // IV
5423 "6daad94ce08acfe7", // input
5424 "660e7d32dcc90e79", // output
5425 },
5426 {
5427 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5428 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5429 "", // IV
5430 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5431 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5432 },
5433 {
5434 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5435 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5436 "43f791134c5647ba", // IV
5437 "dcc153cef81d6f24", // input
5438 "92538bd8af18d3ba", // output
5439 },
5440 {
5441 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5442 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5443 "c2e999cb6249023c", // IV
5444 "c689aee38a301bb316da75db36f110b5", // input
5445 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5446 },
5447 {
5448 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5449 PaddingMode::PKCS7,
5450 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5451 "c2e999cb6249023c", // IV
5452 "c689aee38a301bb316da75db36f110b500", // input
5453 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5454 },
5455 {
5456 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5457 PaddingMode::PKCS7,
5458 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5459 "c2e999cb6249023c", // IV
5460 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5461 "c689aee38a301bb316da75db36f110b500", // output
5462 },
5463 {
5464 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5465 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5466 "41746c7e442d3681", // IV
5467 "c53a7b0ec40600fe", // input
5468 "d4f00eb455de1034", // output
5469 },
5470 {
5471 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5472 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5473 "3982bc02c3727d45", // IV
5474 "6006f10adef52991fcc777a1238bbb65", // input
5475 "edae09288e9e3bc05746d872b48e3b29", // output
5476 },
5477};
5478
5479/*
5480 * EncryptionOperationsTest.TripleDesTestVector
5481 *
5482 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5483 */
5484TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5485 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5486 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5487 SCOPED_TRACE(test->name);
5488 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5489 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5490 hex2str(test->output));
5491 }
5492}
5493
5494/*
5495 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5496 *
5497 * Validates CBC mode functionality.
5498 */
5499TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5500 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5501 .TripleDesEncryptionKey(168)
5502 .BlockMode(BlockMode::CBC)
5503 .Authorization(TAG_NO_AUTH_REQUIRED)
5504 .Padding(PaddingMode::NONE)));
5505
5506 ASSERT_GT(key_blob_.size(), 0U);
5507
5508 // Two-block message.
5509 string message = "1234567890123456";
5510 vector<uint8_t> iv1;
5511 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5512 EXPECT_EQ(message.size(), ciphertext1.size());
5513
5514 vector<uint8_t> iv2;
5515 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5516 EXPECT_EQ(message.size(), ciphertext2.size());
5517
5518 // IVs should be random, so ciphertexts should differ.
5519 EXPECT_NE(iv1, iv2);
5520 EXPECT_NE(ciphertext1, ciphertext2);
5521
5522 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5523 EXPECT_EQ(message, plaintext);
5524}
5525
5526/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005527 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5528 *
5529 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5530 */
5531TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5532 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5533 .TripleDesEncryptionKey(168)
5534 .BlockMode(BlockMode::CBC)
5535 .Authorization(TAG_NO_AUTH_REQUIRED)
5536 .Authorization(TAG_CALLER_NONCE)
5537 .Padding(PaddingMode::NONE)));
5538 auto params = AuthorizationSetBuilder()
5539 .BlockMode(BlockMode::CBC)
5540 .Padding(PaddingMode::NONE)
5541 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5542 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5543}
5544
5545/*
Selene Huang31ab4042020-04-29 04:22:39 -07005546 * EncryptionOperationsTest.TripleDesCallerIv
5547 *
5548 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5549 */
5550TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5551 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5552 .TripleDesEncryptionKey(168)
5553 .BlockMode(BlockMode::CBC)
5554 .Authorization(TAG_NO_AUTH_REQUIRED)
5555 .Authorization(TAG_CALLER_NONCE)
5556 .Padding(PaddingMode::NONE)));
5557 string message = "1234567890123456";
5558 vector<uint8_t> iv;
5559 // Don't specify IV, should get a random one.
5560 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5561 EXPECT_EQ(message.size(), ciphertext1.size());
5562 EXPECT_EQ(8U, iv.size());
5563
5564 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5565 EXPECT_EQ(message, plaintext);
5566
5567 // Now specify an IV, should also work.
5568 iv = AidlBuf("abcdefgh");
5569 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5570
5571 // Decrypt with correct IV.
5572 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5573 EXPECT_EQ(message, plaintext);
5574
5575 // Now try with wrong IV.
5576 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5577 EXPECT_NE(message, plaintext);
5578}
5579
5580/*
5581 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5582 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005583 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005584 */
5585TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5586 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5587 .TripleDesEncryptionKey(168)
5588 .BlockMode(BlockMode::CBC)
5589 .Authorization(TAG_NO_AUTH_REQUIRED)
5590 .Padding(PaddingMode::NONE)));
5591
5592 string message = "12345678901234567890123456789012";
5593 vector<uint8_t> iv;
5594 // Don't specify nonce, should get a random one.
5595 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5596 EXPECT_EQ(message.size(), ciphertext1.size());
5597 EXPECT_EQ(8U, iv.size());
5598
5599 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5600 EXPECT_EQ(message, plaintext);
5601
5602 // Now specify a nonce, should fail.
5603 auto input_params = AuthorizationSetBuilder()
5604 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5605 .BlockMode(BlockMode::CBC)
5606 .Padding(PaddingMode::NONE);
5607 AuthorizationSet output_params;
5608 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5609 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5610}
5611
5612/*
5613 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5614 *
5615 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5616 */
5617TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5618 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5619 .TripleDesEncryptionKey(168)
5620 .BlockMode(BlockMode::ECB)
5621 .Authorization(TAG_NO_AUTH_REQUIRED)
5622 .Padding(PaddingMode::NONE)));
5623 // Two-block message.
5624 string message = "1234567890123456";
5625 auto begin_params =
5626 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5627 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5628}
5629
5630/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005631 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005632 *
5633 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5634 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005635TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5636 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5637 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5638 .TripleDesEncryptionKey(168)
5639 .BlockMode(blockMode)
5640 .Authorization(TAG_NO_AUTH_REQUIRED)
5641 .Padding(PaddingMode::NONE)));
5642 // Message is slightly shorter than two blocks.
5643 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005644
David Drysdaled2cc8c22021-04-15 13:29:45 +01005645 auto begin_params =
5646 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5647 AuthorizationSet output_params;
5648 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5649 string ciphertext;
5650 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5651
5652 CheckedDeleteKey();
5653 }
Selene Huang31ab4042020-04-29 04:22:39 -07005654}
5655
5656/*
5657 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5658 *
5659 * Verifies that PKCS7 padding works correctly in CBC mode.
5660 */
5661TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5662 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5663 .TripleDesEncryptionKey(168)
5664 .BlockMode(BlockMode::CBC)
5665 .Authorization(TAG_NO_AUTH_REQUIRED)
5666 .Padding(PaddingMode::PKCS7)));
5667
5668 // Try various message lengths; all should work.
5669 for (size_t i = 0; i < 32; ++i) {
5670 string message(i, 'a');
5671 vector<uint8_t> iv;
5672 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5673 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5674 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5675 EXPECT_EQ(message, plaintext);
5676 }
5677}
5678
5679/*
5680 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5681 *
5682 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5683 */
5684TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5685 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5686 .TripleDesEncryptionKey(168)
5687 .BlockMode(BlockMode::CBC)
5688 .Authorization(TAG_NO_AUTH_REQUIRED)
5689 .Padding(PaddingMode::NONE)));
5690
5691 // Try various message lengths; all should fail.
5692 for (size_t i = 0; i < 32; ++i) {
5693 auto begin_params =
5694 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5695 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5696 }
5697}
5698
5699/*
5700 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5701 *
5702 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5703 */
5704TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5705 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5706 .TripleDesEncryptionKey(168)
5707 .BlockMode(BlockMode::CBC)
5708 .Authorization(TAG_NO_AUTH_REQUIRED)
5709 .Padding(PaddingMode::PKCS7)));
5710
5711 string message = "a";
5712 vector<uint8_t> iv;
5713 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5714 EXPECT_EQ(8U, ciphertext.size());
5715 EXPECT_NE(ciphertext, message);
5716 ++ciphertext[ciphertext.size() / 2];
5717
5718 auto begin_params = AuthorizationSetBuilder()
5719 .BlockMode(BlockMode::CBC)
5720 .Padding(PaddingMode::PKCS7)
5721 .Authorization(TAG_NONCE, iv);
5722 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5723 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005724 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005725 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5726}
5727
5728/*
5729 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5730 *
5731 * Verifies that 3DES CBC works with many different input sizes.
5732 */
5733TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5734 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5735 .TripleDesEncryptionKey(168)
5736 .BlockMode(BlockMode::CBC)
5737 .Authorization(TAG_NO_AUTH_REQUIRED)
5738 .Padding(PaddingMode::NONE)));
5739
5740 int increment = 7;
5741 string message(240, 'a');
5742 AuthorizationSet input_params =
5743 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5744 AuthorizationSet output_params;
5745 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5746
5747 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005748 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005749 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005750 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5751 EXPECT_EQ(message.size(), ciphertext.size());
5752
5753 // Move TAG_NONCE into input_params
5754 input_params = output_params;
5755 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5756 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5757 output_params.Clear();
5758
5759 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5760 string plaintext;
5761 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005762 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005763 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5764 EXPECT_EQ(ciphertext.size(), plaintext.size());
5765 EXPECT_EQ(message, plaintext);
5766}
5767
5768INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5769
5770typedef KeyMintAidlTestBase MaxOperationsTest;
5771
5772/*
5773 * MaxOperationsTest.TestLimitAes
5774 *
5775 * Verifies that the max uses per boot tag works correctly with AES keys.
5776 */
5777TEST_P(MaxOperationsTest, TestLimitAes) {
5778 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5779
5780 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5781 .Authorization(TAG_NO_AUTH_REQUIRED)
5782 .AesEncryptionKey(128)
5783 .EcbMode()
5784 .Padding(PaddingMode::NONE)
5785 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5786
5787 string message = "1234567890123456";
5788
5789 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5790
5791 EncryptMessage(message, params);
5792 EncryptMessage(message, params);
5793 EncryptMessage(message, params);
5794
5795 // Fourth time should fail.
5796 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5797}
5798
5799/*
Qi Wud22ec842020-11-26 13:27:53 +08005800 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005801 *
5802 * Verifies that the max uses per boot tag works correctly with RSA keys.
5803 */
5804TEST_P(MaxOperationsTest, TestLimitRsa) {
5805 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5806
5807 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5808 .Authorization(TAG_NO_AUTH_REQUIRED)
5809 .RsaSigningKey(1024, 65537)
5810 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005811 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5812 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005813
5814 string message = "1234567890123456";
5815
5816 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5817
5818 SignMessage(message, params);
5819 SignMessage(message, params);
5820 SignMessage(message, params);
5821
5822 // Fourth time should fail.
5823 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5824}
5825
5826INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5827
Qi Wud22ec842020-11-26 13:27:53 +08005828typedef KeyMintAidlTestBase UsageCountLimitTest;
5829
5830/*
Qi Wubeefae42021-01-28 23:16:37 +08005831 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005832 *
Qi Wubeefae42021-01-28 23:16:37 +08005833 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005834 */
Qi Wubeefae42021-01-28 23:16:37 +08005835TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005836 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5837
5838 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5839 .Authorization(TAG_NO_AUTH_REQUIRED)
5840 .AesEncryptionKey(128)
5841 .EcbMode()
5842 .Padding(PaddingMode::NONE)
5843 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5844
5845 // Check the usage count limit tag appears in the authorizations.
5846 AuthorizationSet auths;
5847 for (auto& entry : key_characteristics_) {
5848 auths.push_back(AuthorizationSet(entry.authorizations));
5849 }
5850 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5851 << "key usage count limit " << 1U << " missing";
5852
5853 string message = "1234567890123456";
5854 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5855
Qi Wubeefae42021-01-28 23:16:37 +08005856 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5857 AuthorizationSet keystore_auths =
5858 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5859
Qi Wud22ec842020-11-26 13:27:53 +08005860 // First usage of AES key should work.
5861 EncryptMessage(message, params);
5862
Qi Wud22ec842020-11-26 13:27:53 +08005863 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5864 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5865 // must be invalidated from secure storage (such as RPMB partition).
5866 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5867 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005868 // Usage count limit tag is enforced by keystore, keymint does nothing.
5869 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005870 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5871 }
5872}
5873
5874/*
Qi Wubeefae42021-01-28 23:16:37 +08005875 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005876 *
Qi Wubeefae42021-01-28 23:16:37 +08005877 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005878 */
Qi Wubeefae42021-01-28 23:16:37 +08005879TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5880 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5881
5882 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5883 .Authorization(TAG_NO_AUTH_REQUIRED)
5884 .AesEncryptionKey(128)
5885 .EcbMode()
5886 .Padding(PaddingMode::NONE)
5887 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5888
5889 // Check the usage count limit tag appears in the authorizations.
5890 AuthorizationSet auths;
5891 for (auto& entry : key_characteristics_) {
5892 auths.push_back(AuthorizationSet(entry.authorizations));
5893 }
5894 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5895 << "key usage count limit " << 3U << " missing";
5896
5897 string message = "1234567890123456";
5898 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5899
5900 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5901 AuthorizationSet keystore_auths =
5902 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5903
5904 EncryptMessage(message, params);
5905 EncryptMessage(message, params);
5906 EncryptMessage(message, params);
5907
5908 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5909 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5910 // must be invalidated from secure storage (such as RPMB partition).
5911 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5912 } else {
5913 // Usage count limit tag is enforced by keystore, keymint does nothing.
5914 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5915 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5916 }
5917}
5918
5919/*
5920 * UsageCountLimitTest.TestSingleUseRsa
5921 *
5922 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5923 */
5924TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005925 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5926
5927 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5928 .Authorization(TAG_NO_AUTH_REQUIRED)
5929 .RsaSigningKey(1024, 65537)
5930 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005931 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5932 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005933
5934 // Check the usage count limit tag appears in the authorizations.
5935 AuthorizationSet auths;
5936 for (auto& entry : key_characteristics_) {
5937 auths.push_back(AuthorizationSet(entry.authorizations));
5938 }
5939 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5940 << "key usage count limit " << 1U << " missing";
5941
5942 string message = "1234567890123456";
5943 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5944
Qi Wubeefae42021-01-28 23:16:37 +08005945 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5946 AuthorizationSet keystore_auths =
5947 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5948
Qi Wud22ec842020-11-26 13:27:53 +08005949 // First usage of RSA key should work.
5950 SignMessage(message, params);
5951
Qi Wud22ec842020-11-26 13:27:53 +08005952 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5953 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5954 // must be invalidated from secure storage (such as RPMB partition).
5955 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5956 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005957 // Usage count limit tag is enforced by keystore, keymint does nothing.
5958 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5959 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5960 }
5961}
5962
5963/*
5964 * UsageCountLimitTest.TestLimitUseRsa
5965 *
5966 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5967 */
5968TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
5969 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5970
5971 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5972 .Authorization(TAG_NO_AUTH_REQUIRED)
5973 .RsaSigningKey(1024, 65537)
5974 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005975 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
5976 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08005977
5978 // Check the usage count limit tag appears in the authorizations.
5979 AuthorizationSet auths;
5980 for (auto& entry : key_characteristics_) {
5981 auths.push_back(AuthorizationSet(entry.authorizations));
5982 }
5983 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5984 << "key usage count limit " << 3U << " missing";
5985
5986 string message = "1234567890123456";
5987 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5988
5989 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5990 AuthorizationSet keystore_auths =
5991 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5992
5993 SignMessage(message, params);
5994 SignMessage(message, params);
5995 SignMessage(message, params);
5996
5997 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5998 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5999 // must be invalidated from secure storage (such as RPMB partition).
6000 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6001 } else {
6002 // Usage count limit tag is enforced by keystore, keymint does nothing.
6003 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006004 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6005 }
6006}
6007
Qi Wu8e727f72021-02-11 02:49:33 +08006008/*
6009 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6010 *
6011 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6012 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6013 * in hardware.
6014 */
6015TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
6016 if (SecLevel() == SecurityLevel::STRONGBOX) return;
6017
6018 auto error = GenerateKey(AuthorizationSetBuilder()
6019 .RsaSigningKey(2048, 65537)
6020 .Digest(Digest::NONE)
6021 .Padding(PaddingMode::NONE)
6022 .Authorization(TAG_NO_AUTH_REQUIRED)
6023 .Authorization(TAG_ROLLBACK_RESISTANCE)
6024 .SetDefaultValidity());
6025 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6026
6027 if (error == ErrorCode::OK) {
6028 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6029 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6030 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6031 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6032
6033 // The KeyMint should also enforce single use key in hardware when it supports rollback
6034 // resistance.
6035 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6036 .Authorization(TAG_NO_AUTH_REQUIRED)
6037 .RsaSigningKey(1024, 65537)
6038 .NoDigestOrPadding()
6039 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6040 .SetDefaultValidity()));
6041
6042 // Check the usage count limit tag appears in the hardware authorizations.
6043 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6044 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6045 << "key usage count limit " << 1U << " missing";
6046
6047 string message = "1234567890123456";
6048 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6049
6050 // First usage of RSA key should work.
6051 SignMessage(message, params);
6052
6053 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6054 // must be invalidated from secure storage (such as RPMB partition).
6055 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6056 }
6057}
6058
Qi Wud22ec842020-11-26 13:27:53 +08006059INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6060
David Drysdale7de9feb2021-03-05 14:56:19 +00006061typedef KeyMintAidlTestBase GetHardwareInfoTest;
6062
6063TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6064 // Retrieving hardware info should give the same result each time.
6065 KeyMintHardwareInfo info;
6066 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6067 KeyMintHardwareInfo info2;
6068 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6069 EXPECT_EQ(info, info2);
6070}
6071
6072INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6073
Selene Huang31ab4042020-04-29 04:22:39 -07006074typedef KeyMintAidlTestBase AddEntropyTest;
6075
6076/*
6077 * AddEntropyTest.AddEntropy
6078 *
6079 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6080 * is actually added.
6081 */
6082TEST_P(AddEntropyTest, AddEntropy) {
6083 string data = "foo";
6084 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6085}
6086
6087/*
6088 * AddEntropyTest.AddEmptyEntropy
6089 *
6090 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6091 */
6092TEST_P(AddEntropyTest, AddEmptyEntropy) {
6093 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6094}
6095
6096/*
6097 * AddEntropyTest.AddLargeEntropy
6098 *
6099 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6100 */
6101TEST_P(AddEntropyTest, AddLargeEntropy) {
6102 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6103}
6104
David Drysdalebb3d85e2021-04-13 11:15:51 +01006105/*
6106 * AddEntropyTest.AddTooLargeEntropy
6107 *
6108 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6109 */
6110TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6111 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6112 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6113}
6114
Selene Huang31ab4042020-04-29 04:22:39 -07006115INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6116
Selene Huang31ab4042020-04-29 04:22:39 -07006117typedef KeyMintAidlTestBase KeyDeletionTest;
6118
6119/**
6120 * KeyDeletionTest.DeleteKey
6121 *
6122 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6123 * valid key blob.
6124 */
6125TEST_P(KeyDeletionTest, DeleteKey) {
6126 auto error = GenerateKey(AuthorizationSetBuilder()
6127 .RsaSigningKey(2048, 65537)
6128 .Digest(Digest::NONE)
6129 .Padding(PaddingMode::NONE)
6130 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006131 .Authorization(TAG_ROLLBACK_RESISTANCE)
6132 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006133 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6134
6135 // Delete must work if rollback protection is implemented
6136 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006137 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006138 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6139
6140 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
6141
6142 string message = "12345678901234567890123456789012";
6143 AuthorizationSet begin_out_params;
6144 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6145 Begin(KeyPurpose::SIGN, key_blob_,
6146 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6147 &begin_out_params));
6148 AbortIfNeeded();
6149 key_blob_ = AidlBuf();
6150 }
6151}
6152
6153/**
6154 * KeyDeletionTest.DeleteInvalidKey
6155 *
6156 * This test checks that the HAL excepts invalid key blobs..
6157 */
6158TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6159 // Generate key just to check if rollback protection is implemented
6160 auto error = GenerateKey(AuthorizationSetBuilder()
6161 .RsaSigningKey(2048, 65537)
6162 .Digest(Digest::NONE)
6163 .Padding(PaddingMode::NONE)
6164 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006165 .Authorization(TAG_ROLLBACK_RESISTANCE)
6166 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006167 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6168
6169 // Delete must work if rollback protection is implemented
6170 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006171 AuthorizationSet enforced(SecLevelAuthorizations());
6172 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006173
6174 // Delete the key we don't care about the result at this point.
6175 DeleteKey();
6176
6177 // Now create an invalid key blob and delete it.
6178 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
6179
6180 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6181 }
6182}
6183
6184/**
6185 * KeyDeletionTest.DeleteAllKeys
6186 *
6187 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6188 *
6189 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6190 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6191 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6192 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6193 * credentials stored in Keystore/Keymint.
6194 */
6195TEST_P(KeyDeletionTest, DeleteAllKeys) {
6196 if (!arm_deleteAllKeys) return;
6197 auto error = GenerateKey(AuthorizationSetBuilder()
6198 .RsaSigningKey(2048, 65537)
6199 .Digest(Digest::NONE)
6200 .Padding(PaddingMode::NONE)
6201 .Authorization(TAG_NO_AUTH_REQUIRED)
6202 .Authorization(TAG_ROLLBACK_RESISTANCE));
6203 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6204
6205 // Delete must work if rollback protection is implemented
6206 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006207 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006208 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6209
6210 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
6211
6212 string message = "12345678901234567890123456789012";
6213 AuthorizationSet begin_out_params;
6214
6215 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6216 Begin(KeyPurpose::SIGN, key_blob_,
6217 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6218 &begin_out_params));
6219 AbortIfNeeded();
6220 key_blob_ = AidlBuf();
6221 }
6222}
6223
6224INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6225
David Drysdaled2cc8c22021-04-15 13:29:45 +01006226typedef KeyMintAidlTestBase KeyUpgradeTest;
6227
6228/**
6229 * KeyUpgradeTest.UpgradeInvalidKey
6230 *
6231 * This test checks that the HAL excepts invalid key blobs..
6232 */
6233TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6234 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6235
6236 std::vector<uint8_t> new_blob;
6237 Status result = keymint_->upgradeKey(key_blob,
6238 AuthorizationSetBuilder()
6239 .Authorization(TAG_APPLICATION_ID, "clientid")
6240 .Authorization(TAG_APPLICATION_DATA, "appdata")
6241 .vector_data(),
6242 &new_blob);
6243 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6244}
6245
6246INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6247
Selene Huang31ab4042020-04-29 04:22:39 -07006248using UpgradeKeyTest = KeyMintAidlTestBase;
6249
6250/*
6251 * UpgradeKeyTest.UpgradeKey
6252 *
6253 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6254 */
6255TEST_P(UpgradeKeyTest, UpgradeKey) {
6256 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6257 .AesEncryptionKey(128)
6258 .Padding(PaddingMode::NONE)
6259 .Authorization(TAG_NO_AUTH_REQUIRED)));
6260
6261 auto result = UpgradeKey(key_blob_);
6262
6263 // Key doesn't need upgrading. Should get okay, but no new key blob.
6264 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6265}
6266
6267INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6268
6269using ClearOperationsTest = KeyMintAidlTestBase;
6270
6271/*
6272 * ClearSlotsTest.TooManyOperations
6273 *
6274 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6275 * operations are started without being finished or aborted. Also verifies
6276 * that aborting the operations clears the operations.
6277 *
6278 */
6279TEST_P(ClearOperationsTest, TooManyOperations) {
6280 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6281 .Authorization(TAG_NO_AUTH_REQUIRED)
6282 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006283 .Padding(PaddingMode::NONE)
6284 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006285
6286 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6287 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006288 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006289 AuthorizationSet out_params;
6290 ErrorCode result;
6291 size_t i;
6292
6293 for (i = 0; i < max_operations; i++) {
6294 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6295 if (ErrorCode::OK != result) {
6296 break;
6297 }
6298 }
6299 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6300 // Try again just in case there's a weird overflow bug
6301 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6302 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6303 for (size_t j = 0; j < i; j++) {
6304 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6305 << "Aboort failed for i = " << j << std::endl;
6306 }
6307 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6308 AbortIfNeeded();
6309}
6310
6311INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6312
6313typedef KeyMintAidlTestBase TransportLimitTest;
6314
6315/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006316 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006317 *
6318 * Verifies that passing input data to finish succeeds as expected.
6319 */
6320TEST_P(TransportLimitTest, LargeFinishInput) {
6321 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6322 .Authorization(TAG_NO_AUTH_REQUIRED)
6323 .AesEncryptionKey(128)
6324 .BlockMode(BlockMode::ECB)
6325 .Padding(PaddingMode::NONE)));
6326
6327 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6328 auto cipher_params =
6329 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6330
6331 AuthorizationSet out_params;
6332 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6333
6334 string plain_message = std::string(1 << msg_size, 'x');
6335 string encrypted_message;
6336 auto rc = Finish(plain_message, &encrypted_message);
6337
6338 EXPECT_EQ(ErrorCode::OK, rc);
6339 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6340 << "Encrypt finish returned OK, but did not consume all of the given input";
6341 cipher_params.push_back(out_params);
6342
6343 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6344
6345 string decrypted_message;
6346 rc = Finish(encrypted_message, &decrypted_message);
6347 EXPECT_EQ(ErrorCode::OK, rc);
6348 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6349 << "Decrypt finish returned OK, did not consume all of the given input";
6350 }
6351}
6352
6353INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6354
David Zeuthene0c40892021-01-08 12:54:11 -05006355typedef KeyMintAidlTestBase KeyAgreementTest;
6356
6357int CurveToOpenSslCurveName(EcCurve curve) {
6358 switch (curve) {
6359 case EcCurve::P_224:
6360 return NID_secp224r1;
6361 case EcCurve::P_256:
6362 return NID_X9_62_prime256v1;
6363 case EcCurve::P_384:
6364 return NID_secp384r1;
6365 case EcCurve::P_521:
6366 return NID_secp521r1;
6367 }
6368}
6369
6370/*
6371 * KeyAgreementTest.Ecdh
6372 *
6373 * Verifies that ECDH works for all curves
6374 */
6375TEST_P(KeyAgreementTest, Ecdh) {
6376 // Because it's possible to use this API with keys on different curves, we
6377 // check all N^2 combinations where N is the number of supported
6378 // curves.
6379 //
6380 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6381 // lot more curves we can be smart about things and just pick |otherCurve| so
6382 // it's not |curve| and that way we end up with only 2*N runs
6383 //
6384 for (auto curve : ValidCurves()) {
6385 for (auto localCurve : ValidCurves()) {
6386 // Generate EC key locally (with access to private key material)
6387 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6388 int curveName = CurveToOpenSslCurveName(localCurve);
6389 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6390 ASSERT_NE(group, nullptr);
6391 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6392 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6393 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6394 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6395
6396 // Get encoded form of the public part of the locally generated key...
6397 unsigned char* p = nullptr;
6398 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6399 ASSERT_GT(encodedPublicKeySize, 0);
6400 vector<uint8_t> encodedPublicKey(
6401 reinterpret_cast<const uint8_t*>(p),
6402 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6403 OPENSSL_free(p);
6404
6405 // Generate EC key in KeyMint (only access to public key material)
6406 vector<uint8_t> challenge = {0x41, 0x42};
6407 EXPECT_EQ(
6408 ErrorCode::OK,
6409 GenerateKey(AuthorizationSetBuilder()
6410 .Authorization(TAG_NO_AUTH_REQUIRED)
6411 .Authorization(TAG_EC_CURVE, curve)
6412 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6413 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6414 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006415 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6416 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006417 << "Failed to generate key";
6418 ASSERT_GT(cert_chain_.size(), 0);
6419 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6420 ASSERT_NE(kmKeyCert, nullptr);
6421 // Check that keyAgreement (bit 4) is set in KeyUsage
6422 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6423 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6424 ASSERT_NE(kmPkey, nullptr);
6425 if (dump_Attestations) {
6426 for (size_t n = 0; n < cert_chain_.size(); n++) {
6427 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6428 }
6429 }
6430
6431 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6432 if (curve != localCurve) {
6433 // If the keys are using different curves KeyMint should fail with
6434 // ErrorCode:INVALID_ARGUMENT. Check that.
6435 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6436 string ZabFromKeyMintStr;
6437 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6438 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6439 &ZabFromKeyMintStr));
6440
6441 } else {
6442 // Otherwise if the keys are using the same curve, it should work.
6443 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6444 string ZabFromKeyMintStr;
6445 EXPECT_EQ(ErrorCode::OK,
6446 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6447 &ZabFromKeyMintStr));
6448 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6449
6450 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6451 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6452 ASSERT_NE(ctx, nullptr);
6453 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6454 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6455 size_t ZabFromTestLen = 0;
6456 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6457 vector<uint8_t> ZabFromTest;
6458 ZabFromTest.resize(ZabFromTestLen);
6459 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6460
6461 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6462 }
6463
6464 CheckedDeleteKey();
6465 }
6466 }
6467}
6468
6469INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6470
David Drysdaled2cc8c22021-04-15 13:29:45 +01006471using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6472
6473// This is a problematic test, as it can render the device under test permanently unusable.
6474// Re-enable and run at your own risk.
6475TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6476 auto result = DestroyAttestationIds();
6477 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6478}
6479
6480INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6481
Shawn Willdend659c7c2021-02-19 14:51:51 -07006482using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006483
6484TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
6485 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6486 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6487
6488 CheckedDeleteKey(&aesKeyData.blob);
6489 CheckedDeleteKey(&hmacKeyData.blob);
6490 CheckedDeleteKey(&rsaKeyData.blob);
6491 CheckedDeleteKey(&ecdsaKeyData.blob);
6492}
6493
David Drysdaled2cc8c22021-04-15 13:29:45 +01006494// 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 +00006495// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6496// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6497// early boot, so you'll have to reboot between runs.
6498TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6499 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6500 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6501 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6502 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6503 EXPECT_TRUE(
6504 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6505 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6506 EXPECT_TRUE(
6507 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6508
6509 // Should be able to use keys, since early boot has not ended
6510 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6511 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6512 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6513 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6514
6515 // End early boot
6516 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6517 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6518
6519 // Should not be able to use already-created keys.
6520 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6521 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6522 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6523 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6524
6525 CheckedDeleteKey(&aesKeyData.blob);
6526 CheckedDeleteKey(&hmacKeyData.blob);
6527 CheckedDeleteKey(&rsaKeyData.blob);
6528 CheckedDeleteKey(&ecdsaKeyData.blob);
6529
6530 // Should not be able to create new keys
6531 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6532 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6533
6534 CheckedDeleteKey(&aesKeyData.blob);
6535 CheckedDeleteKey(&hmacKeyData.blob);
6536 CheckedDeleteKey(&rsaKeyData.blob);
6537 CheckedDeleteKey(&ecdsaKeyData.blob);
6538}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006539
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006540INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6541
Shawn Willdend659c7c2021-02-19 14:51:51 -07006542using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006543
6544// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6545// between runs... and on most test devices there are no enrolled credentials so it can't be
6546// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6547// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6548// a manual test process, which includes unlocking between runs, which is why it's included here.
6549// Well, that and the fact that it's the only test we can do without also making calls into the
6550// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6551// implications might be, so that may or may not be a solution.
6552TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6553 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6554 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6555
6556 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6557 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6558 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6559 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6560
6561 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006562 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006563 ASSERT_EQ(ErrorCode::OK, rc);
6564 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6565 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6566 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6567 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6568
6569 CheckedDeleteKey(&aesKeyData.blob);
6570 CheckedDeleteKey(&hmacKeyData.blob);
6571 CheckedDeleteKey(&rsaKeyData.blob);
6572 CheckedDeleteKey(&ecdsaKeyData.blob);
6573}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006574
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006575INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6576
Janis Danisevskis24c04702020-12-16 18:28:39 -08006577} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006578
6579int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006580 std::cout << "Testing ";
6581 auto halInstances =
6582 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6583 std::cout << "HAL instances:\n";
6584 for (auto& entry : halInstances) {
6585 std::cout << " " << entry << '\n';
6586 }
6587
Selene Huang31ab4042020-04-29 04:22:39 -07006588 ::testing::InitGoogleTest(&argc, argv);
6589 for (int i = 1; i < argc; ++i) {
6590 if (argv[i][0] == '-') {
6591 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006592 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6593 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006594 }
6595 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006596 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6597 dump_Attestations = true;
6598 } else {
6599 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006600 }
David Drysdalebb3d85e2021-04-13 11:15:51 +01006601 // TODO(drysdale): Remove this flag when available KeyMint devices comply with spec
6602 if (std::string(argv[i]) == "--check_patchLevels") {
6603 aidl::android::hardware::security::keymint::test::check_patchLevels = true;
6604 }
Selene Huang31ab4042020-04-29 04:22:39 -07006605 }
6606 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006607 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006608}